carlos / platform Public

edgeguard: review fixes (well-known covers queries, tier-safe prefix scan, lenient decode)

Exempt /.well-known/ from query rules too, run the qparam scan only on a
real name= parameter, stop a prefix rule outside the tier ending the
search, require one leading version line, make Version a const checked at
init, and decode valid escapes even when another escape is invalid.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 20012357bc2423e58ad18333b312d35fd9563c4d parent 681b05c
4 files changed, +179 −28
  • internal/edgeguard/catalogue.go +30 −16
  • internal/edgeguard/catalogue_test.go +7 −2
  • internal/edgeguard/match.go +81 −10
  • internal/edgeguard/match_test.go +61 −0

CI failed — run details

diff --git a/internal/edgeguard/catalogue.go b/internal/edgeguard/catalogue.go
index 5496bcd87..22a4840d0 100644
--- a/internal/edgeguard/catalogue.go
+++ b/internal/edgeguard/catalogue.go
@@ -96,12 +96,13 @@ var modeNames = map[string]Mode{"watch": ModeWatch, "block": ModeBlock, "burst":
//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
+// Version is the catalogue's version. It is bumped whenever a rule is added,
+// removed or changed, so a log line can say which catalogue produced it. It
+// must equal the "# version N" line in catalogue.txt, and init panics if the
+// two disagree, so a rule edit that forgets one of them fails the tests.
+const Version = 1
+var (
rules []Rule
idx index
)
@@ -111,11 +112,14 @@ func init() {
if err != nil {
panic(err)
}
+ if v != Version {
+ panic(fmt.Sprintf("edgeguard catalogue: catalogue.txt says version %d but Version is %d", v, Version))
+ }
ix, err := buildIndex(rs)
if err != nil {
panic(err)
}
- rules, Version, idx = rs, v, ix
+ rules, idx = rs, ix
}
// Rules returns the catalogue in file order. The caller may keep and modify
@@ -151,14 +155,24 @@ func parseCatalogue(data []byte) ([]Rule, int, error) {
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
+ rest, isVersion := strings.CutPrefix(line, "# version ")
+ if !haveVer {
+ // The version is the first thing in the file, so a catalogue
+ // with rules ahead of it, or none, is refused.
+ if !isVersion {
+ return nil, 0, fmt.Errorf("edgeguard catalogue line %d: the first line must be \"# version N\"", lineNumber)
+ }
+ 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
+ }
+ if isVersion {
+ return nil, 0, fmt.Errorf("edgeguard catalogue line %d: a second version line", lineNumber)
+ }
+ if strings.HasPrefix(line, "#") {
continue
}
f := strings.Fields(line)
@@ -302,8 +316,8 @@ type seqEntry struct {
}
type qparamEntry struct {
- name, valuePrefix string
- pos int
+ name, nameEq, valuePrefix string
+ pos int
}
func buildIndex(rs []Rule) (index, error) {
@@ -343,7 +357,7 @@ func buildIndex(rs []Rule) (index, error) {
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})
+ ix.qparams = append(ix.qparams, qparamEntry{name, name + "=", val, i})
case kindDotdot:
ix.dotdots = append(ix.dotdots, i)
}
diff --git a/internal/edgeguard/catalogue_test.go b/internal/edgeguard/catalogue_test.go
index 8a7ac0c9d..743929be5 100644
--- a/internal/edgeguard/catalogue_test.go
+++ b/internal/edgeguard/catalogue_test.go
@@ -13,8 +13,8 @@ func TestCatalogueParses(t *testing.T) {
if len(rs) == 0 {
t.Fatal("no rules")
}
- if Version != 1 {
- t.Fatalf("Version = %d, want 1", Version)
+ if _, v, err := parseCatalogue(catalogueData); err != nil || v != Version {
+ t.Fatalf("catalogue.txt parses to version %d, %v; Version is %d", v, err, Version)
}
seen := map[string]bool{}
sawProbe := false
@@ -106,6 +106,11 @@ func TestParseRejects(t *testing.T) {
{"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},
+ {"empty file", "", 1},
+ {"rule before the version line", ok + "# version 1\n", 1},
+ {"comment before the version line", "# notes\n# version 1\n" + ok, 1},
+ {"second version line", "# version 1\n" + ok + "# version 2\n", 3},
+ {"repeated version line", "# version 1\n# version 1\n" + ok, 2},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
diff --git a/internal/edgeguard/match.go b/internal/edgeguard/match.go
index 566037153..3c57844ee 100644
--- a/internal/edgeguard/match.go
+++ b/internal/edgeguard/match.go
@@ -67,13 +67,15 @@ func (b *best) offerFirst(positions []int, fragment string) {
func check(urlPath, rawQuery string, lo, hi int) (Hit, bool) {
b := best{lo: lo, pos: hi}
- scanPath(urlPath, &b)
+ exempt := scanPath(urlPath, &b)
if strings.IndexByte(urlPath, '%') >= 0 {
- if dec, err := url.PathUnescape(urlPath); err == nil && dec != urlPath {
- scanPath(dec, &b)
+ if dec := unescapeLenient(urlPath); dec != urlPath {
+ if scanPath(dec, &b) {
+ exempt = true
+ }
}
}
- if rawQuery != "" {
+ if rawQuery != "" && !exempt {
scanQuery(rawQuery, &b)
}
if b.pos >= hi {
@@ -82,8 +84,10 @@ func check(urlPath, rawQuery string, lo, hi int) (Hit, bool) {
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) {
+// 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)
if strings.IndexByte(p, ';') >= 0 {
p = stripParams(p)
@@ -97,7 +101,7 @@ func scanPath(p string, b *best) {
c := path.Clean(p)
rest := c[1:]
if first, _, _ := strings.Cut(rest, "/"); first == ".well-known" {
- return
+ return true
}
if pos, ok := idx.exact[c]; ok {
@@ -106,6 +110,10 @@ func scanPath(p string, b *best) {
if rest != "" {
first, _, _ := strings.Cut(rest, "/")
for _, e := range idx.prefix[first] {
+ // A rule outside the requested tier must not end the search.
+ if e.pos < b.lo {
+ continue
+ }
if isPrefixPath(c, e.pattern) {
b.offer(e.pos, c)
break
@@ -139,6 +147,51 @@ func scanPath(p string, b *best) {
b.offer(e.pos, c)
}
}
+ return false
+}
+
+// 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
+// returns s itself when nothing was decoded.
+func unescapeLenient(s string) string {
+ var sb strings.Builder
+ decoded := false
+ start := 0 // the start of the text not yet copied to sb
+ for i := 0; i+2 < len(s); i++ {
+ if s[i] != '%' {
+ continue
+ }
+ hi, lo := unhex(s[i+1]), unhex(s[i+2])
+ if hi < 0 || lo < 0 {
+ continue
+ }
+ if !decoded {
+ sb.Grow(len(s))
+ decoded = true
+ }
+ sb.WriteString(s[start:i])
+ sb.WriteByte(byte(hi<<4 | lo))
+ i += 2
+ start = i + 1
+ }
+ if !decoded {
+ return s
+ }
+ sb.WriteString(s[start:])
+ return sb.String()
+}
+
+func unhex(c byte) int {
+ switch {
+ case c >= '0' && c <= '9':
+ return int(c - '0')
+ case c >= 'a' && c <= 'f':
+ return int(c-'a') + 10
+ case c >= 'A' && c <= 'F':
+ return int(c-'A') + 10
+ }
+ return -1
}
// isPrefixPath reports whether the cleaned path is the pattern or lies under
@@ -224,14 +277,32 @@ func stripParams(p string) string {
}
}
+// hasParam reports whether rawQuery has a parameter called name, judged on
+// the raw text. nameEq is the name followed by "=": it must be at the start or right after "&". ";" is not treated
+// as a separator, because url.ParseQuery does not treat it as one. A name
+// that is percent-encoded in the query is not found.
+func hasParam(rawQuery, nameEq string) bool {
+ for from := 0; ; {
+ i := strings.Index(rawQuery[from:], nameEq)
+ if i < 0 {
+ return false
+ }
+ i += from
+ if i == 0 || rawQuery[i-1] == '&' {
+ return true
+ }
+ from = i + 1
+ }
+}
+
// 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.
+// it has a parameter by a rule'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) {
+ if e.pos < b.lo || e.pos >= b.pos || !hasParam(rawQuery, e.nameEq) {
continue
}
if !parsed {
diff --git a/internal/edgeguard/match_test.go b/internal/edgeguard/match_test.go
index ce3386e25..e5823b800 100644
--- a/internal/edgeguard/match_test.go
+++ b/internal/edgeguard/match_test.go
@@ -100,6 +100,13 @@ func TestCheckEncodingTricks(t *testing.T) {
{"/a;b=c/.git/config", "", "hard.secrets.git"},
{"/%2E%2Egit/x", "", ""},
{"/bad%zz/.env", "", "hard.secrets.env"},
+ // One invalid escape does not stop the valid ones being decoded.
+ {"/%zz/%2eenv", "", "hard.secrets.env"},
+ {"/%/%2e%2e/%2Egit", "", "hard.traversal.dotdot"},
+ {"/100%/%2egit/config", "", "hard.secrets.git"},
+ {"/%2", "", ""},
+ // Decoding happens once: %252e is a literal "%2e", not a dot.
+ {"/%252eenv", "", ""},
})
}
@@ -109,9 +116,60 @@ func TestCheckWellKnownExempt(t *testing.T) {
{"/.well-known/security.txt", "", ""},
{"/.well-known/.env", "", ""},
{"/.well-known/../.env", "", "hard.traversal.dotdot"},
+ // The exemption covers query rules as well as path rules.
+ {"/.well-known/x", `s=/index/\think`, ""},
+ {"/.well-known", `s=/index/\think`, ""},
+ {"/%2ewell-known/x", `s=/index/\think`, ""},
+ {"/x", `s=/index/\think`, "probe.phpframework.thinkphp"},
})
}
+func TestCheckQueryParamBoundary(t *testing.T) {
+ runCases(t, []checkCase{
+ {"/", `s=/index/\think`, "probe.phpframework.thinkphp"},
+ {"/", `a=1&s=/index/\think`, "probe.phpframework.thinkphp"},
+ {"/", `a=1&S=/index/\think`, ""},
+ {"/", `xs=/index/\think`, ""},
+ {"/", `a=1&xs=/index/\think`, ""},
+ {"/", `a=s=/index/\think`, ""},
+ {"/", `a=1;s=/index/\think`, ""},
+ })
+}
+
+// withCatalogue swaps the package's catalogue for the given text, built
+// through the same parser and index builder as the real one.
+func withCatalogue(t *testing.T, text string) {
+ t.Helper()
+ rs, _, err := parseCatalogue([]byte(text))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ix, err := buildIndex(rs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ oldRules, oldIdx := rules, idx
+ rules, idx = rs, ix
+ t.Cleanup(func() { rules, idx = oldRules, oldIdx })
+}
+
+// A rule outside the requested tier must not end the search for one inside
+// it, even when both share a first segment.
+func TestCheckTierSharedPrefixSegment(t *testing.T) {
+ withCatalogue(t, "# version 1\n"+
+ "hard g one prefix /a watch\n"+
+ "probe g two prefix /a/b watch\n")
+ if h, ok := CheckTier("/a/b", "", reqrec.TierProbe); !ok || h.Rule.ID != "probe.g.two" {
+ t.Errorf("probe check = %v, %v; want probe.g.two", h, ok)
+ }
+ if h, ok := CheckTier("/a/b", "", reqrec.TierHard); !ok || h.Rule.ID != "hard.g.one" {
+ t.Errorf("hard check = %v, %v; want hard.g.one", h, ok)
+ }
+ if h, ok := Check("/a/b", ""); !ok || h.Rule.ID != "hard.g.one" {
+ t.Errorf("Check = %v, %v; want hard.g.one", h, ok)
+ }
+}
+
func TestCheckMisfireCorpus(t *testing.T) {
var cases []checkCase
for _, p := range []string{
@@ -243,6 +301,9 @@ func TestCheckOrdinaryPathAllocs(t *testing.T) {
for _, c := range []struct{ path, query string }{
{"/blog/2026/10/some-article-slug", ""},
{"/assets/app-3f2a9c.js", "v=2"},
+ {"/blog/post", "utm_source=newsletter"},
+ {"/blog/post", "page=2&sort=asc"},
+ {"/blog/post", "session=abc"},
{"/", ""},
} {
if n := testing.AllocsPerRun(100, func() { Check(c.path, c.query) }); n != 0 {