edge: run the hard and probe tiers once per request, watch by default
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+551
−57
internal/edge/answered.go+16 −4internal/edge/edge.go+43 −2internal/edge/guard.go+126 −0internal/edge/guard_test.go+291 −0internal/edge/reqrecords.go+29 −25internal/edge/reqrecords_test.go+41 −25internal/host/reqrec_e2e_test.go+3 −1internal/hostenv/hostenv.go+2 −0
CI failed — run details
diff --git a/internal/edge/answered.go b/internal/edge/answered.go| index e92d52977..2b0fce230 100644 |
| --- a/internal/edge/answered.go |
| +++ b/internal/edge/answered.go |
| @@ -39,6 +39,11 @@ type outcome struct { |
| // (MarkWoke), so a request record can say which request woke the app. |
| // Requests that queued behind the same wake are not marked. |
| woke bool |
| + // guard is set when the hard and probe checks run for this request |
| + // (guard.go), and holds their verdict once one matched. nil means the |
| + // guard is off for it: a door caller, a request a tunnel delivered (the |
| + // hub checked it), or CARLOS_EDGE_PROTECT=off. |
| + guard *guardState |
| } |
| // causeClientGone is the cause noted when a proxy fails because the CLIENT |
| @@ -67,11 +72,18 @@ func WithAnswerFlag(r *http.Request) (*http.Request, *bool) { |
| return r, &o.answered |
| } |
| +// outcomeFrom returns the outcome r carries, or nil when the edge attached |
| +// none. |
| +func outcomeFrom(r *http.Request) *outcome { |
| + o, _ := r.Context().Value(answeredKey{}).(*outcome) |
| + return o |
| +} |
| + |
| // MarkAnswered sets the flag when r carries one; a no-op otherwise — so the |
| // activator can call it unconditionally, including on the paths (a |
| // non-hibernating route, a direct unit test) where the edge attached none. |
| func MarkAnswered(r *http.Request) { |
| - if o, ok := r.Context().Value(answeredKey{}).(*outcome); ok { |
| + if o := outcomeFrom(r); o != nil { |
| o.answered = true |
| } |
| } |
| @@ -83,15 +95,15 @@ func MarkWoke(r *http.Request) { |
| if r == nil { |
| return |
| } |
| - if o, ok := r.Context().Value(answeredKey{}).(*outcome); ok { |
| + if o := outcomeFrom(r); o != nil { |
| o.woke = true |
| } |
| } |
| // Woke reports whether MarkWoke was called for r. |
| func Woke(r *http.Request) bool { |
| - o, ok := r.Context().Value(answeredKey{}).(*outcome) |
| - return ok && o.woke |
| + o := outcomeFrom(r) |
| + return o != nil && o.woke |
| } |
| // waited reports how long r has been served for, when the edge attached an |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index c7ffc02d2..86c5efd59 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -51,6 +51,7 @@ import ( |
| "golang.org/x/crypto/acme/autocert" |
| "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| "github.com/carlosframework/platform/internal/edgeproof" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/gate" |
| @@ -61,6 +62,7 @@ import ( |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| ) |
| // Default cache sizing for EnableCache: 4096 entries is comfortably above a |
| @@ -249,6 +251,11 @@ type Edge struct { |
| // false, ServeHTTP never constructs a gzipWriter and the writer stack is |
| // byte-for-byte what it was before compression existed (compress.go). |
| gzipOn bool |
| + // guard is CARLOS_EDGE_PROTECT, read once in New: what the edge does |
| + // with a request matching a hard or probe rule (guard.go). By default |
| + // each rule's own mode, and in catalogue version 1 that is only ever to |
| + // watch. |
| + guard guardMode |
| // issuer, when set, gates certificate ISSUANCE on this box holding the |
| // deployment's housekeeper lease (certsync.go). It arrives through |
| // WithIssuerGate because internal/host imports this package and never the |
| @@ -419,7 +426,7 @@ type upstream struct { |
| // New builds an Edge over reg and performs the startup reload. act may be nil |
| // (no hibernation). |
| func New(reg *registry.Registry, act Activator) (*Edge, error) { |
| - e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(), |
| + e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), guard: guardModeFromEnv(os.Getenv), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(), |
| lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000)} |
| e.geo = geo.NewSwappable() |
| e.geoLookup = e.geo.Lookup |
| @@ -1712,6 +1719,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| var bytes int64 |
| ob := &countingWriter{ResponseWriter: w, n: &bytes} |
| w = ob |
| + var out *outcome |
| if up.route.Kind != "status" { |
| // The outcome rides the request so the two things only the inner |
| // layers know reach this defer: the activator marks the wake-path |
| @@ -1719,8 +1727,15 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // member's platform event, so not filed again (spec §3.2, "exactly |
| // once") — and a proxy ErrorHandler notes WHY it answered 502/503 |
| // (noteCause), which is what groups Availability by cause. |
| - var out *outcome |
| r, out = withOutcome(r) |
| + // The hard and probe checks (guard.go) run for every request this |
| + // box is the first to see. A door caller is the platform itself, |
| + // not a visitor. A request a tunnel delivered was checked, and is |
| + // recorded, by the hub that forwarded it, so checking it again |
| + // here would answer or count it twice. |
| + if e.guard != guardOff && !isDoor && !fromTunnel(r.Context()) { |
| + out.guard = &guardState{mode: e.guard, mint: e.mintRef} |
| + } |
| defer func() { |
| if m := e.usageMeter.Load(); m != nil { |
| m.Record(up.route, 1, bytes, hopped) |
| @@ -1733,6 +1748,32 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| }() |
| } |
| + // The hard and probe checks (internal/edgeguard; edge protection spec |
| + // §5.3), once per request. Placed HERE for the gate's reasons below: |
| + // after the meter and the observer defer, so a block page bills and is |
| + // recorded like any answer; before the gate, so a probe on a gated |
| + // route meets the guard rather than the login page; before the upgrade |
| + // branch and the cache, so a stored answer is never served to a probe; |
| + // and before the activator, so a check never waits on a wake and a |
| + // blocked probe never wakes anything. The matcher allocates nothing for |
| + // an ordinary path. |
| + // |
| + // A static route this box serves itself checks only the hard tier here: |
| + // whether a probe-tier path is a probe depends on what the site holds, |
| + // which only the static handler knows, so it decides that tier itself. |
| + if out != nil && out.guard != nil { |
| + var hit edgeguard.Hit |
| + var matched bool |
| + if up.route.Kind == "static" && !up.viaTunnel { |
| + hit, matched = edgeguard.CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierHard) |
| + } else { |
| + hit, matched = edgeguard.Check(r.URL.Path, r.URL.RawQuery) |
| + } |
| + if matched && guardDecide(w, r, hit) { |
| + return |
| + } |
| + } |
| + |
| // The password gate (internal/gate; spec 2026-09-07-password-gate-design |
| // §4.1). Placed HERE and the neighbours are load-bearing: after the |
| // meter, so the login page's bytes bill to the route that caused them; |
diff --git a/internal/edge/guard.go b/internal/edge/guard.go| new file mode 100644 |
| index 000000000..40f6eef0b |
| --- /dev/null |
| +++ b/internal/edge/guard.go |
| @@ -0,0 +1,126 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/edgeguard" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| +) |
| + |
| +// guardMode is what the edge does with a request that matches a hard or |
| +// probe rule (internal/edgeguard). It is read once, in New, from |
| +// CARLOS_EDGE_PROTECT. |
| +type guardMode uint8 |
| + |
| +const ( |
| + // guardCatalogue, the default, does what each rule's own mode says. Every |
| + // rule in catalogue version 1 watches or counts toward a burst, so by |
| + // default nothing is blocked: a match is recorded with the app's answer. |
| + guardCatalogue guardMode = iota |
| + // guardOff runs no check at all. |
| + guardOff |
| + // guardWatch records every match and blocks none, whatever the catalogue |
| + // says. |
| + guardWatch |
| + // guardBlock blocks every match except a burst rule's, which is a page a |
| + // real visitor may ask for once. It is for dev boxes, to see the block |
| + // page and its code end to end. |
| + guardBlock |
| +) |
| + |
| +// guardModeFromEnv reads CARLOS_EDGE_PROTECT. An unknown value is logged and |
| +// read as the default, so a typo never turns protection off. |
| +func guardModeFromEnv(getenv func(string) string) guardMode { |
| + v := getenv("CARLOS_EDGE_PROTECT") |
| + switch strings.ToLower(strings.TrimSpace(v)) { |
| + case "off": |
| + return guardOff |
| + case "watch": |
| + return guardWatch |
| + case "block": |
| + return guardBlock |
| + case "": |
| + return guardCatalogue |
| + } |
| + log.Printf("edge: CARLOS_EDGE_PROTECT=%q is not off, watch or block; using the catalogue's modes", v) |
| + return guardCatalogue |
| +} |
| + |
| +// blocks reports whether a match on rule is answered with the block page |
| +// rather than forwarded. |
| +func (m guardMode) blocks(rule *edgeguard.Rule) bool { |
| + switch m { |
| + case guardBlock: |
| + return rule.Mode != edgeguard.ModeBurst |
| + case guardCatalogue: |
| + return rule.Mode == edgeguard.ModeBlock |
| + } |
| + return false |
| +} |
| + |
| +// guardVerdict is what the guard decided about a request that matched a |
| +// rule. frag has already passed through reqrec.Fragment, and is "" when it |
| +// may not be kept; ref is the code on the block page, set only for a block. |
| +type guardVerdict struct { |
| + rule *edgeguard.Rule |
| + frag string |
| + block bool |
| + ref string |
| +} |
| + |
| +// guardState rides a request's outcome when the guard runs for it. ServeHTTP |
| +// sets it, and the observer defer reads the verdict to file one Match in |
| +// place of the plain Response. mint is the edge's mintRef, carried here so |
| +// guardDecide needs no *Edge: the static handler, which has none, decides |
| +// the probe tier for its own routes. |
| +type guardState struct { |
| + mode guardMode |
| + mint func(reqrec.Tier, string) string |
| + verdict *guardVerdict |
| +} |
| + |
| +// guardDecide notes hit as r's verdict and, when the mode blocks the rule, |
| +// answers r with the block page and reports true: the caller must then stop |
| +// serving. It does nothing when the guard is not running for r, or when a |
| +// verdict is already noted, so a request is decided once however many |
| +// places check it. |
| +func guardDecide(w http.ResponseWriter, r *http.Request, hit edgeguard.Hit) (served bool) { |
| + out := outcomeFrom(r) |
| + if out == nil || out.guard == nil || out.guard.verdict != nil || hit.Rule == nil { |
| + return false |
| + } |
| + st := out.guard |
| + v := &guardVerdict{rule: hit.Rule} |
| + if hit.FromQuery { |
| + v.frag, _ = reqrec.Fragment(reqrec.SourceQuery, hit.QueryName, hit.Fragment) |
| + } else { |
| + v.frag, _ = reqrec.Fragment(reqrec.SourcePath, "", hit.Fragment) |
| + } |
| + st.verdict = v |
| + if !st.mode.blocks(hit.Rule) { |
| + return false |
| + } |
| + v.block = true |
| + v.ref = st.mint(hit.Rule.Tier, hit.Rule.ID) |
| + writeGuardBlock(w, v.ref) |
| + return true |
| +} |
| + |
| +// writeGuardBlock writes the block page: a plain 404 that says no more than |
| +// a missing page would, with the reference code in a header and in the |
| +// body, so the visitor can pass it to the site's owner. It is never cached: |
| +// a code names one request. |
| +func writeGuardBlock(w http.ResponseWriter, code string) { |
| + h := w.Header() |
| + h.Set("Content-Type", "text/plain; charset=utf-8") |
| + h.Set("Cache-Control", "no-store") |
| + h.Set("X-Content-Type-Options", "nosniff") |
| + h.Set("X-Carlos-Ref", code) |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprintf(w, "Not found.\n\nIf you expected a page here, send this reference to the site's owner: %s", code) |
| + io.WriteString(w, "\n") |
| +} |
diff --git a/internal/edge/guard_test.go b/internal/edge/guard_test.go| new file mode 100644 |
| index 000000000..fe959acfc |
| --- /dev/null |
| +++ b/internal/edge/guard_test.go |
| @@ -0,0 +1,291 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +func TestGuardModeFromEnv(t *testing.T) { |
| + for v, want := range map[string]guardMode{ |
| + "": guardCatalogue, |
| + "off": guardOff, |
| + " Watch ": guardWatch, |
| + "block": guardBlock, |
| + "bogus": guardCatalogue, |
| + } { |
| + got := guardModeFromEnv(func(k string) string { |
| + if k == "CARLOS_EDGE_PROTECT" { |
| + return v |
| + } |
| + return "" |
| + }) |
| + if got != want { |
| + t.Errorf("CARLOS_EDGE_PROTECT=%q: mode %d, want %d", v, got, want) |
| + } |
| + } |
| +} |
| + |
| +// guardRig is an edge over one route whose upstream and activator count what |
| +// reached them, with a recorder that keeps every record. |
| +type guardRig struct { |
| + e *Edge |
| + rec *memRecorder |
| + upstream *atomic.Int32 |
| + act *fakeActivator |
| + key []byte |
| +} |
| + |
| +// guardEdge builds a guardRig over an instance route for app.test whose |
| +// upstream answers status with body. hibernate puts the route behind a |
| +// counting activator; armed installs a mesh key, so the codes are sealed. |
| +func guardEdge(t *testing.T, hibernate, armed bool, status int, body string) *guardRig { |
| + t.Helper() |
| + g := &guardRig{rec: &memRecorder{}, upstream: new(atomic.Int32), act: &fakeActivator{}} |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + g.upstream.Add(1) |
| + w.WriteHeader(status) |
| + io.WriteString(w, body) |
| + })) |
| + t.Cleanup(backend.Close) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Addr: backend.Listener.Addr().String(), |
| + Status: "ready", Hibernate: hibernate, App: "shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, g.act) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + if armed { |
| + s := meshTestStore(t) |
| + if err := mintMeshKey(context.Background(), s); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := newHomeMap(s, "annie") |
| + refreshHomeMap(t, m) |
| + e.homes.Store(m) |
| + g.key, _ = m.meshKeys() |
| + } |
| + e.EnableRequestRecords(g.rec) |
| + g.e = e |
| + return g |
| +} |
| + |
| +func (g *guardRig) get(path string) *httptest.ResponseRecorder { |
| + w := httptest.NewRecorder() |
| + g.e.ServeHTTP(w, httptest.NewRequest("GET", "http://app.test"+path, nil)) |
| + return w |
| +} |
| + |
| +// In the default mode every rule of catalogue version 1 only watches: the |
| +// probe goes through, the visitor gets the app's own answer, and the one |
| +// record for it is a watch carrying that answer's status. |
| +func TestGuardWatchForwards(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "the app's own 404") |
| + w := g.get("/.env") |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q, upstream %d", w.Code, w.Body.String(), g.upstream.Load()) |
| + } |
| + if w.Header().Get("X-Carlos-Ref") != "" { |
| + t.Fatal("a watched request carried a reference code") |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 { |
| + t.Fatalf("responses %d, matches %d; want 0 and 1", len(g.rec.resp), len(g.rec.match)) |
| + } |
| + m := g.rec.match[0] |
| + if m.Kind != reqrec.KindWatch || m.Tier != reqrec.TierHard || m.RuleID != "hard.secrets.env" || m.Status != 404 || m.Ref != "" { |
| + t.Fatalf("match %+v", m) |
| + } |
| + if m.Fragment != ".env" || m.App != "shop" || m.Path != "/.env" { |
| + t.Fatalf("match %+v", m) |
| + } |
| +} |
| + |
| +// Review Focus 5: a watched probe that a sleeping app wakes for and answers |
| +// 200 is one record, a watch, saying 200 and that it woke the app. |
| +func TestGuardWatchRecordsUpstreamStatus(t *testing.T) { |
| + reg := openReg(t) |
| + rt := registry.Route{Host: "sleepy.example.com", Kind: "instance", Socket: t.TempDir() + "/x.sock", Status: "ready", Hibernate: true, App: "web"} |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, wakingActivator{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := &memRecorder{} |
| + e.EnableRequestRecords(rec) |
| + e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://sleepy.example.com/wp-login.php", nil)) |
| + if len(rec.resp) != 0 || len(rec.match) != 1 { |
| + t.Fatalf("responses %d, matches %d; want 0 and 1", len(rec.resp), len(rec.match)) |
| + } |
| + m := rec.match[0] |
| + if m.Kind != reqrec.KindWatch || m.Status != 200 || !m.WokeKnown || !m.Woke || m.Ref != "" || m.RuleID != "probe.wordpress.wp-login" { |
| + t.Fatalf("match %+v", m) |
| + } |
| +} |
| + |
| +// In block mode a hard-tier probe is answered here with the block page: a |
| +// 404 whose body and header carry one sealed code naming the rule. Nothing |
| +// behind the edge sees the request. |
| +func TestGuardBlockMode(t *testing.T) { |
| + g := guardEdge(t, true, true, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + w := g.get("/.git/config") |
| + if w.Code != 404 { |
| + t.Fatalf("status %d, want 404", w.Code) |
| + } |
| + if ct := w.Header().Get("Content-Type"); ct != "text/plain; charset=utf-8" { |
| + t.Fatalf("Content-Type %q", ct) |
| + } |
| + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { |
| + t.Fatalf("Cache-Control %q", cc) |
| + } |
| + code := w.Header().Get("X-Carlos-Ref") |
| + want := "Not found.\n\nIf you expected a page here, send this reference to the site's owner: " + code |
| + if code == "" || strings.TrimSuffix(w.Body.String(), "\n") != want { |
| + t.Fatalf("code %q, body %q", code, w.Body.String()) |
| + } |
| + ref, err := reqrec.ParseRef(code, g.key) |
| + if err != nil || !ref.Verified || ref.Tier != reqrec.TierHard || ref.RuleHash != reqrec.RuleHash("hard.secrets.git") { |
| + t.Fatalf("code %q: %+v %v", code, ref, err) |
| + } |
| + if g.upstream.Load() != 0 || g.act.served != 0 { |
| + t.Fatalf("upstream %d, activator %d; want neither called", g.upstream.Load(), g.act.served) |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 { |
| + t.Fatalf("responses %d, matches %d; want 0 and 1", len(g.rec.resp), len(g.rec.match)) |
| + } |
| + m := g.rec.match[0] |
| + if m.Kind != reqrec.KindBlock || m.Ref != code || m.Status != 404 || !m.WokeKnown || m.Woke || m.RuleID != "hard.secrets.git" { |
| + t.Fatalf("match %+v", m) |
| + } |
| +} |
| + |
| +// Block mode still never blocks a burst rule: an admin page is a normal |
| +// thing to visit once, so it is forwarded and only watched. |
| +func TestGuardBlockModeSparesBurst(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusOK, "admin page") |
| + g.e.guard = guardBlock |
| + w := g.get("/admin") |
| + if w.Code != 200 || w.Body.String() != "admin page" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q, upstream %d", w.Code, w.Body.String(), g.upstream.Load()) |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 1 || g.rec.match[0].Kind != reqrec.KindWatch || g.rec.match[0].RuleID != "probe.admin.admin" { |
| + t.Fatalf("responses %+v, matches %+v", g.rec.resp, g.rec.match) |
| + } |
| +} |
| + |
| +// The guard answers before the password gate and before the cache: a probe |
| +// on a gated route gets the block page rather than the login page, and a |
| +// response cached for the probe's path is never served. |
| +func TestGuardBeforeGateAndCache(t *testing.T) { |
| + cached := func(e *Edge, host string) { |
| + e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + e.cache.Put(CacheKey{Host: host, Method: "GET", Path: "/.env"}, "", &CachedResponse{ |
| + StatusCode: 200, Header: http.Header{"Content-Type": {"text/plain"}}, Body: []byte("cached secret"), |
| + StoredAt: time.Now(), TTL: time.Minute, |
| + }) |
| + } |
| + |
| + e, srv, _, _ := gatedEdge(t, &fakeActivator{}, false) |
| + e.guard = guardBlock |
| + cached(e, "gated.example.com") |
| + resp := doHost(t, srv, http.MethodGet, "gated.example.com", "/.env", "") |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 404 || resp.Header.Get("X-Carlos-Ref") == "" || strings.Contains(string(b), "cached secret") { |
| + t.Fatalf("gated route: %d ref %q body %q", resp.StatusCode, resp.Header.Get("X-Carlos-Ref"), b) |
| + } |
| + |
| + // An ungated route would serve the cached entry if the guard came after |
| + // the cache, so this is the half that shows the order. |
| + g := guardEdge(t, false, false, http.StatusOK, "app") |
| + g.e.guard = guardBlock |
| + cached(g.e, "app.test") |
| + w := g.get("/.env") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || strings.Contains(w.Body.String(), "cached secret") { |
| + t.Fatalf("ungated route: %d %q", w.Code, w.Body.String()) |
| + } |
| + // The control: with the guard off the same request is a cache hit, so |
| + // the entry above is one the cache would have served. |
| + g.e.guard = guardOff |
| + if w := g.get("/.env"); w.Body.String() != "cached secret" { |
| + t.Fatalf("control: %d %q, want the cached entry", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +// With protection off, a probe is an ordinary request: forwarded, and filed |
| +// as a plain response. |
| +func TestGuardOffDoesNothing(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "the app's own 404") |
| + g.e.guard = guardOff |
| + w := g.get("/.env") |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q, upstream %d", w.Code, w.Body.String(), g.upstream.Load()) |
| + } |
| + if len(g.rec.resp) != 1 || len(g.rec.match) != 0 { |
| + t.Fatalf("responses %d, matches %d; want 1 and 0", len(g.rec.resp), len(g.rec.match)) |
| + } |
| +} |
| + |
| +// A request delivered over a tunnel was already checked by the hub that |
| +// forwarded it, which also records it, so this box neither blocks nor |
| +// records it, even in block mode. |
| +func TestGuardSkipsTunnelDelivered(t *testing.T) { |
| + g := guardEdge(t, false, false, http.StatusNotFound, "the app's own 404") |
| + g.e.guard = guardBlock |
| + w := httptest.NewRecorder() |
| + tunnelclient.Mark(g.e).ServeHTTP(w, httptest.NewRequest("GET", "http://app.test/.env", nil)) |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || w.Header().Get("X-Carlos-Ref") != "" || g.upstream.Load() != 1 { |
| + t.Fatalf("got %d %q ref %q, upstream %d", w.Code, w.Body.String(), w.Header().Get("X-Carlos-Ref"), g.upstream.Load()) |
| + } |
| + if len(g.rec.resp) != 0 || len(g.rec.match) != 0 { |
| + t.Fatalf("responses %d, matches %d; want none", len(g.rec.resp), len(g.rec.match)) |
| + } |
| +} |
| + |
| +// outcomeActivator keeps the outcome of the request it serves, so a test can |
| +// see what the guard left on it. |
| +type outcomeActivator struct{ out *outcome } |
| + |
| +func (a *outcomeActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool { |
| + a.out = outcomeFrom(r) |
| + w.WriteHeader(http.StatusOK) |
| + return true |
| +} |
| +func (a *outcomeActivator) RetireExcept(map[string]bool) {} |
| + |
| +// An ordinary request matches no rule: it is filed as a plain response and |
| +// the guard leaves no verdict on it. |
| +func TestGuardOrdinaryRequestUntouched(t *testing.T) { |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Socket: t.TempDir() + "/x.sock", Status: "ready", Hibernate: true, App: "shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + act := &outcomeActivator{} |
| + e, err := New(reg, act) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := &memRecorder{} |
| + e.EnableRequestRecords(rec) |
| + e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/blog/post", nil)) |
| + if len(rec.resp) != 1 || len(rec.match) != 0 { |
| + t.Fatalf("responses %d, matches %d; want 1 and 0", len(rec.resp), len(rec.match)) |
| + } |
| + if act.out == nil || act.out.guard == nil || act.out.guard.verdict != nil { |
| + t.Fatalf("outcome %+v: want the guard run and no verdict", act.out) |
| + } |
| +} |
diff --git a/internal/edge/reqrecords.go b/internal/edge/reqrecords.go| index 15c6121c7..4a9d5a812 100644 |
| --- a/internal/edge/reqrecords.go |
| +++ b/internal/edge/reqrecords.go |
| @@ -31,9 +31,9 @@ func (e *Edge) EnableRequestRecords(rec RequestRecorder) { |
| e.requestRecords.Store(&requestRecorderRef{rec}) |
| } |
| -// requestResponse is the Response for r on rt, shared by the observer defer |
| -// and recordMatch so a match and a plain response describe a request the |
| -// same way. Woke is left for the caller: only the defer knows it. When is |
| +// requestResponse is the Response for r on rt, shared by the observer |
| +// defer's plain responses and matches so both describe a request the same |
| +// way. Woke is left for the caller: only the defer knows it. When is |
| // left zero, so the recorder stamps it from its own clock; the environment |
| // is the route's as it was when this request was served. |
| func requestResponse(rt registry.Route, r *http.Request, status int) reqrec.Response { |
| @@ -69,32 +69,36 @@ func (e *Edge) observeRecords(rt registry.Route, viaTunnel bool, r *http.Request |
| status = http.StatusOK // nothing written: net/http answers 200 |
| } |
| x := requestResponse(rt, r, status) |
| + // A request a protection rule matched is filed as one Match in place of |
| + // the Response, never both: the Match carries the same response, so a |
| + // second record would count the request twice. |
| + if out != nil && out.guard != nil && out.guard.verdict != nil { |
| + v := out.guard.verdict |
| + kind := reqrec.KindWatch |
| + if v.block { |
| + // A blocked request never reached the activator, so it woke |
| + // nothing, and that is known on whichever box answered it. |
| + kind = reqrec.KindBlock |
| + x.WokeKnown, x.Woke = true, false |
| + } else { |
| + // A watched one was forwarded like any other request, so what |
| + // it woke is known exactly as for a plain response. |
| + x.WokeKnown, x.Woke = !viaTunnel, out.woke |
| + } |
| + ref.Match(reqrec.Match{Response: x, Kind: kind, Tier: v.rule.Tier, RuleID: v.rule.ID, Fragment: v.frag, Ref: v.ref}) |
| + return |
| + } |
| x.WokeKnown = !viaTunnel |
| x.Woke = out != nil && out.woke |
| ref.Response(x) |
| } |
| -// recordMatch files a Match for a request a protection rule blocked (kind |
| -// KindBlock) or only watched (KindWatch), and returns the reference code the |
| -// block page shows. The code is sealed with the current mesh key when this |
| -// box has one, and unsealed otherwise, so a box outside the mesh can still |
| -// show one. It is returned even when recording is off: the visitor's page |
| -// does not depend on whether anything was written. |
| -// |
| -// frag must already have passed through reqrec.Fragment. |
| -func (e *Edge) recordMatch(rt registry.Route, r *http.Request, kind reqrec.Kind, tier reqrec.Tier, ruleID, frag string, status int) string { |
| +// mintRef returns the reference code for a block by the rule ruleID of tier. |
| +// The code is sealed with the current mesh key when this box has one, and |
| +// unsealed otherwise, so a box outside the mesh can still show one. Minting |
| +// writes nothing: the visitor's page does not depend on whether recording |
| +// is on, and the observer defer files the Match that carries the code. |
| +func (e *Edge) mintRef(tier reqrec.Tier, ruleID string) string { |
| key, _ := e.homes.Load().meshKeys() |
| - code := reqrec.NewRef(time.Now(), tier, ruleID, e.box, key) |
| - ref := e.requestRecords.Load() |
| - if ref == nil { |
| - return code |
| - } |
| - x := requestResponse(rt, r, status) |
| - // A blocked request never reaches the activator, so it woke nothing, and |
| - // that is known on whichever box answers it. A watched one is forwarded |
| - // and may wake the app, which nothing passed in here says, so its record |
| - // leaves woke out rather than claim it did not. |
| - x.WokeKnown = kind == reqrec.KindBlock |
| - ref.Match(reqrec.Match{Response: x, Kind: kind, Tier: tier, RuleID: ruleID, Fragment: frag, Ref: code}) |
| - return code |
| + return reqrec.NewRef(time.Now(), tier, ruleID, e.box, key) |
| } |
diff --git a/internal/edge/reqrecords_test.go b/internal/edge/reqrecords_test.go| index 16ad3ef9b..3ff1860bd 100644 |
| --- a/internal/edge/reqrecords_test.go |
| +++ b/internal/edge/reqrecords_test.go |
| @@ -24,25 +24,36 @@ func TestRecordsSeeAppNotFound(t *testing.T) { |
| e := edgeWithBackend(t, http.NotFoundHandler()) |
| rec := &memRecorder{} |
| e.EnableRequestRecords(rec) |
| - req := httptest.NewRequest("GET", "http://app.test/wp-login.php?x=1", nil) |
| + req := httptest.NewRequest("GET", "http://app.test/old-page.html?x=1", nil) |
| e.ServeHTTP(httptest.NewRecorder(), req) |
| - if len(rec.resp) != 1 || rec.resp[0].Status != 404 || rec.resp[0].Path != "/wp-login.php" || rec.resp[0].RawQuery != "x=1" || !rec.resp[0].WokeKnown { |
| + if len(rec.resp) != 1 || rec.resp[0].Status != 404 || rec.resp[0].Path != "/old-page.html" || rec.resp[0].RawQuery != "x=1" || !rec.resp[0].WokeKnown { |
| t.Fatalf("got %+v", rec.resp) |
| } |
| } |
| -// The edge leaves When unset: the recorder stamps it with its own clock, so |
| -// one clock decides which minute a request lands in. |
| +// The edge leaves When unset, on a plain response and on a match alike: the |
| +// recorder stamps it with its own clock, so one clock decides which minute a |
| +// request lands in. A match also carries the route's environment as it was |
| +// when the request was served, as a plain response does. |
| func TestRecordsLeaveWhenToTheRecorder(t *testing.T) { |
| e := edgeWithBackend(t, http.NotFoundHandler()) |
| + if err := e.reg.SetEnvironment("app.test", "staging"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.guard = guardBlock |
| rec := &memRecorder{} |
| e.EnableRequestRecords(rec) |
| e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/x", nil)) |
| - rt := registry.Route{Host: "app.test", App: "shop"} |
| - e.recordMatch(rt, httptest.NewRequest("GET", "http://app.test/.env", nil), reqrec.KindBlock, reqrec.TierHard, "dotenv", "", 404) |
| + e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "http://app.test/.env", nil)) |
| if len(rec.resp) != 1 || !rec.resp[0].When.IsZero() || len(rec.match) != 1 || !rec.match[0].When.IsZero() { |
| t.Fatalf("resp %+v match %+v", rec.resp, rec.match) |
| } |
| + if rec.match[0].Environment != "staging" { |
| + t.Fatalf("environment %q, want the route's", rec.match[0].Environment) |
| + } |
| } |
| // The hub that forwarded a request over the tunnel records it; the box it |
| @@ -58,36 +69,41 @@ func TestRecordsSkipTunnelDelivered(t *testing.T) { |
| } |
| } |
| -// recordMatch seals its reference code with the mesh key, so the code it |
| -// hands back verifies against that key and is the one the match carries. |
| -func TestRecordMatchReturnsSealedCode(t *testing.T) { |
| +// mintRef seals its reference code with the mesh key, so the code verifies |
| +// against that key and names the tier and rule it was minted for. |
| +func TestMintRefSealed(t *testing.T) { |
| e, _, key := proofEdge(t, true) |
| - rec := &memRecorder{} |
| - e.EnableRequestRecords(rec) |
| - rt := registry.Route{Host: "app.test", App: "shop"} |
| - rt.Environment = "staging" |
| - code := e.recordMatch(rt, httptest.NewRequest("GET", "http://app.test/.env", nil), reqrec.KindBlock, reqrec.TierHard, "dotenv", "", 404) |
| + code := e.mintRef(reqrec.TierHard, "hard.secrets.env") |
| r, err := reqrec.ParseRef(code, key) |
| - if err != nil || !r.Verified || len(rec.match) != 1 || rec.match[0].Ref != code { |
| - t.Fatalf("code %q: %+v %v; matches %d", code, r, err, len(rec.match)) |
| - } |
| - if rec.match[0].Environment != "staging" { |
| - t.Fatalf("environment %q, want the route's", rec.match[0].Environment) |
| + if err != nil || !r.Verified || r.Tier != reqrec.TierHard || r.RuleHash != reqrec.RuleHash("hard.secrets.env") { |
| + t.Fatalf("code %q: %+v %v", code, r, err) |
| } |
| } |
| -// With recording off, recordMatch still hands back a code: the block page |
| -// shows it whether or not anything was written. With no home map there is no |
| -// mesh key, so the code is unsealed rather than missing. |
| -func TestRecordMatchCodeWithoutRecorder(t *testing.T) { |
| +// With no home map there is no mesh key, so mintRef hands back an unsealed |
| +// code rather than none: the block page shows one either way, and whether |
| +// anything is recorded does not change it. |
| +func TestMintRefUnsealed(t *testing.T) { |
| e, _, _ := proofEdge(t, false) |
| - rt := registry.Route{Host: "app.test", App: "shop"} |
| - code := e.recordMatch(rt, httptest.NewRequest("GET", "http://app.test/.env", nil), reqrec.KindBlock, reqrec.TierHard, "dotenv", "", 404) |
| + code := e.mintRef(reqrec.TierHard, "hard.secrets.env") |
| if r, err := reqrec.ParseRef(code); err != nil || r.Sealed || r.Tier != reqrec.TierHard { |
| t.Fatalf("code %q: %+v %v", code, r, err) |
| } |
| } |
| +// In block mode with recording off, the visitor still gets the block page |
| +// and its code: the page does not depend on whether anything was written. |
| +func TestGuardBlockWithoutRecorder(t *testing.T) { |
| + e := edgeWithBackend(t, http.NotFoundHandler()) |
| + e.guard = guardBlock |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, httptest.NewRequest("GET", "http://app.test/.env", nil)) |
| + code := w.Header().Get("X-Carlos-Ref") |
| + if r, err := reqrec.ParseRef(code); w.Code != 404 || err != nil || r.Tier != reqrec.TierHard { |
| + t.Fatalf("%d, code %q: %+v %v", w.Code, code, r, err) |
| + } |
| +} |
| + |
| // wakingActivator answers every request as an activator that woke the |
| // instance for it would: MarkWoke, the call internal/activator's begin makes |
| // for the request that starts a wake, then the app's answer. |
diff --git a/internal/host/reqrec_e2e_test.go b/internal/host/reqrec_e2e_test.go| index 3a10edf3d..e797e170c 100644 |
| --- a/internal/host/reqrec_e2e_test.go |
| +++ b/internal/host/reqrec_e2e_test.go |
| @@ -35,9 +35,11 @@ func TestRequestRecordsEndToEnd(t *testing.T) { |
| get := func(path string) { t.Helper(); x.serve("GET", path, clientAddr) } |
| // The reset link goes first so it is inside the 60-record sample, which |
| // is the case where the token would leak if masking were not applied. |
| + // The missing page is one no protection rule matches: a probe path such |
| + // as /wp-login.php is filed as a watch match, not a not-found record. |
| get("/reset/" + token) |
| for i := 0; i < 70; i++ { |
| - get("/wp-login.php") |
| + get("/old-page.html") |
| } |
| x.flush() |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index e89154183..baf66869a 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -77,6 +77,8 @@ var Optional = []string{ |
| "CARLOS_BACKHAUL_MAX_INFLIGHT", |
| "CARLOS_DNS_PROVIDER", |
| "CARLOS_EDGE_GZIP", |
| + "CARLOS_EDGE_PROTECT", |
| + "CARLOS_EDGE_RECORDS", |
| "CARLOS_HIBERNATE_IDLE", |
| "CARLOS_HIBERNATE_PREFIX", |
| "CARLOS_HOST_CLAIM_RETIRED_LOCATIONS", |