carlos / platform Public

edge: static sites serve probe paths they have, and never a rewrite onto a leak

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 703de09677639557160e3f2c5017284bc9ed7780 parent d67f994
3 files changed, +326 −0
  • internal/edge/redirects.go +29 −0
  • internal/edge/static.go +33 −0
  • internal/edge/static_guard_test.go +264 −0

CI failed — run details

diff --git a/internal/edge/redirects.go b/internal/edge/redirects.go
index f38a1d416..df918c316 100644
--- a/internal/edge/redirects.go
+++ b/internal/edge/redirects.go
@@ -410,6 +410,35 @@ func (rs *redirectRules) resolve(host, p, rawPath, rawQuery string, exists bool)
return redirectAction{}, false
}
+// names reports whether some rule names the cleaned path p outright for
+// host: a rule with no splat and no ":name" segment, whose source segments
+// are p's. Such a rule is the site saying it has a page at p, wherever the
+// file is. A catch-all or a placeholder rule says nothing of the kind, because
+// it answers paths the site never listed. A nil set names nothing.
+func (rs *redirectRules) names(host, p string) bool {
+ if rs == nil {
+ return false
+ }
+ var reqSegs []string
+ if p != "/" {
+ reqSegs = strings.Split(p[1:], "/")
+ }
+rules:
+ for i := range rs.rules {
+ rule := &rs.rules[i]
+ if rule.splat || len(rule.segs) != len(reqSegs) || rule.host != "" && rule.host != host {
+ continue
+ }
+ for j, seg := range rule.segs {
+ if strings.HasPrefix(seg, ":") || seg != reqSegs[j] {
+ continue rules
+ }
+ }
+ return true
+ }
+ return false
+}
+
// hostOf is the host of a "scheme://host[:port]" prefix, normalized as
// requestHost normalizes a request's.
func hostOf(prefix string) string {
diff --git a/internal/edge/static.go b/internal/edge/static.go
index 2f2fd0907..b12ad4394 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -35,8 +35,10 @@ import (
"time"
"github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/edgeguard"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/reqrec"
)
// siteArtifactFile is the one artifact a static release carries: the gzipped
@@ -479,6 +481,17 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
// The _redirects file is configuration and answers nothing.
found := err == nil && !fi.IsDir() && p != "/"+redirectsFile
if !rewritten {
+ // The probe tier, which ServeHTTP leaves to the tree: a path like
+ // /wp-login.php is a probe only when the site has no such page,
+ // and only the tree knows. A _redirects rule that names the path
+ // outright counts as a page there; a catch-all or placeholder rule
+ // does not, or one "/* /index.html 200" would exempt every probe.
+ // This runs before the rules act, so a blocked probe is never
+ // redirected or given the fallback page.
+ if !found && !tree.redirects.names(requestHost(r.Host), p) &&
+ staticGuardHit(w, r, r.URL.Path, r.URL.RawQuery, reqrec.TierProbe) {
+ return
+ }
if act, ok := tree.redirects.resolve(requestHost(r.Host), p, r.URL.Path, r.URL.RawQuery, found); ok {
if act.location != "" {
http.Redirect(w, r, act.location, act.status)
@@ -506,11 +519,31 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
w.WriteHeader(http.StatusMovedPermanently)
return
}
+ // A rewrite sends a file the request did not name, so the request's
+ // own path passing the hard tier in ServeHTTP says nothing about it:
+ // /download rewritten onto /.env would serve a leak.
+ if rewritten && staticGuardHit(w, r, p, "", reqrec.TierHard) {
+ return
+ }
s.serveFile(fp, p, fi, status, w, r)
return
}
}
+// staticGuardHit runs one tier of the catalogue over urlPath for a request
+// the guard is running for, and hands a match to guardDecide. It reports
+// whether the guard answered the request, in which case the caller must stop.
+// It does nothing, the matcher included, when the guard is off for r or has
+// already decided it, so a request is decided once however many places check.
+func staticGuardHit(w http.ResponseWriter, r *http.Request, urlPath, rawQuery string, tier reqrec.Tier) bool {
+ out := outcomeFrom(r)
+ if out == nil || out.guard == nil || out.guard.verdict != nil {
+ return false
+ }
+ hit, ok := edgeguard.CheckTier(urlPath, rawQuery, tier)
+ return ok && guardDecide(w, r, hit)
+}
+
// serveFile sends the tree file at fp, whose tree path is p (for logs). A 200
// gets a content tag and net/http's conditional and range handling. Any other
// status — a _redirects 404 page — is the file's bytes under that status,
diff --git a/internal/edge/static_guard_test.go b/internal/edge/static_guard_test.go
new file mode 100644
index 000000000..b1db23923
--- /dev/null
+++ b/internal/edge/static_guard_test.go
@@ -0,0 +1,264 @@
+package edge
+
+import (
+ "context"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/reqrec"
+)
+
+// staticGuardRig is a whole edge over one static route for site.example.com,
+// serving files, with a recorder that keeps every record. Requests go through
+// ServeHTTP, so the guard state exists as it does in production.
+type staticGuardRig struct {
+ e *Edge
+ rec *memRecorder
+}
+
+func staticGuardEdge(t *testing.T, mode guardMode, files map[string]string) *staticGuardRig {
+ t.Helper()
+ store := release.NewDirStore(filepath.Join(t.TempDir(), "store"))
+ priv, pub := testKeys(t)
+ shipSite(t, store, "site", "v1", files)
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil {
+ t.Fatalf("Promote: %v", err)
+ }
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.EnableStatic(store, pub, filepath.Join(t.TempDir(), "cache"))
+ if err := e.Reload(); err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ rec := &memRecorder{}
+ e.EnableRequestRecords(rec)
+ e.guard = mode
+ return &staticGuardRig{e: e, rec: rec}
+}
+
+func (g *staticGuardRig) get(path string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ g.e.ServeHTTP(w, httptest.NewRequest("GET", "http://site.example.com"+path, nil))
+ return w
+}
+
+// onlyMatch fails unless the recorder holds exactly one Match and no plain
+// Response, and returns that Match.
+func (g *staticGuardRig) onlyMatch(t *testing.T) reqrec.Match {
+ t.Helper()
+ if len(g.rec.resp) != 0 || len(g.rec.match) != 1 {
+ t.Fatalf("responses %+v, matches %+v; want 0 and 1", g.rec.resp, g.rec.match)
+ }
+ return g.rec.match[0]
+}
+
+// onlyResponse fails unless the recorder holds exactly one plain Response and
+// no Match, and returns that Response.
+func (g *staticGuardRig) onlyResponse(t *testing.T) reqrec.Response {
+ t.Helper()
+ if len(g.rec.resp) != 1 || len(g.rec.match) != 0 {
+ t.Fatalf("responses %+v, matches %+v; want 1 and 0", g.rec.resp, g.rec.match)
+ }
+ return g.rec.resp[0]
+}
+
+// A site without the file is asked for a probe path: the tree's own answer is
+// a 404, and the one record is a watch for the probe rule carrying it. In
+// block mode the guard's block page answers instead.
+func TestStaticProbeAbsentIsMatched(t *testing.T) {
+ files := map[string]string{"index.html": "home"}
+
+ g := staticGuardEdge(t, guardCatalogue, files)
+ if w := g.get("/wp-login.php"); w.Code != 404 {
+ t.Fatalf("watch: status %d, want 404", w.Code)
+ }
+ m := g.onlyMatch(t)
+ if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierProbe || m.RuleID != "probe.wordpress.wp-login" || m.Status != 404 || m.Ref != "" {
+ t.Fatalf("watch: match %+v", m)
+ }
+
+ g = staticGuardEdge(t, guardBlock, files)
+ w := g.get("/wp-login.php")
+ if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" {
+ t.Fatalf("block: %d ref %q", w.Code, w.Header().Get("X-Carlos-Ref"))
+ }
+ m = g.onlyMatch(t)
+ if m.Kind != reqrec.KindBlock || m.RuleID != "probe.wordpress.wp-login" || m.Ref != w.Header().Get("X-Carlos-Ref") {
+ t.Fatalf("block: match %+v", m)
+ }
+}
+
+// A probe-looking path the site really has is the site's own page: served
+// with its bytes, in block mode too, and nothing is recorded as a match.
+func TestStaticProbePresentIsServed(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ files map[string]string
+ path string
+ body string
+ }{
+ {"file", map[string]string{"wp-login.php": "a login page of my own"}, "/wp-login.php", "a login page of my own"},
+ {"directory index", map[string]string{"administrator/index.html": "our administrators"}, "/administrator/", "our administrators"},
+ } {
+ for _, mode := range []guardMode{guardCatalogue, guardBlock} {
+ g := staticGuardEdge(t, mode, tc.files)
+ w := g.get(tc.path)
+ if w.Code != 200 || w.Body.String() != tc.body {
+ t.Fatalf("%s, mode %d: %d %q", tc.name, mode, w.Code, w.Body.String())
+ }
+ if r := g.onlyResponse(t); r.Status != 200 {
+ t.Fatalf("%s, mode %d: response %+v", tc.name, mode, r)
+ }
+ }
+ }
+}
+
+// Review Focus 4: a catch-all rule answers every path, so it says nothing
+// about which paths the site has. A probe path it would answer is still a
+// probe, and in block mode it is blocked rather than given the fallback page.
+func TestStaticSplatIsNotExistence(t *testing.T) {
+ files := map[string]string{"index.html": "the fallback page", "_redirects": "/* /index.html 200\n"}
+
+ g := staticGuardEdge(t, guardCatalogue, files)
+ if w := g.get("/wp-login.php"); w.Code != 200 || w.Body.String() != "the fallback page" {
+ t.Fatalf("watch: %d %q, want the fallback page", w.Code, w.Body.String())
+ }
+ m := g.onlyMatch(t)
+ if m.Kind != reqrec.KindWatch || m.RuleID != "probe.wordpress.wp-login" || m.Status != 200 {
+ t.Fatalf("watch: match %+v", m)
+ }
+
+ g = staticGuardEdge(t, guardBlock, files)
+ w := g.get("/wp-login.php")
+ if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || w.Body.String() == "the fallback page" {
+ t.Fatalf("block: %d ref %q body %q", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String())
+ }
+ if m := g.onlyMatch(t); m.Kind != reqrec.KindBlock {
+ t.Fatalf("block: match %+v", m)
+ }
+}
+
+// A rule that names the path outright is the site declaring it has a page
+// there, so the answer is served and nothing is matched.
+func TestStaticExplicitRedirectIsExistence(t *testing.T) {
+ files := map[string]string{"api/rpc.html": "our rpc docs", "_redirects": "/xmlrpc.php /api/rpc.html 200\n"}
+ for _, mode := range []guardMode{guardCatalogue, guardBlock} {
+ g := staticGuardEdge(t, mode, files)
+ if w := g.get("/xmlrpc.php"); w.Code != 200 || w.Body.String() != "our rpc docs" {
+ t.Fatalf("mode %d: %d %q", mode, w.Code, w.Body.String())
+ }
+ g.onlyResponse(t)
+ }
+}
+
+// A rewrite onto a file the hard tier names is not served as a rewrite: the
+// request path looked harmless, the file it would send is a leak. Watching
+// records it and serves the file; blocking answers with the guard's 404.
+func TestStaticRewriteToHardFile(t *testing.T) {
+ files := map[string]string{".env": "SECRET=1", "_redirects": "/download /.env 200\n"}
+
+ g := staticGuardEdge(t, guardCatalogue, files)
+ if w := g.get("/download"); w.Code != 200 || w.Body.String() != "SECRET=1" {
+ t.Fatalf("watch: %d %q, want the file served", w.Code, w.Body.String())
+ }
+ m := g.onlyMatch(t)
+ if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Status != 200 {
+ t.Fatalf("watch: match %+v", m)
+ }
+
+ g = staticGuardEdge(t, guardBlock, files)
+ w := g.get("/download")
+ if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || w.Body.String() == "SECRET=1" {
+ t.Fatalf("block: %d ref %q body %q", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String())
+ }
+ m = g.onlyMatch(t)
+ if m.Kind != reqrec.KindBlock || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Ref != w.Header().Get("X-Carlos-Ref") {
+ t.Fatalf("block: match %+v", m)
+ }
+}
+
+// A hard-tier path asked for directly is decided by the check in ServeHTTP,
+// before the static handler runs. The handler must not file it a second time.
+func TestStaticHardAtEdgeOnce(t *testing.T) {
+ files := map[string]string{".env": "SECRET=1", "index.html": "home"}
+ for _, mode := range []guardMode{guardCatalogue, guardBlock} {
+ g := staticGuardEdge(t, mode, files)
+ w := g.get("/.env")
+ if mode == guardBlock && w.Code != 404 {
+ t.Fatalf("block: status %d, want 404", w.Code)
+ }
+ m := g.onlyMatch(t)
+ if m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" {
+ t.Fatalf("mode %d: match %+v", mode, m)
+ }
+ }
+}
+
+// With the guard off for a request there is no state to decide on, so the
+// handler checks nothing and serves as it always did.
+func TestStaticGuardOffServesAsBefore(t *testing.T) {
+ g := staticGuardEdge(t, guardOff, map[string]string{".env": "SECRET=1", "_redirects": "/download /.env 200\n/* /index.html 200\n", "index.html": "home"})
+ if w := g.get("/download"); w.Code != 200 || w.Body.String() != "SECRET=1" {
+ t.Fatalf("%d %q", w.Code, w.Body.String())
+ }
+ if w := g.get("/wp-login.php"); w.Code != 200 || w.Body.String() != "home" {
+ t.Fatalf("%d %q", w.Code, w.Body.String())
+ }
+ if len(g.rec.match) != 0 || len(g.rec.resp) != 2 {
+ t.Fatalf("responses %d, matches %d; want 2 and 0", len(g.rec.resp), len(g.rec.match))
+ }
+}
+
+func TestRedirectNames(t *testing.T) {
+ rs, err := parseRedirects([]byte("" +
+ "/old /new 301\n" +
+ "/blog/:slug /posts/:slug 301\n" +
+ "/docs/* /d/:splat 200\n" +
+ "/xmlrpc.php /api/rpc.html 200\n" +
+ "https://other.example.com/only-there /x 301\n" +
+ "/nested/deep/page /y 200\n"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ host, p string
+ want bool
+ }{
+ {"site.example.com", "/old", true},
+ {"site.example.com", "/xmlrpc.php", true},
+ {"site.example.com", "/nested/deep/page", true},
+ {"site.example.com", "/nested/deep", false},
+ {"site.example.com", "/blog/hello", false},
+ {"site.example.com", "/docs/a", false},
+ {"site.example.com", "/docs", false},
+ {"site.example.com", "/wp-login.php", false},
+ {"site.example.com", "/only-there", false},
+ {"other.example.com", "/only-there", true},
+ } {
+ if got := rs.names(tc.host, tc.p); got != tc.want {
+ t.Errorf("names(%q, %q) = %v, want %v", tc.host, tc.p, got, tc.want)
+ }
+ }
+ var none *redirectRules
+ if none.names("site.example.com", "/old") {
+ t.Error("a nil rule set names nothing")
+ }
+ // A catch-all alone names no path in particular.
+ all, err := parseRedirects([]byte("/* /index.html 200\n"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if all.names("site.example.com", "/wp-login.php") {
+ t.Error("a splat rule must not count as naming a path")
+ }
+}