edgeguard: the hard tier and probe catalogue, matched on path structure
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
5 files changed,
+1,102
−0
internal/edgeguard/catalogue.go+352 −0internal/edgeguard/catalogue.txt+82 −0internal/edgeguard/catalogue_test.go+132 −0internal/edgeguard/match.go+270 −0internal/edgeguard/match_test.go+266 −0
diff --git a/internal/edgeguard/catalogue.go b/internal/edgeguard/catalogue.go| new file mode 100644 |
| index 000000000..5496bcd87 |
| --- /dev/null |
| +++ b/internal/edgeguard/catalogue.go |
| @@ -0,0 +1,352 @@ |
| +// Package edgeguard is the edge's catalogue of requests that no real visitor |
| +// makes, and the matcher that recognises them. |
| +// |
| +// The catalogue is a text file embedded in the binary. Every rule matches on |
| +// the structure of the request path (whole segments, an extension on the last |
| +// segment, a whole path or a leading path) or on the start of a query value. |
| +// None of them looks for a word inside a path, because a misfire on a real |
| +// visitor costs more than a missed probe: "/help/vat-in-the-european-union" |
| +// must stay a help page. |
| +package edgeguard |
| + |
| +import ( |
| + _ "embed" |
| + "fmt" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// Mode says what the edge does with a request that matched a rule. |
| +type Mode uint8 |
| + |
| +const ( |
| + // ModeWatch records the match and lets the request through. |
| + ModeWatch Mode = iota |
| + // ModeBlock refuses the request. |
| + ModeBlock |
| + // ModeBurst counts the match toward a per-client burst limit instead of |
| + // acting on a single request (an admin page is a normal thing to visit |
| + // once). |
| + ModeBurst |
| +) |
| + |
| +func (m Mode) String() string { |
| + switch m { |
| + case ModeWatch: |
| + return "watch" |
| + case ModeBlock: |
| + return "block" |
| + case ModeBurst: |
| + return "burst" |
| + } |
| + return "unknown" |
| +} |
| + |
| +// Rule is one row of the catalogue. ID is "<tier>.<group>.<name>", for |
| +// example "hard.secrets.env". |
| +type Rule struct { |
| + ID string |
| + Group string |
| + Tier reqrec.Tier |
| + Mode Mode |
| + |
| + kind kind |
| + pattern string |
| +} |
| + |
| +// Hit is a rule that matched, with the text that matched it. Fragment is a |
| +// path segment, a cleaned path or, when FromQuery is set, the value of the |
| +// query parameter called QueryName. Path fragments are lower case. |
| +type Hit struct { |
| + Rule *Rule |
| + Fragment string |
| + FromQuery bool |
| + QueryName string |
| +} |
| + |
| +type kind uint8 |
| + |
| +const ( |
| + kindExact kind = iota + 1 |
| + kindPrefix |
| + kindSegment |
| + kindSegglob |
| + kindExt |
| + kindSegseq |
| + kindQparam |
| + kindDotdot |
| +) |
| + |
| +var kindNames = map[string]kind{ |
| + "exact": kindExact, |
| + "prefix": kindPrefix, |
| + "segment": kindSegment, |
| + "segglob": kindSegglob, |
| + "ext": kindExt, |
| + "segseq": kindSegseq, |
| + "qparam": kindQparam, |
| + "dotdot": kindDotdot, |
| +} |
| + |
| +var modeNames = map[string]Mode{"watch": ModeWatch, "block": ModeBlock, "burst": ModeBurst} |
| + |
| +//go:embed catalogue.txt |
| +var catalogueData []byte |
| + |
| +var ( |
| + // Version is the catalogue's "# version N" line. It is bumped whenever a |
| + // rule is added, removed or changed, so a log line can say which |
| + // catalogue produced it. |
| + Version int |
| + |
| + rules []Rule |
| + idx index |
| +) |
| + |
| +func init() { |
| + rs, v, err := parseCatalogue(catalogueData) |
| + if err != nil { |
| + panic(err) |
| + } |
| + ix, err := buildIndex(rs) |
| + if err != nil { |
| + panic(err) |
| + } |
| + rules, Version, idx = rs, v, ix |
| +} |
| + |
| +// Rules returns the catalogue in file order. The caller may keep and modify |
| +// the slice. |
| +func Rules() []Rule { return slices.Clone(rules) } |
| + |
| +// RuleByHash finds the rule whose ID hashes to h under reqrec.RuleHash, which |
| +// is how a reference code names a rule. |
| +func RuleByHash(h uint32) (*Rule, bool) { |
| + i, ok := idx.byHash[h] |
| + if !ok { |
| + return nil, false |
| + } |
| + return &rules[i], true |
| +} |
| + |
| +// parseCatalogue reads the catalogue format: one rule per line with the |
| +// columns "tier group name kind pattern mode", "#" comments, blank lines, and |
| +// a "# version N" comment. It returns the rules in file order and the version. |
| +// Every error names the line that caused it. |
| +func parseCatalogue(data []byte) ([]Rule, int, error) { |
| + var ( |
| + out []Rule |
| + version int |
| + haveVer bool |
| + seen = map[string]bool{} |
| + sawProbe bool |
| + lineNumber int |
| + ) |
| + for _, line := range strings.Split(string(data), "\n") { |
| + lineNumber++ |
| + line = strings.TrimSpace(line) |
| + if line == "" { |
| + continue |
| + } |
| + if strings.HasPrefix(line, "#") { |
| + if rest, ok := strings.CutPrefix(line, "# version "); ok && !haveVer { |
| + n, err := strconv.Atoi(strings.TrimSpace(rest)) |
| + if err != nil || n < 1 { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: bad version %q", lineNumber, rest) |
| + } |
| + version, haveVer = n, true |
| + } |
| + continue |
| + } |
| + f := strings.Fields(line) |
| + if len(f) != 6 { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: want 6 columns (tier group name kind pattern mode), got %d", lineNumber, len(f)) |
| + } |
| + tierName, group, name, kindName, pattern, modeName := f[0], f[1], f[2], f[3], f[4], f[5] |
| + var tier reqrec.Tier |
| + switch tierName { |
| + case "hard": |
| + tier = reqrec.TierHard |
| + if sawProbe { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: hard rule after a probe rule (Check relies on hard rules coming first)", lineNumber) |
| + } |
| + case "probe": |
| + tier = reqrec.TierProbe |
| + sawProbe = true |
| + default: |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: unknown tier %q", lineNumber, tierName) |
| + } |
| + if !isName(group) || !isName(name) { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: group %q and name %q must match [a-z0-9-]+", lineNumber, group, name) |
| + } |
| + k, ok := kindNames[kindName] |
| + if !ok { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: unknown kind %q", lineNumber, kindName) |
| + } |
| + mode, ok := modeNames[modeName] |
| + if !ok { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: unknown mode %q", lineNumber, modeName) |
| + } |
| + if err := checkPattern(k, pattern); err != nil { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: %v", lineNumber, err) |
| + } |
| + id := tierName + "." + group + "." + name |
| + if seen[id] { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line %d: duplicate rule id %q", lineNumber, id) |
| + } |
| + seen[id] = true |
| + out = append(out, Rule{ID: id, Group: group, Tier: tier, Mode: mode, kind: k, pattern: pattern}) |
| + } |
| + if !haveVer { |
| + return nil, 0, fmt.Errorf("edgeguard catalogue line 1: missing \"# version N\" line") |
| + } |
| + return out, version, nil |
| +} |
| + |
| +func isName(s string) bool { |
| + if s == "" { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + c := s[i] |
| + if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// checkPattern holds a pattern to what its kind can match. The matcher works |
| +// on lower-cased, cleaned paths, so a pattern that could never be equal to |
| +// one is a mistake in the file, not a rule that quietly never fires. |
| +func checkPattern(k kind, p string) error { |
| + for i := 0; i < len(p); i++ { |
| + if p[i] >= 'A' && p[i] <= 'Z' { |
| + return fmt.Errorf("pattern %q must be lower case", p) |
| + } |
| + } |
| + switch k { |
| + case kindExact, kindPrefix: |
| + if len(p) < 2 || p[0] != '/' || p[len(p)-1] == '/' { |
| + return fmt.Errorf("pattern %q must start with / and not end with /", p) |
| + } |
| + case kindSegment, kindExt: |
| + if strings.Contains(p, "/") || p == ".." || p == "." { |
| + return fmt.Errorf("pattern %q must be a single path segment", p) |
| + } |
| + case kindSegglob: |
| + if strings.Count(p, "*") != 1 || strings.Contains(p, "/") { |
| + return fmt.Errorf("segglob pattern %q must be one segment holding exactly one *", p) |
| + } |
| + case kindSegseq: |
| + if strings.HasPrefix(p, "/") || strings.HasSuffix(p, "/") || !strings.Contains(p, "/") { |
| + return fmt.Errorf("segseq pattern %q must be two or more segments without a leading or trailing /", p) |
| + } |
| + case kindQparam: |
| + if name, _, ok := strings.Cut(p, "="); !ok || name == "" { |
| + return fmt.Errorf("qparam pattern %q must be name=valueprefix", p) |
| + } |
| + case kindDotdot: |
| + if p != "-" { |
| + return fmt.Errorf("dotdot pattern must be -, got %q", p) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// index is the catalogue arranged for lookup. Every entry holds the rule's |
| +// position in file order, and lists are in ascending position, so the matcher |
| +// can take the earliest hit across all kinds and get what a scan down the |
| +// file would give. |
| +type index struct { |
| + exact map[string][]int |
| + segment map[string][]int |
| + // prefix is keyed by the pattern's first segment, so a request path |
| + // needs one map lookup rather than one comparison per prefix rule. |
| + prefix map[string][]prefixEntry |
| + globs []globEntry |
| + exts []extEntry |
| + segseqs []seqEntry |
| + qparams []qparamEntry |
| + dotdots []int |
| + |
| + // minSeg and maxSeg bound the length of any segment rule's pattern, so |
| + // most segments skip the map lookup. |
| + minSeg, maxSeg int |
| + |
| + hardEnd int |
| + byHash map[uint32]int |
| +} |
| + |
| +type prefixEntry struct { |
| + pattern string |
| + pos int |
| +} |
| + |
| +type globEntry struct { |
| + prefix, suffix string |
| + pos int |
| +} |
| + |
| +type extEntry struct { |
| + suffix string |
| + pos int |
| +} |
| + |
| +type seqEntry struct { |
| + segs string |
| + pos int |
| +} |
| + |
| +type qparamEntry struct { |
| + name, valuePrefix string |
| + pos int |
| +} |
| + |
| +func buildIndex(rs []Rule) (index, error) { |
| + ix := index{ |
| + exact: map[string][]int{}, |
| + segment: map[string][]int{}, |
| + prefix: map[string][]prefixEntry{}, |
| + byHash: map[uint32]int{}, |
| + minSeg: 1 << 30, |
| + } |
| + for i := range rs { |
| + r := &rs[i] |
| + if r.Tier == reqrec.TierHard { |
| + ix.hardEnd = i + 1 |
| + } |
| + h := reqrec.RuleHash(r.ID) |
| + if other, dup := ix.byHash[h]; dup { |
| + return index{}, fmt.Errorf("edgeguard catalogue: %q and %q share rule hash %08x", r.ID, rs[other].ID, h) |
| + } |
| + ix.byHash[h] = i |
| + switch r.kind { |
| + case kindExact: |
| + ix.exact[r.pattern] = append(ix.exact[r.pattern], i) |
| + case kindPrefix: |
| + first, _, _ := strings.Cut(r.pattern[1:], "/") |
| + ix.prefix[first] = append(ix.prefix[first], prefixEntry{r.pattern, i}) |
| + case kindSegment: |
| + ix.segment[r.pattern] = append(ix.segment[r.pattern], i) |
| + ix.minSeg = min(ix.minSeg, len(r.pattern)) |
| + ix.maxSeg = max(ix.maxSeg, len(r.pattern)) |
| + case kindSegglob: |
| + pre, suf, _ := strings.Cut(r.pattern, "*") |
| + ix.globs = append(ix.globs, globEntry{pre, suf, i}) |
| + case kindExt: |
| + ix.exts = append(ix.exts, extEntry{r.pattern, i}) |
| + case kindSegseq: |
| + ix.segseqs = append(ix.segseqs, seqEntry{r.pattern, i}) |
| + case kindQparam: |
| + name, val, _ := strings.Cut(r.pattern, "=") |
| + ix.qparams = append(ix.qparams, qparamEntry{name, val, i}) |
| + case kindDotdot: |
| + ix.dotdots = append(ix.dotdots, i) |
| + } |
| + } |
| + return ix, nil |
| +} |
diff --git a/internal/edgeguard/catalogue.txt b/internal/edgeguard/catalogue.txt| new file mode 100644 |
| index 000000000..0b7cc81f0 |
| --- /dev/null |
| +++ b/internal/edgeguard/catalogue.txt |
| @@ -0,0 +1,82 @@ |
| +# version 1 |
| +# tier group name kind pattern mode |
| +hard traversal dotdot dotdot - watch |
| +hard traversal proc-self segseq proc/self watch |
| +hard traversal vite-fs segment @fs watch |
| +hard secrets env segment .env watch |
| +hard secrets env-variant segglob .env.* watch |
| +hard secrets git segment .git watch |
| +hard secrets git-credentials segment .git-credentials watch |
| +hard secrets svn segment .svn watch |
| +hard secrets hg segment .hg watch |
| +hard secrets aws segment .aws watch |
| +hard secrets ssh segment .ssh watch |
| +hard secrets docker segment .docker watch |
| +hard secrets kube segment .kube watch |
| +hard secrets npmrc segment .npmrc watch |
| +hard secrets pypirc segment .pypirc watch |
| +hard secrets netrc segment .netrc watch |
| +hard secrets htpasswd segment .htpasswd watch |
| +hard keys id-rsa segment id_rsa watch |
| +hard keys id-dsa segment id_dsa watch |
| +hard keys id-ecdsa segment id_ecdsa watch |
| +hard keys id-ed25519 segment id_ed25519 watch |
| +hard keys credentials-json segment credentials.json watch |
| +hard keys gcp-credentials segment gcp-credentials.json watch |
| +hard keys firebase-admin segglob firebase-adminsdk*.json watch |
| +hard dumps db-sql exact /db.sql watch |
| +hard dumps dump-sql exact /dump.sql watch |
| +hard dumps backup-sql exact /backup.sql watch |
| +hard dumps database-sql exact /database.sql watch |
| +hard source php-save ext .php.save watch |
| +hard source php-bak ext .php.bak watch |
| +hard source php-old ext .php.old watch |
| +hard source php-swp ext .php.swp watch |
| +hard source php-tilde ext .php~ watch |
| +probe wordpress wp-login exact /wp-login.php watch |
| +probe wordpress xmlrpc exact /xmlrpc.php watch |
| +probe wordpress wp-links-opml exact /wp-links-opml.php watch |
| +probe wordpress wp-admin prefix /wp-admin watch |
| +probe wordpress wp-json prefix /wp-json watch |
| +probe wordpress site-wp-json prefix /site/wp-json watch |
| +probe wordpress news-wp-json prefix /news/wp-json watch |
| +probe wordpress cms-wp-json prefix /cms/wp-json watch |
| +probe wordpress blog-wp-json prefix /blog/wp-json watch |
| +probe wordpress wp-wp-json prefix /wp/wp-json watch |
| +probe wordpress wordpress-dir prefix /wordpress watch |
| +probe wordpress press-wp-json prefix /press/wp-json watch |
| +probe phpframework phpunit prefix /vendor/phpunit watch |
| +probe phpframework composer-json exact /vendor/composer/installed.json watch |
| +probe phpframework ignition prefix /_ignition watch |
| +probe phpframework telescope prefix /telescope watch |
| +probe phpframework debugbar prefix /_debugbar watch |
| +probe phpframework profiler-phpinfo prefix /_profiler/phpinfo watch |
| +probe phpframework thinkphp qparam s=/index/\think watch |
| +probe phpmyadmin phpmyadmin prefix /phpmyadmin watch |
| +probe phpmyadmin pma prefix /pma watch |
| +probe php php ext .php watch |
| +probe java actuator prefix /actuator watch |
| +probe java action ext .action watch |
| +probe java do ext .do watch |
| +probe java jsp ext .jsp watch |
| +probe cgi cgi-bin prefix /cgi-bin watch |
| +probe cgi setup-cgi exact /setup.cgi watch |
| +probe cgi hnap1 exact /hnap1 watch |
| +probe cgi gponform prefix /gponform watch |
| +probe status server-status prefix /server-status watch |
| +probe status server-info prefix /server-info watch |
| +probe metadata meta-data prefix /latest/meta-data watch |
| +probe devconfig docker-compose exact /docker-compose.yml watch |
| +probe devconfig dockerfile exact /dockerfile watch |
| +probe devconfig gitlab-ci exact /.gitlab-ci.yml watch |
| +probe dumps sql ext .sql watch |
| +probe dumps sql-gz ext .sql.gz watch |
| +probe dumps sqlite ext .sqlite watch |
| +probe dumps sqlite3 ext .sqlite3 watch |
| +probe dumps db ext .db watch |
| +probe dumps bak ext .bak watch |
| +probe admin admin exact /admin burst |
| +probe admin admin-login exact /admin/login burst |
| +probe admin admin-settings exact /admin/settings burst |
| +probe admin admin-dashboard exact /admin/dashboard burst |
| +probe admin administrator prefix /administrator burst |
diff --git a/internal/edgeguard/catalogue_test.go b/internal/edgeguard/catalogue_test.go| new file mode 100644 |
| index 000000000..8a7ac0c9d |
| --- /dev/null |
| +++ b/internal/edgeguard/catalogue_test.go |
| @@ -0,0 +1,132 @@ |
| +package edgeguard |
| + |
| +import ( |
| + "fmt" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +func TestCatalogueParses(t *testing.T) { |
| + rs := Rules() |
| + if len(rs) == 0 { |
| + t.Fatal("no rules") |
| + } |
| + if Version != 1 { |
| + t.Fatalf("Version = %d, want 1", Version) |
| + } |
| + seen := map[string]bool{} |
| + sawProbe := false |
| + for _, r := range rs { |
| + parts := strings.Split(r.ID, ".") |
| + if len(parts) != 3 || parts[0] != r.Tier.String() || parts[1] != r.Group || parts[2] == "" { |
| + t.Errorf("rule %q (tier %s, group %s) is not tier.group.name", r.ID, r.Tier, r.Group) |
| + } |
| + if seen[r.ID] { |
| + t.Errorf("duplicate id %q", r.ID) |
| + } |
| + seen[r.ID] = true |
| + switch r.Tier { |
| + case reqrec.TierHard: |
| + if sawProbe { |
| + t.Errorf("hard rule %q comes after a probe rule", r.ID) |
| + } |
| + case reqrec.TierProbe: |
| + sawProbe = true |
| + default: |
| + t.Errorf("rule %q has tier %s", r.ID, r.Tier) |
| + } |
| + } |
| +} |
| + |
| +func TestCatalogueRuleHashesUnique(t *testing.T) { |
| + seen := map[uint32]string{} |
| + for _, r := range Rules() { |
| + h := reqrec.RuleHash(r.ID) |
| + if other, dup := seen[h]; dup { |
| + t.Errorf("%q and %q share hash %08x", r.ID, other, h) |
| + } |
| + seen[h] = r.ID |
| + got, ok := RuleByHash(h) |
| + if !ok || got.ID != r.ID { |
| + t.Errorf("RuleByHash(%08x) = %v, %v; want %q", h, got, ok, r.ID) |
| + } |
| + } |
| +} |
| + |
| +func TestCatalogueAdminIsBurst(t *testing.T) { |
| + admin := 0 |
| + for _, r := range Rules() { |
| + if r.Group == "admin" { |
| + admin++ |
| + if r.Mode != ModeBurst { |
| + t.Errorf("%s has mode %s, want burst", r.ID, r.Mode) |
| + } |
| + } else if r.Mode == ModeBurst { |
| + t.Errorf("%s is burst but not in group admin", r.ID) |
| + } |
| + } |
| + if admin == 0 { |
| + t.Error("no admin rules") |
| + } |
| +} |
| + |
| +func TestModeString(t *testing.T) { |
| + for m, want := range map[Mode]string{ModeWatch: "watch", ModeBlock: "block", ModeBurst: "burst"} { |
| + if got := m.String(); got != want { |
| + t.Errorf("Mode(%d).String() = %q, want %q", m, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestParseRejects(t *testing.T) { |
| + const ok = "hard a b segment .env watch\n" |
| + cases := []struct { |
| + name string |
| + in string |
| + line int |
| + }{ |
| + {"upper-case pattern", "# version 1\nhard a b segment .ENV watch\n", 2}, |
| + {"unknown kind", "# version 1\n\nhard a b regex .env watch\n", 3}, |
| + {"unknown mode", "# version 1\nhard a b segment .env ban\n", 2}, |
| + {"unknown tier", "# version 1\ntenant a b segment .env watch\n", 2}, |
| + {"duplicate id", "# version 1\n" + ok + "# again\n" + ok, 4}, |
| + {"segglob without star", "# version 1\nhard a b segglob .env watch\n", 2}, |
| + {"segglob with two stars", "# version 1\nhard a b segglob .env.*.* watch\n", 2}, |
| + {"qparam without equals", "# version 1\nhard a b qparam s watch\n", 2}, |
| + {"qparam without name", "# version 1\nhard a b qparam =x watch\n", 2}, |
| + {"missing columns", "# version 1\nhard a b segment .env\n", 2}, |
| + {"extra columns", "# version 1\nhard a b segment .env watch more\n", 2}, |
| + {"bad name", "# version 1\nhard a B_c segment .env watch\n", 2}, |
| + {"exact without slash", "# version 1\nhard a b exact db.sql watch\n", 2}, |
| + {"prefix with trailing slash", "# version 1\nhard a b prefix /pma/ watch\n", 2}, |
| + {"segment holding a slash", "# version 1\nhard a b segment a/b watch\n", 2}, |
| + {"dotdot with a pattern", "# version 1\nhard a b dotdot .. watch\n", 2}, |
| + {"hard after probe", "# version 1\nprobe a b segment .env watch\nhard a c segment .git watch\n", 3}, |
| + {"missing version", ok, 1}, |
| + {"version not a number", "# version x\n" + ok, 1}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + _, _, err := parseCatalogue([]byte(c.in)) |
| + if err == nil { |
| + t.Fatal("parseCatalogue accepted it") |
| + } |
| + want := fmt.Sprintf("line %d", c.line) |
| + if !strings.Contains(err.Error(), want) { |
| + t.Fatalf("error %q does not name %q", err, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestParseAccepts(t *testing.T) { |
| + rs, v, err := parseCatalogue([]byte("# version 7\n\n# note\nhard a b segment .env watch\nprobe a c qparam s=/x\\y burst\n")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if v != 7 || len(rs) != 2 || rs[0].ID != "hard.a.b" || rs[1].Mode != ModeBurst { |
| + t.Fatalf("got version %d, rules %+v", v, rs) |
| + } |
| +} |
diff --git a/internal/edgeguard/match.go b/internal/edgeguard/match.go| new file mode 100644 |
| index 000000000..566037153 |
| --- /dev/null |
| +++ b/internal/edgeguard/match.go |
| @@ -0,0 +1,270 @@ |
| +package edgeguard |
| + |
| +import ( |
| + "net/url" |
| + "path" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// Check reports the first catalogue rule the request matches. urlPath is |
| +// r.URL.Path, which has already been decoded once; rawQuery is r.URL.RawQuery. |
| +// Hard rules are tried before probe rules and each tier in file order, so the |
| +// answer is the same as scanning the catalogue from the top. |
| +// |
| +// The path is read in a few forms so that dressing a probe up does not hide |
| +// it. Case and "\" are folded, ";params" on a segment are dropped, and when |
| +// the path holds a "%" it is decoded once more and read again. Rules other |
| +// than dotdot then look at the cleaned path, but dotdot looks at the segments |
| +// before cleaning, because "/static/../.env" is the request, not "/.env". |
| +// |
| +// A request under /.well-known/ is exempt from every path rule except dotdot: |
| +// that tree is where certificate issuers and security contacts look, and some |
| +// of what they fetch has names the rules would otherwise catch. |
| +// |
| +// An ordinary path allocates nothing. |
| +func Check(urlPath, rawQuery string) (Hit, bool) { |
| + return check(urlPath, rawQuery, 0, len(rules)) |
| +} |
| + |
| +// CheckTier is Check limited to the rules of one tier. |
| +func CheckTier(urlPath, rawQuery string, tier reqrec.Tier) (Hit, bool) { |
| + switch tier { |
| + case reqrec.TierHard: |
| + return check(urlPath, rawQuery, 0, idx.hardEnd) |
| + case reqrec.TierProbe: |
| + return check(urlPath, rawQuery, idx.hardEnd, len(rules)) |
| + } |
| + return Hit{}, false |
| +} |
| + |
| +// best is the earliest matching rule so far. pos is the rule's place in file |
| +// order, or the end of the range being checked while nothing has matched. |
| +type best struct { |
| + lo, pos int |
| + fragment string |
| + query string |
| + fromQ bool |
| +} |
| + |
| +// offer records a match when it is in range and earlier than the best so far. |
| +func (b *best) offer(pos int, fragment string) { |
| + if pos >= b.lo && pos < b.pos { |
| + b.pos, b.fragment, b.fromQ, b.query = pos, fragment, false, "" |
| + } |
| +} |
| + |
| +// offerFirst offers the first position at or after lo from an ascending list. |
| +func (b *best) offerFirst(positions []int, fragment string) { |
| + for _, p := range positions { |
| + if p >= b.lo { |
| + b.offer(p, fragment) |
| + return |
| + } |
| + } |
| +} |
| + |
| +func check(urlPath, rawQuery string, lo, hi int) (Hit, bool) { |
| + b := best{lo: lo, pos: hi} |
| + scanPath(urlPath, &b) |
| + if strings.IndexByte(urlPath, '%') >= 0 { |
| + if dec, err := url.PathUnescape(urlPath); err == nil && dec != urlPath { |
| + scanPath(dec, &b) |
| + } |
| + } |
| + if rawQuery != "" { |
| + scanQuery(rawQuery, &b) |
| + } |
| + if b.pos >= hi { |
| + return Hit{}, false |
| + } |
| + return Hit{Rule: &rules[b.pos], Fragment: b.fragment, FromQuery: b.fromQ, QueryName: b.query}, true |
| +} |
| + |
| +// scanPath offers every path rule that matches one form of the path. |
| +func scanPath(p string, b *best) { |
| + p = fold(p) |
| + if strings.IndexByte(p, ';') >= 0 { |
| + p = stripParams(p) |
| + } |
| + if len(idx.dotdots) > 0 && hasDotDot(p) { |
| + b.offerFirst(idx.dotdots, "..") |
| + } |
| + if p == "" || p[0] != '/' { |
| + p = "/" + p |
| + } |
| + c := path.Clean(p) |
| + rest := c[1:] |
| + if first, _, _ := strings.Cut(rest, "/"); first == ".well-known" { |
| + return |
| + } |
| + |
| + if pos, ok := idx.exact[c]; ok { |
| + b.offerFirst(pos, c) |
| + } |
| + if rest != "" { |
| + first, _, _ := strings.Cut(rest, "/") |
| + for _, e := range idx.prefix[first] { |
| + if isPrefixPath(c, e.pattern) { |
| + b.offer(e.pos, c) |
| + break |
| + } |
| + } |
| + } |
| + last := "" |
| + for rest != "" { |
| + var seg string |
| + seg, rest, _ = strings.Cut(rest, "/") |
| + last = seg |
| + if len(seg) >= idx.minSeg && len(seg) <= idx.maxSeg { |
| + if pos, ok := idx.segment[seg]; ok { |
| + b.offerFirst(pos, seg) |
| + } |
| + } |
| + for _, g := range idx.globs { |
| + if g.pos >= b.lo && g.pos < b.pos && len(seg) >= len(g.prefix)+len(g.suffix) && |
| + strings.HasPrefix(seg, g.prefix) && strings.HasSuffix(seg, g.suffix) { |
| + b.offer(g.pos, seg) |
| + } |
| + } |
| + } |
| + for _, e := range idx.exts { |
| + if e.pos >= b.lo && e.pos < b.pos && len(last) > len(e.suffix) && strings.HasSuffix(last, e.suffix) { |
| + b.offer(e.pos, last) |
| + } |
| + } |
| + for _, e := range idx.segseqs { |
| + if e.pos >= b.lo && e.pos < b.pos && hasSegments(c, e.segs) { |
| + b.offer(e.pos, c) |
| + } |
| + } |
| +} |
| + |
| +// isPrefixPath reports whether the cleaned path is the pattern or lies under |
| +// it. "/wp-json" covers "/wp-json/wp/v2" but not "/wp-jsonx". |
| +func isPrefixPath(c, pattern string) bool { |
| + return strings.HasPrefix(c, pattern) && (len(c) == len(pattern) || c[len(pattern)] == '/') |
| +} |
| + |
| +// hasSegments reports whether segs, a run of whole segments such as |
| +// "proc/self", appears in the cleaned path. |
| +func hasSegments(c, segs string) bool { |
| + for from := 0; ; { |
| + i := strings.Index(c[from:], segs) |
| + if i < 0 { |
| + return false |
| + } |
| + start := from + i |
| + end := start + len(segs) |
| + if c[start-1] == '/' && (end == len(c) || c[end] == '/') { |
| + return true |
| + } |
| + from = start + 1 |
| + } |
| +} |
| + |
| +// hasDotDot reports whether any segment of the path is "..". |
| +func hasDotDot(p string) bool { |
| + for p != "" { |
| + var seg string |
| + seg, p, _ = strings.Cut(p, "/") |
| + if seg == ".." { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// fold lower-cases ASCII and turns "\" into "/", returning s itself when it |
| +// needs neither. Only ASCII is folded: the patterns are ASCII, and full |
| +// Unicode folding would let a Kelvin sign pass for a "k". |
| +func fold(s string) string { |
| + for i := 0; i < len(s); i++ { |
| + if c := s[i]; c >= 'A' && c <= 'Z' || c == '\\' { |
| + return foldFrom(s, i) |
| + } |
| + } |
| + return s |
| +} |
| + |
| +func foldFrom(s string, i int) string { |
| + var sb strings.Builder |
| + sb.Grow(len(s)) |
| + sb.WriteString(s[:i]) |
| + for ; i < len(s); i++ { |
| + switch c := s[i]; { |
| + case c >= 'A' && c <= 'Z': |
| + sb.WriteByte(c + 'a' - 'A') |
| + case c == '\\': |
| + sb.WriteByte('/') |
| + default: |
| + sb.WriteByte(c) |
| + } |
| + } |
| + return sb.String() |
| +} |
| + |
| +// stripParams drops ";..." from the end of every segment, the way servlet |
| +// containers read "/..;/" and "/.env;x=1". |
| +func stripParams(p string) string { |
| + var sb strings.Builder |
| + sb.Grow(len(p)) |
| + for { |
| + seg, rest, more := strings.Cut(p, "/") |
| + if i := strings.IndexByte(seg, ';'); i >= 0 { |
| + seg = seg[:i] |
| + } |
| + sb.WriteString(seg) |
| + if !more { |
| + return sb.String() |
| + } |
| + sb.WriteByte('/') |
| + p = rest |
| + } |
| +} |
| + |
| +// scanQuery offers the query parameter rules. The query is only parsed when |
| +// it holds a parameter's name, so an ordinary request pays for a substring |
| +// search and nothing more. |
| +func scanQuery(rawQuery string, b *best) { |
| + var vals url.Values |
| + parsed := false |
| + for _, e := range idx.qparams { |
| + if e.pos < b.lo || e.pos >= b.pos || !strings.Contains(rawQuery, e.name) { |
| + continue |
| + } |
| + if !parsed { |
| + // A parse error still returns the pairs that did parse. |
| + vals, _ = url.ParseQuery(rawQuery) |
| + parsed = true |
| + } |
| + for _, v := range vals[e.name] { |
| + if hasPrefixFold(v, e.valuePrefix) { |
| + b.offer(e.pos, v) |
| + if b.pos == e.pos { |
| + b.fromQ, b.query = true, e.name |
| + } |
| + break |
| + } |
| + } |
| + } |
| +} |
| + |
| +// hasPrefixFold reports whether s, lower-cased, starts with the lower-case |
| +// prefix. |
| +func hasPrefixFold(s, prefix string) bool { |
| + if len(s) < len(prefix) { |
| + return false |
| + } |
| + for i := 0; i < len(prefix); i++ { |
| + c := s[i] |
| + if c >= 'A' && c <= 'Z' { |
| + c += 'a' - 'A' |
| + } |
| + if c != prefix[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/edgeguard/match_test.go b/internal/edgeguard/match_test.go| new file mode 100644 |
| index 000000000..ce3386e25 |
| --- /dev/null |
| +++ b/internal/edgeguard/match_test.go |
| @@ -0,0 +1,266 @@ |
| +package edgeguard |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +type checkCase struct { |
| + path, rawQuery, wantID string |
| +} |
| + |
| +func runCases(t *testing.T, cases []checkCase) { |
| + t.Helper() |
| + for _, c := range cases { |
| + hit, ok := Check(c.path, c.rawQuery) |
| + switch { |
| + case c.wantID == "" && ok: |
| + t.Errorf("Check(%q, %q) = %s (fragment %q), want no match", c.path, c.rawQuery, hit.Rule.ID, hit.Fragment) |
| + case c.wantID != "" && !ok: |
| + t.Errorf("Check(%q, %q) = no match, want %s", c.path, c.rawQuery, c.wantID) |
| + case c.wantID != "" && hit.Rule.ID != c.wantID: |
| + t.Errorf("Check(%q, %q) = %s, want %s", c.path, c.rawQuery, hit.Rule.ID, c.wantID) |
| + } |
| + } |
| +} |
| + |
| +func TestCheckHardTier(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/.env", "", "hard.secrets.env"}, |
| + {"/backend/.env", "", "hard.secrets.env"}, |
| + {"/.env.local", "", "hard.secrets.env-variant"}, |
| + {"/.env.production", "", "hard.secrets.env-variant"}, |
| + {"/.git/config", "", "hard.secrets.git"}, |
| + {"/.git/HEAD", "", "hard.secrets.git"}, |
| + {"/.git-credentials", "", "hard.secrets.git-credentials"}, |
| + {"/.aws/credentials", "", "hard.secrets.aws"}, |
| + {"/.docker/config.json", "", "hard.secrets.docker"}, |
| + {"/credentials.json", "", "hard.keys.credentials-json"}, |
| + {"/gcp-credentials.json", "", "hard.keys.gcp-credentials"}, |
| + {"/firebase-adminsdk.json", "", "hard.keys.firebase-admin"}, |
| + {"/firebase-adminsdk-x1y2.json", "", "hard.keys.firebase-admin"}, |
| + {"/@fs/.env", "", "hard.traversal.vite-fs"}, |
| + // proc-self precedes vite-fs in the catalogue, and the first rule in |
| + // file order wins, so this is not vite-fs. |
| + {"/@fs/proc/self/environ", "", "hard.traversal.proc-self"}, |
| + {"/x/proc/self/environ", "", "hard.traversal.proc-self"}, |
| + {"/static/../.env", "", "hard.traversal.dotdot"}, |
| + {"/db.sql", "", "hard.dumps.db-sql"}, |
| + {"/index.php.save", "", "hard.source.php-save"}, |
| + {"/index.php~", "", "hard.source.php-tilde"}, |
| + {"/home/.ssh/id_rsa", "", "hard.secrets.ssh"}, |
| + {"/id_ed25519", "", "hard.keys.id-ed25519"}, |
| + }) |
| +} |
| + |
| +func TestCheckProbeTier(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/wp-login.php", "", "probe.wordpress.wp-login"}, |
| + {"/xmlrpc.php", "", "probe.wordpress.xmlrpc"}, |
| + {"/blog/wp-json/wp/v2/users", "", "probe.wordpress.blog-wp-json"}, |
| + {"/wp-admin/install.php", "", "probe.wordpress.wp-admin"}, |
| + {"/info.php", "", "probe.php.php"}, |
| + {"/_profiler/phpinfo", "", "probe.phpframework.profiler-phpinfo"}, |
| + {"/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", "", "probe.phpframework.phpunit"}, |
| + {"/_ignition/execute-solution", "", "probe.phpframework.ignition"}, |
| + {"/vendor/composer/installed.json", "", "probe.phpframework.composer-json"}, |
| + {"/", `s=/index/\think\app/invokefunction`, "probe.phpframework.thinkphp"}, |
| + {"/phpmyadmin/index.php", "", "probe.phpmyadmin.phpmyadmin"}, |
| + {"/pma/", "", "probe.phpmyadmin.pma"}, |
| + {"/actuator/env", "", "probe.java.actuator"}, |
| + {"/login.action", "", "probe.java.action"}, |
| + {"/index.jsp", "", "probe.java.jsp"}, |
| + {"/cgi-bin/luci", "", "probe.cgi.cgi-bin"}, |
| + {"/HNAP1", "", "probe.cgi.hnap1"}, |
| + {"/GponForm/diag_Form", "", "probe.cgi.gponform"}, |
| + {"/server-status", "", "probe.status.server-status"}, |
| + {"/latest/meta-data/iam/", "", "probe.metadata.meta-data"}, |
| + {"/Dockerfile", "", "probe.devconfig.dockerfile"}, |
| + {"/.gitlab-ci.yml", "", "probe.devconfig.gitlab-ci"}, |
| + {"/backup/site.sql", "", "probe.dumps.sql"}, |
| + {"/data/app.sqlite", "", "probe.dumps.sqlite"}, |
| + {"/admin", "", "probe.admin.admin"}, |
| + {"/administrator/", "", "probe.admin.administrator"}, |
| + }) |
| +} |
| + |
| +func TestCheckEncodingTricks(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/.ENV", "", "hard.secrets.env"}, |
| + {"/.Git/config", "", "hard.secrets.git"}, |
| + {"/%2eenv", "", "hard.secrets.env"}, |
| + {"/static/%2e%2e/.env", "", "hard.traversal.dotdot"}, |
| + {`/static/..\.env`, "", "hard.traversal.dotdot"}, |
| + {"/x/..;/.env", "", "hard.traversal.dotdot"}, |
| + {"/.env;x=1", "", "hard.secrets.env"}, |
| + {"//.env", "", "hard.secrets.env"}, |
| + {"/./.git/config", "", "hard.secrets.git"}, |
| + {"/a;b=c/.git/config", "", "hard.secrets.git"}, |
| + {"/%2E%2Egit/x", "", ""}, |
| + {"/bad%zz/.env", "", "hard.secrets.env"}, |
| + }) |
| +} |
| + |
| +func TestCheckWellKnownExempt(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + {"/.well-known/acme-challenge/abc", "", ""}, |
| + {"/.well-known/security.txt", "", ""}, |
| + {"/.well-known/.env", "", ""}, |
| + {"/.well-known/../.env", "", "hard.traversal.dotdot"}, |
| + }) |
| +} |
| + |
| +func TestCheckMisfireCorpus(t *testing.T) { |
| + var cases []checkCase |
| + for _, p := range []string{ |
| + "/help/vat-in-the-european-union", |
| + "/docs/display-a-selection-of-tickets", |
| + "/docs/update-the-widget-from-version-1", |
| + "/en/articles/how-do-i-delete-a-hub", |
| + "/help/export-attendees-from-all-events", |
| + "/docs/embeddable-javascript-widget", |
| + "/assets/admin/application-3f2a9c.js", |
| + "/favicon-admin-32.png", |
| + "/help/the-admin-pane", |
| + "/wp-content/uploads/2024/05/logo.png", |
| + "/uploads/PMA_FULL_LOGO.png", |
| + "/img/photo..jpg", |
| + `/en/articles/"https:/x.example"`, |
| + "/api/union/members", |
| + "/env", |
| + "/environment", |
| + "/blog/.envoy", |
| + "/docs/index.php-guide", |
| + "/products/admin-chair", |
| + "/static/app.min.js", |
| + "/todo", |
| + "/telescopes", |
| + } { |
| + cases = append(cases, checkCase{p, "", ""}) |
| + } |
| + for _, q := range []string{ |
| + "redirect_uri=https://example.com/cb", |
| + "sig=ZXZhbCBkcm9wIHVuaW9u", |
| + "s=search+terms", |
| + } { |
| + cases = append(cases, checkCase{"/", q, ""}) |
| + } |
| + runCases(t, cases) |
| +} |
| + |
| +// Two kinds can both match one request, and a linear scan in file order picks |
| +// the earlier rule. The indexes must agree, whichever kind found it first. |
| +func TestCheckFileOrderAcrossKinds(t *testing.T) { |
| + runCases(t, []checkCase{ |
| + // vite-fs (segment) is listed before env (segment) and before |
| + // php-save (ext). |
| + {"/@fs/.env", "", "hard.traversal.vite-fs"}, |
| + {"/@fs/index.php.save", "", "hard.traversal.vite-fs"}, |
| + // env (segment) is listed before db-sql (exact). |
| + {"/.env/db.sql", "", "hard.secrets.env"}, |
| + // A hard rule beats a probe rule even when the probe rule is an |
| + // exact match on the whole path. |
| + {"/.git/wp-login.php", "", "hard.secrets.git"}, |
| + // wp-login (exact) is listed before php (ext). |
| + {"/wp-login.php", "", "probe.wordpress.wp-login"}, |
| + // A query parameter rule loses to an earlier path rule and beats a |
| + // later one. |
| + {"/wp-admin/x", `s=/index/\think`, "probe.wordpress.wp-admin"}, |
| + {"/admin", `s=/index/\think`, "probe.phpframework.thinkphp"}, |
| + }) |
| +} |
| + |
| +func TestCheckFragments(t *testing.T) { |
| + cases := []struct { |
| + path, rawQuery, fragment string |
| + fromQuery bool |
| + queryName string |
| + }{ |
| + {"/a/.ENV", "", ".env", false, ""}, |
| + {"/a/.env.local", "", ".env.local", false, ""}, |
| + {"/static/../.env", "", "..", false, ""}, |
| + {"/pma/", "", "/pma", false, ""}, |
| + {"/wp-admin/x/", "", "/wp-admin/x", false, ""}, |
| + {"/x/proc/self/environ", "", "/x/proc/self/environ", false, ""}, |
| + {"/a/b/info.php", "", "info.php", false, ""}, |
| + {"/", `a=1&s=%2Findex%2F%5CThink%5Capp`, `/index/\Think\app`, true, "s"}, |
| + } |
| + for _, c := range cases { |
| + hit, ok := Check(c.path, c.rawQuery) |
| + if !ok { |
| + t.Errorf("Check(%q, %q) = no match", c.path, c.rawQuery) |
| + continue |
| + } |
| + if hit.Fragment != c.fragment || hit.FromQuery != c.fromQuery || hit.QueryName != c.queryName { |
| + t.Errorf("Check(%q, %q) = fragment %q, fromQuery %v, name %q; want %q, %v, %q", |
| + c.path, c.rawQuery, hit.Fragment, hit.FromQuery, hit.QueryName, c.fragment, c.fromQuery, c.queryName) |
| + } |
| + } |
| +} |
| + |
| +func TestCheckTier(t *testing.T) { |
| + if _, ok := CheckTier("/.env", "", reqrec.TierProbe); ok { |
| + t.Error("probe-only check matched a hard rule") |
| + } |
| + if _, ok := CheckTier("/wp-login.php", "", reqrec.TierHard); ok { |
| + t.Error("hard-only check matched a probe rule") |
| + } |
| + if h, ok := CheckTier("/wp-login.php", "", reqrec.TierProbe); !ok || h.Rule.ID != "probe.wordpress.wp-login" { |
| + t.Errorf("probe check = %v, %v", h, ok) |
| + } |
| + // The probe tier still sees the path when a hard rule hides it from Check. |
| + if h, ok := CheckTier("/.git/wp-login.php", "", reqrec.TierProbe); !ok || h.Rule.ID != "probe.php.php" { |
| + t.Errorf("probe check under a hard hit = %v, %v", h, ok) |
| + } |
| + if h, ok := CheckTier("/", `s=/index/\think`, reqrec.TierProbe); !ok || !h.FromQuery { |
| + t.Errorf("probe query check = %v, %v", h, ok) |
| + } |
| + if _, ok := CheckTier("/", `s=/index/\think`, reqrec.TierHard); ok { |
| + t.Error("hard-only check matched a probe query rule") |
| + } |
| + if _, ok := CheckTier("/.env", "", reqrec.TierAttack); ok { |
| + t.Error("a tier with no rules matched") |
| + } |
| +} |
| + |
| +func TestCheckLongPath(t *testing.T) { |
| + long := strings.Repeat("/a", 512*1024) + "/.env" |
| + if len(long) < 1<<20 { |
| + t.Fatalf("path is %d bytes", len(long)) |
| + } |
| + hit, ok := Check(long, "") |
| + if !ok || hit.Rule.ID != "hard.secrets.env" { |
| + t.Fatalf("Check(long) = %v, %v", hit, ok) |
| + } |
| + if n := testing.AllocsPerRun(3, func() { Check(long, "") }); n > 4 { |
| + t.Fatalf("Check(long) allocates %v times, want at most 4", n) |
| + } |
| +} |
| + |
| +func TestCheckOrdinaryPathAllocs(t *testing.T) { |
| + for _, c := range []struct{ path, query string }{ |
| + {"/blog/2026/10/some-article-slug", ""}, |
| + {"/assets/app-3f2a9c.js", "v=2"}, |
| + {"/", ""}, |
| + } { |
| + if n := testing.AllocsPerRun(100, func() { Check(c.path, c.query) }); n != 0 { |
| + t.Errorf("Check(%q, %q) allocates %v times, want 0", c.path, c.query, n) |
| + } |
| + } |
| +} |
| + |
| +func BenchmarkCheckOrdinary(b *testing.B) { |
| + for _, c := range []struct{ name, path, query string }{ |
| + {"article", "/blog/2026/10/some-article-slug", ""}, |
| + {"asset", "/assets/app-3f2a9c.js", "v=2"}, |
| + } { |
| + b.Run(c.name, func(b *testing.B) { |
| + b.ReportAllocs() |
| + for i := 0; i < b.N; i++ { |
| + Check(c.path, c.query) |
| + } |
| + }) |
| + } |
| +} |