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/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/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 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/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 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]) + } + } + }) +}