edgeguard: a hit's fragment is the matched part, in the request's spelling
The matcher compares lower-cased text, and a prefix or segseq hit used to hand the whole cleaned, folded path to the recorder as its fragment. A mixed-case token under /wp-admin/ came out lower case, which the redactor no longer recognises as a token, so it was stored in "frag" while the record's path field masked it (final review C1). A path hit is now kept as a span of the cleaned text and spelled out of the request's own form only once the search is over: the pattern's span for exact and prefix rules, the run of segments for segseq, the matched segment for segment, segglob and ext, ".." for dotdot. Folding case moves no "/", ";" or ".", so the spelled text lines up byte for byte with the folded one. A path that matches nothing still allocates nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+182
−36
internal/edge/guard_test.go+42 −0internal/edgeguard/catalogue.go+7 −3internal/edgeguard/match.go+89 −30internal/edgeguard/match_test.go+44 −3
diff --git a/internal/edge/guard_test.go b/internal/edge/guard_test.go| index fe959acfc..c66572ca4 100644 |
| --- a/internal/edge/guard_test.go |
| +++ b/internal/edge/guard_test.go |
| @@ -289,3 +289,45 @@ func TestGuardOrdinaryRequestUntouched(t *testing.T) { |
| t.Fatalf("outcome %+v: want the guard run and no verdict", act.out) |
| } |
| } |
| + |
| +// fieldSink keeps the fields of every record a real reqrec.Recorder writes. |
| +type fieldSink struct{ recs []map[string]string } |
| + |
| +func (s *fieldSink) Edge(acct, app, host, level, msg string, f map[string]string) { |
| + s.recs = append(s.recs, f) |
| +} |
| +func (s *fieldSink) EdgeSummary(acct, app, host, level, msg string, f map[string]string) {} |
| + |
| +// Review C1: a token in a watched probe's path must not reach the record by |
| +// way of the fragment, in its own spelling or case-folded. The rules compare |
| +// lower-cased text, and a folded token no longer looks mixed case to the |
| +// redactor, so the fragment is only the part the rule matched, in the |
| +// request's spelling. Through the real recorder, so this is what is stored. |
| +func TestGuardFragmentKeepsNoToken(t *testing.T) { |
| + const token = "AbCd12_EfGh34_IjKl56_MnOp78" |
| + for _, tc := range []struct{ name, path, frag string }{ |
| + {"underscores", "/wp-admin/" + token, "/wp-admin"}, |
| + {"hyphens", "/WP-Admin/AbCd12-EfGh34-IjKl56-MnOp78", "/WP-Admin"}, |
| + {"slashes", "/wp-admin/AbCd12/EfGh34/IjKl56/MnOp78", "/wp-admin"}, |
| + {"under a segseq", "/Proc/Self/AbCd12_EfGh34_IjKl56_MnOp78", "Proc/Self"}, |
| + } { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "no") |
| + sink := &fieldSink{} |
| + g.e.EnableRequestRecords(reqrec.NewRecorder(sink, nil, nil)) |
| + g.get(tc.path) |
| + if len(sink.recs) != 1 { |
| + t.Fatalf("%s: %d records, want 1", tc.name, len(sink.recs)) |
| + } |
| + f := sink.recs[0] |
| + if f["kind"] != string(reqrec.KindWatch) || f["frag"] != tc.frag { |
| + t.Fatalf("%s: kind %q frag %q, want watch and %q", tc.name, f["kind"], f["frag"], tc.frag) |
| + } |
| + for _, piece := range []string{"AbCd12", "EfGh34", "IjKl56", "MnOp78"} { |
| + for _, spelt := range []string{piece, strings.ToLower(piece)} { |
| + if strings.Contains(f["frag"], spelt) { |
| + t.Errorf("%s: frag %q keeps %q", tc.name, f["frag"], spelt) |
| + } |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/edgeguard/catalogue.go b/internal/edgeguard/catalogue.go| index 22a4840d0..95f580000 100644 |
| --- a/internal/edgeguard/catalogue.go |
| +++ b/internal/edgeguard/catalogue.go |
| @@ -57,9 +57,13 @@ type Rule struct { |
| 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. |
| +// Hit is a rule that matched, with the text that matched it. Fragment is |
| +// only the part the rule matched, in the request's own spelling rather than |
| +// the case-folded text the rules compare: the whole cleaned path for an exact |
| +// rule, the pattern's leading segments for a prefix rule (never what lies |
| +// under them), the run of segments for a segseq rule, the matched segment for |
| +// a segment, segglob or ext rule, ".." for dotdot, and, when FromQuery is |
| +// set, the decoded value of the query parameter called QueryName. |
| type Hit struct { |
| Rule *Rule |
| Fragment string |
diff --git a/internal/edgeguard/match.go b/internal/edgeguard/match.go| index 3c57844ee..7d7e37097 100644 |
| --- a/internal/edgeguard/match.go |
| +++ b/internal/edgeguard/match.go |
| @@ -41,28 +41,52 @@ func CheckTier(urlPath, rawQuery string, tier reqrec.Tier) (Hit, bool) { |
| // 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. |
| +// |
| +// A path match is kept as a place, not as text: form is the form of the path |
| +// it was found in, as the request spelled it, and from and to are where the |
| +// match lies in that form's cleaned, folded text. check spells the fragment |
| +// out of form only once the search is over (spell), so the evidence is the |
| +// request's own text and never the case-folded copy the rules compare, and a |
| +// path that matches nothing pays for none of it. text is the fragment of a |
| +// match that is not a span of the path: ".." or a query value. |
| type best struct { |
| lo, pos int |
| - fragment string |
| + span bool |
| + form string |
| + from, to int |
| + text 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, "" |
| +// offer records a match on the span [from, to) of form's cleaned text when it |
| +// is in range and earlier than the best so far, and reports whether it did. |
| +func (b *best) offer(pos int, form string, from, to int) bool { |
| + if pos < b.lo || pos >= b.pos { |
| + return false |
| } |
| + *b = best{lo: b.lo, pos: pos, span: true, form: form, from: from, to: to} |
| + return true |
| } |
| -// offerFirst offers the first position at or after lo from an ascending list. |
| -func (b *best) offerFirst(positions []int, fragment string) { |
| +// offerText is offer for a match whose fragment is text rather than a span. |
| +func (b *best) offerText(pos int, text string) bool { |
| + if pos < b.lo || pos >= b.pos { |
| + return false |
| + } |
| + *b = best{lo: b.lo, pos: pos, text: text} |
| + return true |
| +} |
| + |
| +// first returns the first position at or after lo from an ascending list, or |
| +// -1 when there is none. |
| +func (b *best) first(positions []int) int { |
| for _, p := range positions { |
| if p >= b.lo { |
| - b.offer(p, fragment) |
| - return |
| + return p |
| } |
| } |
| + return -1 |
| } |
| func check(urlPath, rawQuery string, lo, hi int) (Hit, bool) { |
| @@ -81,19 +105,25 @@ func check(urlPath, rawQuery string, lo, hi int) (Hit, bool) { |
| if b.pos >= hi { |
| return Hit{}, false |
| } |
| - return Hit{Rule: &rules[b.pos], Fragment: b.fragment, FromQuery: b.fromQ, QueryName: b.query}, true |
| + h := Hit{Rule: &rules[b.pos], Fragment: b.text, FromQuery: b.fromQ, QueryName: b.query} |
| + if b.span { |
| + h.Fragment = spell(b.form)[b.from:b.to] |
| + } |
| + return h, true |
| } |
| // scanPath offers every path rule that matches one form of the path. It |
| // reports whether the form lies under /.well-known/, which exempts the |
| // request from every rule but dotdot, query rules included. |
| -func scanPath(p string, b *best) (exempt bool) { |
| - p = fold(p) |
| +func scanPath(form string, b *best) (exempt bool) { |
| + p := fold(form) |
| if strings.IndexByte(p, ';') >= 0 { |
| p = stripParams(p) |
| } |
| if len(idx.dotdots) > 0 && hasDotDot(p) { |
| - b.offerFirst(idx.dotdots, "..") |
| + if pos := b.first(idx.dotdots); pos >= 0 { |
| + b.offerText(pos, "..") |
| + } |
| } |
| if p == "" || p[0] != '/' { |
| p = "/" + p |
| @@ -105,7 +135,9 @@ func scanPath(p string, b *best) (exempt bool) { |
| } |
| if pos, ok := idx.exact[c]; ok { |
| - b.offerFirst(pos, c) |
| + if pos := b.first(pos); pos >= 0 { |
| + b.offer(pos, form, 0, len(c)) |
| + } |
| } |
| if rest != "" { |
| first, _, _ := strings.Cut(rest, "/") |
| @@ -115,41 +147,69 @@ func scanPath(p string, b *best) (exempt bool) { |
| continue |
| } |
| if isPrefixPath(c, e.pattern) { |
| - b.offer(e.pos, c) |
| + // The pattern's span only: what lies under it is the |
| + // request's own text, and may be a token. |
| + b.offer(e.pos, form, 0, len(e.pattern)) |
| break |
| } |
| } |
| } |
| - last := "" |
| - for rest != "" { |
| + // at is where seg starts in c. A cleaned path has no empty segment, so |
| + // each one starts just past the "/" that ends the one before. |
| + last, lastAt := "", 0 |
| + for at := 1; rest != ""; { |
| var seg string |
| seg, rest, _ = strings.Cut(rest, "/") |
| - last = seg |
| + last, lastAt = seg, at |
| if len(seg) >= idx.minSeg && len(seg) <= idx.maxSeg { |
| if pos, ok := idx.segment[seg]; ok { |
| - b.offerFirst(pos, seg) |
| + if pos := b.first(pos); pos >= 0 { |
| + b.offer(pos, form, at, at+len(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) |
| + b.offer(g.pos, form, at, at+len(seg)) |
| } |
| } |
| + at += len(seg) + 1 |
| } |
| 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) |
| + b.offer(e.pos, form, lastAt, lastAt+len(last)) |
| } |
| } |
| for _, e := range idx.segseqs { |
| - if e.pos >= b.lo && e.pos < b.pos && hasSegments(c, e.segs) { |
| - b.offer(e.pos, c) |
| + if e.pos >= b.lo && e.pos < b.pos { |
| + if at := segmentsAt(c, e.segs); at >= 0 { |
| + b.offer(e.pos, form, at, at+len(e.segs)) |
| + } |
| } |
| } |
| return false |
| } |
| +// spell is the cleaned path scanPath compares, made from form with its case |
| +// left as the request sent it. Folding case changes no "/", ";" or ".", which |
| +// are all that stripping parameters and cleaning look at, so the result lines |
| +// up byte for byte with the folded text: a match's place in one is its place |
| +// in the other. It runs only for a match, so its allocations are a match's. |
| +func spell(form string) string { |
| + p := form |
| + if strings.IndexByte(p, '\\') >= 0 { |
| + p = strings.ReplaceAll(p, `\`, "/") |
| + } |
| + if strings.IndexByte(p, ';') >= 0 { |
| + p = stripParams(p) |
| + } |
| + if p == "" || p[0] != '/' { |
| + p = "/" + p |
| + } |
| + return path.Clean(p) |
| +} |
| + |
| // unescapeLenient decodes every valid %XX in s and leaves an invalid escape |
| // as it is. url.PathUnescape refuses the whole string over one bad escape, |
| // which would let "/%zz/%2eenv" hide the second escape from the rules. It |
| @@ -200,18 +260,18 @@ 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 { |
| +// segmentsAt reports where segs, a run of whole segments such as |
| +// "proc/self", first appears in the cleaned path, or -1 when it does not. |
| +func segmentsAt(c, segs string) int { |
| for from := 0; ; { |
| i := strings.Index(c[from:], segs) |
| if i < 0 { |
| - return false |
| + return -1 |
| } |
| start := from + i |
| end := start + len(segs) |
| if c[start-1] == '/' && (end == len(c) || c[end] == '/') { |
| - return true |
| + return start |
| } |
| from = start + 1 |
| } |
| @@ -312,8 +372,7 @@ func scanQuery(rawQuery string, b *best) { |
| } |
| for _, v := range vals[e.name] { |
| if hasPrefixFold(v, e.valuePrefix) { |
| - b.offer(e.pos, v) |
| - if b.pos == e.pos { |
| + if b.offerText(e.pos, v) { |
| b.fromQ, b.query = true, e.name |
| } |
| break |
diff --git a/internal/edgeguard/match_test.go b/internal/edgeguard/match_test.go| index e5823b800..3f6235871 100644 |
| --- a/internal/edgeguard/match_test.go |
| +++ b/internal/edgeguard/match_test.go |
| @@ -1,6 +1,7 @@ |
| package edgeguard |
| import ( |
| + "path" |
| "strings" |
| "testing" |
| @@ -236,13 +237,32 @@ func TestCheckFragments(t *testing.T) { |
| fromQuery bool |
| queryName string |
| }{ |
| - {"/a/.ENV", "", ".env", false, ""}, |
| + // A fragment is in the request's own spelling, never the folded |
| + // text the rules compare. |
| + {"/a/.ENV", "", ".ENV", false, ""}, |
| {"/a/.env.local", "", ".env.local", false, ""}, |
| + {"/a/.Env.Local", "", ".Env.Local", false, ""}, |
| {"/static/../.env", "", "..", false, ""}, |
| + {"/static/../.ENV", "", "..", false, ""}, |
| + // A prefix rule's fragment is the pattern's span and nothing under |
| + // it: what follows /wp-admin is the request's own, and may be a |
| + // token. |
| {"/pma/", "", "/pma", false, ""}, |
| - {"/wp-admin/x/", "", "/wp-admin/x", false, ""}, |
| - {"/x/proc/self/environ", "", "/x/proc/self/environ", false, ""}, |
| + {"/wp-admin/x/", "", "/wp-admin", false, ""}, |
| + {"/WP-Admin/AbCd12_EfGh34_IjKl56_MnOp78", "", "/WP-Admin", false, ""}, |
| + {`\WP-Admin\AbCd12`, "", "/WP-Admin", false, ""}, |
| + {"//WP-Admin/./x", "", "/WP-Admin", false, ""}, |
| + {"/Blog/WP-Json/wp/v2/users", "", "/Blog/WP-Json", false, ""}, |
| + // A segseq rule's fragment is its run of segments. |
| + {"/x/proc/self/environ", "", "proc/self", false, ""}, |
| + {"/X/Proc/Self/Environ", "", "Proc/Self", false, ""}, |
| + {"/WP-Login.php", "", "/WP-Login.php", false, ""}, |
| {"/a/b/info.php", "", "info.php", false, ""}, |
| + {"/a/B/Info.PHP", "", "Info.PHP", false, ""}, |
| + {"/a;x=1/.ENV;y=2", "", ".ENV", false, ""}, |
| + // The decoded form's spelling, when that is the form that matched. |
| + {"/%2EEnv", "", ".Env", false, ""}, |
| + {"/a/%2EGit/config", "", ".Git", false, ""}, |
| {"/", `a=1&s=%2Findex%2F%5CThink%5Capp`, `/index/\Think\app`, true, "s"}, |
| } |
| for _, c := range cases { |
| @@ -258,6 +278,27 @@ func TestCheckFragments(t *testing.T) { |
| } |
| } |
| +// spell must line up byte for byte with the folded, cleaned text scanPath |
| +// compares, or a fragment would be cut from the wrong place. |
| +func TestSpellLinesUpWithFold(t *testing.T) { |
| + for _, p := range []string{ |
| + "", "/", "x", "/A/B/C", `\A\..\B`, "/a;X=1/B;y/.ENV", "//A/./B/../C/", "/Ä/.ENV", |
| + "/%2E%2E/X", "/A;b/;c/D;", `/x/..;\.Git`, "/ABC/./../../D", |
| + } { |
| + c := fold(p) |
| + if strings.IndexByte(c, ';') >= 0 { |
| + c = stripParams(c) |
| + } |
| + if c == "" || c[0] != '/' { |
| + c = "/" + c |
| + } |
| + c = path.Clean(c) |
| + if got := spell(p); fold(got) != c { |
| + t.Errorf("spell(%q) = %q, folds to %q; want %q", p, got, fold(got), c) |
| + } |
| + } |
| +} |
| + |
| func TestCheckTier(t *testing.T) { |
| if _, ok := CheckTier("/.env", "", reqrec.TierProbe); ok { |
| t.Error("probe-only check matched a hard rule") |