Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions docs/architecture/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
130 changes: 130 additions & 0 deletions internal/tags/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -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
}
24 changes: 22 additions & 2 deletions rules/str/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:]
Expand All @@ -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)
}
Expand Down Expand Up @@ -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++ {
Expand Down
6 changes: 6 additions & 0 deletions rules/str/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]",
Expand Down Expand Up @@ -57,6 +58,11 @@ func TestIsURL(t *testing.T) {
"https://[nope]",
"https://-bad-.com",
"https://us er@example.com",
"a://\"@example.com",
"https://us<er@example.com",
"https://u%zz@example.com",
"https://[fe80::1%25en0]/",
"https://[::0%00]",
})
}

Expand Down
126 changes: 126 additions & 0 deletions rules/str/fuzz_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
2 changes: 2 additions & 0 deletions rules/str/testdata/fuzz/FuzzEncodings/3d825909dc6e0868
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
string("000000000000")
2 changes: 2 additions & 0 deletions rules/str/testdata/fuzz/FuzzURL/7a80fe3d7de1bd2d
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
string("A://[::0%00]")
2 changes: 2 additions & 0 deletions rules/str/testdata/fuzz/FuzzURL/a2ea43ad5d19c060
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
string("A://\"@0")
13 changes: 13 additions & 0 deletions scripts/fuzz.sh
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion shared/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading