From 28940564c6e82faa50264adef5ad343541c990a8 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 12:43:58 +0300 Subject: [PATCH 1/3] fix(str): URL rejects invalid userinfo and the zones of IPv6 hosts The userinfo was checked only for whitespace, A://"@0 was valid; it is the userinfo of RFC 3986 now. A zone of an IPv6 host, [::0%00], was accepted by netip; url.Parse needs it escaped, the zones aren't allowed. Both were found by fuzzing against url.Parse. --- rules/str/format.go | 24 ++++++++++++++++++++++-- rules/str/format_test.go | 6 ++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/rules/str/format.go b/rules/str/format.go index 3d2ae65..e59226a 100644 --- a/rules/str/format.go +++ b/rules/str/format.go @@ -24,7 +24,7 @@ func isURL(s string) bool { authority, tail = rest[:end], rest[end:] } if i := strings.LastIndexByte(authority, '@'); i >= 0 { - if !isURLText(authority[:i]) { + if !isUserinfo(authority[:i]) { return false } authority = authority[i+1:] @@ -38,7 +38,8 @@ func isURL(s string) bool { return false } addr, err := netip.ParseAddr(host[1 : len(host)-1]) - return err == nil && addr.Is6() && isURLText(tail) + // the zones of the addresses aren't allowed, url.Parse needs them escaped as %25 + return err == nil && addr.Is6() && addr.Zone() == "" && isURLText(tail) } return (isHostname(host) || isIPv4(host)) && isURLText(tail) } @@ -82,6 +83,25 @@ func isPort(s string) bool { return n <= 65535 } +// isUserinfo reports whether s is the userinfo of RFC 3986: unreserved characters, sub-delims, ":" and percent +// escapes, like url.Parse accepts, "@" too. +func isUserinfo(s string) bool { + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case isASCIILetter(c) || isASCIIDigit(c) || strings.IndexByte("-._:~!$&'()*+,;=@", c) >= 0: + case c == '%': + if i+2 >= len(s) || !isHex(s[i+1]) || !isHex(s[i+2]) { + return false + } + i += 2 + default: + return false + } + } + return true +} + // isURLText reports whether s has no whitespace or control characters and its percent escapes are valid. func isURLText(s string) bool { for i := 0; i < len(s); i++ { diff --git a/rules/str/format_test.go b/rules/str/format_test.go index 27e6930..e4cc0b7 100644 --- a/rules/str/format_test.go +++ b/rules/str/format_test.go @@ -29,6 +29,7 @@ func TestIsURL(t *testing.T) { "https://example.com/path/to?q=1&b=2#frag", "https://example.com:8443/path", "ftp://user:pass@files.example.com/dir", + "https://a%20b:p~$&'()*+,;=@example.com", "https://127.0.0.1:80", "https://[::1]:8080/x", "https://[2001:db8::1]", @@ -57,6 +58,11 @@ func TestIsURL(t *testing.T) { "https://[nope]", "https://-bad-.com", "https://us er@example.com", + "a://\"@example.com", + "https://us Date: Mon, 19 Oct 2026 12:43:58 +0300 Subject: [PATCH 2/3] test: fuzz the formats, the reading of the fields and the tags The formats of strings are checked against the parsers of the standard library and the patterns of their JSON Schema, the reading of the fields by the offsets of fmap against the fields themselves, and any tag either configures the rules or panics with its error, the rules never panic. The inputs found by fuzzing are kept in testdata. --- internal/tags/fuzz_test.go | 130 ++++++++++++++++++ rules/str/fuzz_test.go | 126 +++++++++++++++++ .../fuzz/FuzzEncodings/3d825909dc6e0868 | 2 + .../testdata/fuzz/FuzzURL/7a80fe3d7de1bd2d | 2 + .../testdata/fuzz/FuzzURL/a2ea43ad5d19c060 | 2 + shared/field_test.go | 2 +- shared/fuzz_test.go | 75 ++++++++++ 7 files changed, 338 insertions(+), 1 deletion(-) create mode 100644 internal/tags/fuzz_test.go create mode 100644 rules/str/fuzz_test.go create mode 100644 rules/str/testdata/fuzz/FuzzEncodings/3d825909dc6e0868 create mode 100644 rules/str/testdata/fuzz/FuzzURL/7a80fe3d7de1bd2d create mode 100644 rules/str/testdata/fuzz/FuzzURL/a2ea43ad5d19c060 create mode 100644 shared/fuzz_test.go diff --git a/internal/tags/fuzz_test.go b/internal/tags/fuzz_test.go new file mode 100644 index 0000000..cd0c04a --- /dev/null +++ b/internal/tags/fuzz_test.go @@ -0,0 +1,130 @@ +package tags_test + +import ( + "context" + "reflect" + "strings" + "testing" + "time" + + "github.com/insei/fmap/v3" + + "github.com/insei/valigo/internal/helper" + "github.com/insei/valigo/internal/tags" + "github.com/insei/valigo/internal/zero" + "github.com/insei/valigo/shared" +) + +type fuzzItem struct { + Name string `validate:"required"` +} + +// fuzzFields are the fields of the struct of the fuzzed tag, every field but X has the tag. +var fuzzFields = []reflect.StructField{ + {Name: "S", Type: reflect.TypeFor[string]()}, + {Name: "P", Type: reflect.TypeFor[*string]()}, + {Name: "N", Type: reflect.TypeFor[int]()}, + {Name: "U", Type: reflect.TypeFor[*uint8]()}, + {Name: "F", Type: reflect.TypeFor[float64]()}, + {Name: "B", Type: reflect.TypeFor[bool]()}, + {Name: "T", Type: reflect.TypeFor[time.Time]()}, + {Name: "L", Type: reflect.TypeFor[[]string]()}, + {Name: "Q", Type: reflect.TypeFor[[]*int]()}, + {Name: "M", Type: reflect.TypeFor[map[string]int]()}, + {Name: "I", Type: reflect.TypeFor[[]fuzzItem]()}, + {Name: "R", Type: reflect.TypeFor[*fuzzItem]()}, +} + +// FuzzTags checks that a tag either configures the rules or panics with the error of the tag in Configure, +// and that the rules validate any value without panics. +func FuzzTags(f *testing.F) { + for _, tag := range []string{ + "required", "omitempty,min=1,max=3", "dive,required", "email|url", "required_with=X", "required_if=X a", + "gt=1,lt=5", "eqfield=X", "nefield=X", "dive,keys,alpha,endkeys,min=1", "len=2", "unique", "oneof=a b", + "datetime=2006-01-02", "containsany=0x2C", "required_without_all=X N", "keys", "dive,dive", "|", "=", ",,", + } { + f.Add(tag, "value", int64(3)) + } + f.Fuzz(func(t *testing.T, tag, s string, n int64) { + for _, field := range fuzzFields { + field.Tag = reflect.StructTag(`validate:"` + strings.NewReplacer(`"`, "", `\`, "").Replace(tag) + `"`) + typ := reflect.StructOf([]reflect.StructField{field, {Name: "X", Type: reflect.TypeFor[string]()}}) + fns, ok := configure(t, typ) + if !ok { + continue + } + for _, obj := range []reflect.Value{reflect.New(typ), filled(typ, s, n)} { + for _, fn := range fns { + fn(context.Background(), helper.New(), obj.Interface(), nil) + } + } + } + }) +} + +// configure applies the tags of the struct type, false if they panic with the error of a tag. +func configure(t *testing.T, typ reflect.Type) (fns []shared.ValidationFn, ok bool) { + defer func() { + if r := recover(); r != nil { + if msg, isString := r.(string); !isString || !strings.HasPrefix(msg, "valigo: tag ") { + t.Fatalf("%s: a panic of Configure isn't the error of a tag: %v", typ, r) + } + ok = false + } + }() + model := reflect.New(typ).Interface() + zero.Must(model) + storage, err := fmap.GetFrom(model) + if err != nil { + t.Fatal(err) + } + tags.Apply(tags.Struct{Storage: storage, Model: model, Helper: helper.New(), + Fields: func(ptr any) fmap.Field { + field, err := storage.GetFieldByPtr(model, ptr) + if err != nil { + t.Fatalf("%s: %v", typ, err) + } + return field + }, + Add: func(fn shared.ValidationFn) { fns = append(fns, fn) }, + }, "validate") + return fns, true +} + +// filled returns a value of the struct type with the fields made of s and n. +func filled(typ reflect.Type, s string, n int64) reflect.Value { + v := reflect.New(typ) + e := v.Elem() + for i := range e.NumField() { + f := e.Field(i) + switch f.Interface().(type) { + case string: + f.SetString(s) + case *string: + f.Set(reflect.ValueOf(&s)) + case int: + f.SetInt(n) + case *uint8: + u := uint8(n) + f.Set(reflect.ValueOf(&u)) + case float64: + f.SetFloat(float64(n) / 3) + case bool: + f.SetBool(n%2 == 0) + case time.Time: + f.Set(reflect.ValueOf(time.Unix(n, 0))) + case []string: + f.Set(reflect.ValueOf([]string{s, "", s})) + case []*int: + k := int(n) + f.Set(reflect.ValueOf([]*int{&k, nil})) + case map[string]int: + f.Set(reflect.ValueOf(map[string]int{s: int(n), "": 0})) + case []fuzzItem: + f.Set(reflect.ValueOf([]fuzzItem{{Name: s}, {}})) + case *fuzzItem: + f.Set(reflect.ValueOf(&fuzzItem{Name: s})) + } + } + return v +} diff --git a/rules/str/fuzz_test.go b/rules/str/fuzz_test.go new file mode 100644 index 0000000..fa39c3f --- /dev/null +++ b/rules/str/fuzz_test.go @@ -0,0 +1,126 @@ +package str + +import ( + "encoding/base64" + "net" + "net/url" + "regexp" + "strings" + "testing" +) + +// The formats are checked against the parsers of the standard library and the regexps of their definitions, +// the patterns are the patterns of JSON Schema of the rules, so the schema describes the same strings. +var ( + uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + hostnamePattern = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`) + e164Pattern = regexp.MustCompile(`^\+[1-9][0-9]{1,14}$`) + hexColorPattern = regexp.MustCompile(`^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$`) + alnumPattern = regexp.MustCompile(`^[a-zA-Z0-9]+$`) + alphaPattern = regexp.MustCompile(`^[a-zA-Z]+$`) + digitsPattern = regexp.MustCompile(`^[0-9]+$`) + numericPattern = regexp.MustCompile(`^[-+]?[0-9]+(\.[0-9]+)?$`) + hexPattern = regexp.MustCompile(`^(0[xX])?[0-9a-fA-F]+$`) +) + +var fuzzSeeds = []string{ + "", "a", "A1", "0x1f", "-1.5", "+3", "1.", "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "example.com", "-a.com", "a..b", + "+14155550123", "+0123", "#fff", "#ffff1", "QUJD", "QUJ=", "QQ==", "QQ", "a-_b", "00:1a:2b:3c:4d:5e", "001a.2b3c.4d5e", + "00-1a-2b-3c-4d-5e-6f-70", "https://example.com/x?y=1", "http://[::1]:80", "79927398713", "4111 1111 1111 1111", "é", +} + +func seed(f *testing.F) { + for _, s := range fuzzSeeds { + f.Add(s) + } +} + +func FuzzPatterns(f *testing.F) { + seed(f) + f.Fuzz(func(t *testing.T, s string) { + for _, c := range []struct { + name string + fn func(string) bool + pattern *regexp.Regexp + }{ + {"uuid", isUUID, uuidPattern}, {"e164", isE164, e164Pattern}, {"hex color", isHexColor, hexColorPattern}, + {"alphanumeric", isAlphanumeric, alnumPattern}, {"alpha", isAlpha, alphaPattern}, {"digits", isDigits, digitsPattern}, + {"numeric", isNumeric, numericPattern}, {"hexadecimal", isHexadecimal, hexPattern}, + } { + if got, want := c.fn(s), c.pattern.MatchString(s); got != want { + t.Errorf("%s(%q) = %v, the pattern %v", c.name, s, got, want) + } + } + if got, want := isHostname(s), len(s) <= 253 && hostnamePattern.MatchString(s); got != want { + t.Errorf("hostname(%q) = %v, want %v", s, got, want) + } + }) +} + +func FuzzEncodings(f *testing.F) { + seed(f) + f.Fuzz(func(t *testing.T, s string) { + // the decoders of the standard library skip new lines + lines := strings.ContainsAny(s, "\r\n") + _, err := base64.StdEncoding.DecodeString(s) + if got, want := isBase64(s), s != "" && !lines && err == nil; got != want { + t.Errorf("base64(%q) = %v, want %v", s, got, want) + } + _, padded := base64.URLEncoding.DecodeString(s) + _, raw := base64.RawURLEncoding.DecodeString(s) + if got, want := isBase64URL(s), s != "" && !lines && (padded == nil || raw == nil); got != want { + t.Errorf("base64url(%q) = %v, want %v", s, got, want) + } + // MAC accepts the forms with separators, net.ParseMAC also 12 hex digits without them + mac, err := net.ParseMAC(s) + separated := strings.ContainsAny(s, ":-.") + if got, want := isMAC(s), err == nil && separated && (len(mac) == 6 || len(mac) == 8); got != want { + t.Errorf("mac(%q) = %v, want %v", s, got, want) + } + }) +} + +// luhnOf is the reference Luhn algorithm of the digits of s. +func luhnOf(digits string) bool { + sum := 0 + for i := range len(digits) { + d := int(digits[len(digits)-1-i] - '0') + if i%2 == 1 { + d *= 2 + if d > 9 { + d -= 9 + } + } + sum += d + } + return sum%10 == 0 +} + +func FuzzChecksums(f *testing.F) { + seed(f) + f.Fuzz(func(t *testing.T, s string) { + if got, want := isLuhn(s), len(s) >= 2 && digitsPattern.MatchString(s) && luhnOf(s); got != want { + t.Errorf("luhn(%q) = %v, want %v", s, got, want) + } + if isCreditCard(s) { + digits := strings.NewReplacer(" ", "", "-", "").Replace(s) + if !digitsPattern.MatchString(digits) || len(digits) < 12 || len(digits) > 19 || !luhnOf(digits) { + t.Errorf("credit card(%q) is valid with the digits %q", s, digits) + } + } + }) +} + +func FuzzURL(f *testing.F) { + seed(f) + f.Fuzz(func(t *testing.T, s string) { + if !isURL(s) { + return + } + // a valid URL is parsed by the standard library with a scheme and a host + u, err := url.Parse(s) + if err != nil || u.Scheme == "" || u.Host == "" { + t.Errorf("url(%q) is valid, url.Parse: %v, %#v", s, err, u) + } + }) +} diff --git a/rules/str/testdata/fuzz/FuzzEncodings/3d825909dc6e0868 b/rules/str/testdata/fuzz/FuzzEncodings/3d825909dc6e0868 new file mode 100644 index 0000000..99b4729 --- /dev/null +++ b/rules/str/testdata/fuzz/FuzzEncodings/3d825909dc6e0868 @@ -0,0 +1,2 @@ +go test fuzz v1 +string("000000000000") diff --git a/rules/str/testdata/fuzz/FuzzURL/7a80fe3d7de1bd2d b/rules/str/testdata/fuzz/FuzzURL/7a80fe3d7de1bd2d new file mode 100644 index 0000000..cd0ba67 --- /dev/null +++ b/rules/str/testdata/fuzz/FuzzURL/7a80fe3d7de1bd2d @@ -0,0 +1,2 @@ +go test fuzz v1 +string("A://[::0%00]") diff --git a/rules/str/testdata/fuzz/FuzzURL/a2ea43ad5d19c060 b/rules/str/testdata/fuzz/FuzzURL/a2ea43ad5d19c060 new file mode 100644 index 0000000..8ece8f0 --- /dev/null +++ b/rules/str/testdata/fuzz/FuzzURL/a2ea43ad5d19c060 @@ -0,0 +1,2 @@ +go test fuzz v1 +string("A://\"@0") diff --git a/shared/field_test.go b/shared/field_test.go index b7b9e65..ec44c59 100644 --- a/shared/field_test.go +++ b/shared/field_test.go @@ -85,7 +85,7 @@ func (r *rules) validateFull(obj any) []Error { return errs } -func sampleField(t *testing.T, path string) fmap.Field { +func sampleField(t testing.TB, path string) fmap.Field { t.Helper() fields, err := fmap.Get[sample]() require.NoError(t, err) diff --git a/shared/fuzz_test.go b/shared/fuzz_test.go new file mode 100644 index 0000000..13cac4f --- /dev/null +++ b/shared/fuzz_test.go @@ -0,0 +1,75 @@ +package shared + +import ( + "context" + "testing" +) + +// FuzzFieldAccess checks the reading of the fields by the offsets of fmap against the fields themselves: +// nested structs stored by pointer, nil pointers, slices of pointers with nil elements. +func FuzzFieldAccess(f *testing.F) { + f.Add("text", uint8(3), uint8(0xff)) + f.Add("", uint8(0), uint8(0)) + f.Add("é", uint8(7), uint8(5)) + text, textPtr := sampleField(f, "Text"), sampleField(f, "TextPtr") + innerText, innerPtr := sampleField(f, "Inner.Text"), sampleField(f, "Inner.TextPtr") + f.Fuzz(func(t *testing.T, s string, n, flags uint8) { + obj := &sample{Text: s, Num: int(n)} + if flags&1 != 0 { + obj.TextPtr = &s + } + if flags&2 != 0 { + obj.Inner = &inner{Text: s + "i"} + if flags&4 != 0 { + obj.Inner.TextPtr = &obj.Text + } + } + for i := range int(n % 8) { + obj.Texts = append(obj.Texts, s) + if (int(flags)>>(i%8))&1 != 0 { + obj.TextPtrs = append(obj.TextPtrs, &obj.Text) + } else { + obj.TextPtrs = append(obj.TextPtrs, nil) + } + } + + if p := Getter[string](text)(obj); p != &obj.Text { + t.Errorf("Text: %p, want %p", p, &obj.Text) + } + if p := Getter[string](textPtr)(obj); p != obj.TextPtr { + t.Errorf("TextPtr: %p, want %p", p, obj.TextPtr) + } + var wantInner, wantInnerPtr *string + if obj.Inner != nil { + wantInner, wantInnerPtr = &obj.Inner.Text, obj.Inner.TextPtr + } + if p := Getter[string](innerText)(obj); p != wantInner { + t.Errorf("Inner.Text: %p, want %p", p, wantInner) + } + if p := Getter[string](innerPtr)(obj); p != wantInnerPtr { + t.Errorf("Inner.TextPtr: %p, want %p", p, wantInnerPtr) + } + if got := InStruct(innerText)(obj); got != (obj.Inner != nil) { + t.Errorf("InStruct: %v", got) + } + + var r rules + var got []*string + NewSliceFieldConfigurator[string](sampleField(t, "TextPtrs"), pathHelper{}, sampleFields, r.add, nil). + Custom(func(_ context.Context, _ *FieldCustomHelper, e Elems[string]) []Error { + for _, p := range e.All() { + got = append(got, p) + } + return nil + }) + r.validate(obj) + if len(got) != len(obj.TextPtrs) { + t.Fatalf("elements: %d, want %d", len(got), len(obj.TextPtrs)) + } + for i, p := range got { + if p != obj.TextPtrs[i] { + t.Errorf("element %d: %p, want %p", i, p, obj.TextPtrs[i]) + } + } + }) +} From f9458977ba79cf09b4a7ecc6335f84be29a717fd Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 12:43:58 +0300 Subject: [PATCH 3/3] ci: fuzz every target for 30 seconds --- .github/workflows/go.yml | 13 +++++++++++++ docs/architecture/index.md | 1 + scripts/fuzz.sh | 13 +++++++++++++ 3 files changed, 27 insertions(+) create mode 100755 scripts/fuzz.sh diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index ebb2f90..a1b0724 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -79,6 +79,19 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} files: ${{ steps.modules.outputs.coverage }} + fuzz: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: Set up Go + uses: actions/setup-go@v7 + with: + go-version: '1.27' + + - name: Fuzz the formats, the reading of the fields and the tags + run: scripts/fuzz.sh + examples: runs-on: ubuntu-latest steps: diff --git a/docs/architecture/index.md b/docs/architecture/index.md index ac7679f..d0f19d2 100644 --- a/docs/architecture/index.md +++ b/docs/architecture/index.md @@ -54,4 +54,5 @@ The rules append their errors to one pooled buffer of the validation, and `Valid - Commits follow [Conventional Commits](https://www.conventionalcommits.org/), the changelog is generated from them by git-cliff. - `go test -race ./...` and the examples modules run in CI. Programs in the documentation and in the skill for AI agents are built and run by `scripts/check-examples.sh`. +- Fuzz tests check the formats of strings against the parsers of the standard library and the patterns of their JSON Schema, the reading of the fields by the offsets against the fields themselves, and that any tag either configures the rules or panics with its error. `scripts/fuzz.sh` runs every target for `FUZZTIME`, 30s in CI; a failing input is saved in `testdata/fuzz` of the package and stays a regression test. - A new rule of an existing type is a method of its configurator over `Check` or `Required`, with a locale key in `translator/locales/*/data.yaml`. diff --git a/scripts/fuzz.sh b/scripts/fuzz.sh new file mode 100755 index 0000000..c5c4e19 --- /dev/null +++ b/scripts/fuzz.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Runs every fuzz target of the core for FUZZTIME (30s by default). A failing input is saved in testdata/fuzz +# of the package, commit it with the fix: go test runs it as a regression test. +set -euo pipefail + +cd "$(dirname "$0")/.." +time=${FUZZTIME:-30s} +for pkg in ./rules/str ./shared ./internal/tags; do + for target in $(go test -list '^Fuzz' "$pkg" | grep '^Fuzz'); do + echo "$pkg $target" + go test -run '^$' -fuzz "^$target\$" -fuzztime "$time" "$pkg" + done +done