fix: classify bracketed demo hosts and close no-write exits
Match demo classification to router host parsing and refuse malformed demo authorities with 400 DEMO-GONE. Sanitize initial response headers for no-write exits, and cover bracketed hosts, post-lookup publication and implicit HTTP responses.
internal/edge/demo.go+11 −3internal/edge/demo_response.go+7 −2internal/edge/demo_response_test.go+90 −0internal/edge/edge.go+3 −1
CI failed — run details
Intent
<task-notification> <task-id>ab0fcd2bda445d3bc</task-id> <tool-use-id>toolu_019H5q9QoheuoD82GmjzivY8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/ab0fcd2bda445d3bc.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (Opus)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Task 1 (commit 849f5b87) needs one fix before it passes. It is READY AFTER FIXES: no P1, one P2 and five P3s. The targeted `TestDemo` tests pass. - **Spec verdict:** issues found, one P2. The rest of the brief is met, and serving stays closed until Tasks 3 and 4. - **Quality verdict:** needs fixes. - **Counts:** P1 0, P2 1, P3 5. **P2-1 (one host normalisation for demo classification; trust boundary is the client's Host header):** - **Problem:** the demo check at request entry (`demoAuthority`, `internal/edge/demo.go:18`) cuts the Host header at the first `:`. The router later uses `net.SplitHostPort`, which accepts any text in brackets. So a Host like `[unknown.demos.example.com]:443` skips the demo check but is still routed as `unknown.demos.example.com`. - **Effect:** unknown, apex and invalid marked demo names get the ordinary fallback 302, with no demo policy headers. This happens on both the HTTPS and port 80 handlers. No demo content is served, nothing reaches the app and no cookies leak, which is why it is P2 rather than P1. - **Evidence:** I confirmed it with a throwaway test run through `go test -overlay`. Nothing was written to the worktree, and the scratch is deleted. - **Fix:** run the demo check on the host the router actually uses (`SplitHostPort`, then lowercase and trim the trailing dot), and treat a bracketed name as invalid unless it is an IPv6 address. Add four bracketed rows to `TestDemoPolicyEveryExit`. **Deferred to later tasks:** - **Task 3:** - When forwarding is switched on, proxy and tunnel failures must also go through the policy writer. Today nothing is forwarded, so nothing tests them. - The writer offers no write deadline, which the five-second write limit will need. - A handler that returns without writing anything would send a 200 with no policy headers (P3-1). - **Task 4:** when the serving gate opens, requests on port 80 must still only redirect to HTTPS. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-2/.superpowers/sdd/2026-11-04-agent-start-demo-2-edge-protections/task-1-review-r1.md`.</result> <usage><subagent_tokens>121567</subagent_tokens><tool_uses>19</tool_uses><duration_ms>354055</duration_ms></usage> </task-notification>
Attributed to this commit: 10.2 g CO₂e (1,203,622 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/edge/demo.go b/internal/edge/demo.go| index c5ba078c4..97dbef23f 100644 |
| --- a/internal/edge/demo.go |
| +++ b/internal/edge/demo.go |
| @@ -1,6 +1,7 @@ |
| package edge |
| import ( |
| + "net" |
| "net/http" |
| "os" |
| "strconv" |
| @@ -16,11 +17,18 @@ import ( |
| // Only a valid authority can select a route. Ordinary requests keep their |
| // existing host handling; this normalization is solely for demo refusal. |
| func demoAuthority(authority string) (host string, valid bool) { |
| - name := strings.ToLower(strings.TrimSpace(authority)) |
| + name := authority |
| + if h, _, err := net.SplitHostPort(name); err == nil { |
| + name = h |
| + } |
| + name = strings.ToLower(strings.TrimSpace(name)) |
| if i := strings.LastIndexByte(name, '@'); i >= 0 { |
| name = name[i+1:] |
| } |
| - if i := strings.IndexAny(name, ":/\\?#"); i >= 0 { |
| + // Also classify bracketed names without a valid host:port split. DNS |
| + // names in brackets cannot match either valid raw spelling below. |
| + name = strings.TrimPrefix(name, "[") |
| + if i := strings.IndexAny(name, "]:/\\?#"); i >= 0 { |
| name = name[:i] |
| } |
| host = strings.TrimRight(name, ".") |
| @@ -85,7 +93,7 @@ func (e *Edge) refuseDemoRequest(w http.ResponseWriter, r *http.Request) bool { |
| } |
| w = e.beginDemoResponse(w, r) |
| if !valid { |
| - serveDemoPlain(w, r, http.StatusBadRequest, "DEMO-RESPONSE") |
| + serveDemoPlain(w, r, http.StatusBadRequest, "DEMO-GONE") |
| } else if !ok || !up.route.IsDemo() || !e.demoRouteOK(host, up.route) || up.alias || up.platformAlias { |
| serveDemoPlain(w, r, http.StatusNotFound, "DEMO-GONE") |
| } else { |
diff --git a/internal/edge/demo_response.go b/internal/edge/demo_response.go| index 8dd9e5d6d..a27d61573 100644 |
| --- a/internal/edge/demo_response.go |
| +++ b/internal/edge/demo_response.go |
| @@ -158,7 +158,8 @@ func demoLocationOK(location, host string) bool { |
| } |
| // demoResponseWriter never embeds or unwraps its destination. Headers are |
| -// copied once, at the final status; later app mutations cannot become trailers. |
| +// sanitized at entry and copied at the final status; later app mutations |
| +// cannot become trailers. |
| // Flush is supported for streams, but neither Hijack nor full-duplex access is. |
| type demoResponseWriter struct { |
| dst http.ResponseWriter |
| @@ -172,7 +173,11 @@ func (e *Edge) beginDemoResponse(w http.ResponseWriter, r *http.Request) http.Re |
| if _, ok := w.(*demoResponseWriter); ok { |
| return w |
| } |
| - return &demoResponseWriter{dst: w, header: w.Header().Clone(), request: r} |
| + header := w.Header().Clone() |
| + // net/http commits an implicit 200 if the handler never writes. Install |
| + // policy now, while keeping the original headers for final validation. |
| + _ = sanitizeDemoHeaders(w.Header(), r.Host) |
| + return &demoResponseWriter{dst: w, header: header, request: r} |
| } |
| func (w *demoResponseWriter) Header() http.Header { return w.header } |
diff --git a/internal/edge/demo_response_test.go b/internal/edge/demo_response_test.go| index 0e01d4cc5..bb836a429 100644 |
| --- a/internal/edge/demo_response_test.go |
| +++ b/internal/edge/demo_response_test.go |
| @@ -1,6 +1,7 @@ |
| package edge |
| import ( |
| + "context" |
| "errors" |
| "fmt" |
| "io" |
| @@ -104,6 +105,10 @@ func TestDemoPolicyEveryExit(t *testing.T) { |
| {"shop.demos.example.com.", 400}, {"shop.demos.example.com:bad", 400}, |
| {"shop.demos.example.com:443:80", 400}, |
| {bad.Host, 404}, {"MARKED.EXAMPLE.COM:443", 404}, {"alias.example.com", 404}, |
| + {"[unknown.demos.example.com]:443", 400}, {"[demos.example.com]:443", 400}, |
| + {"[MARKED.EXAMPLE.COM]:443", 400}, {"[" + host + "]:443", 400}, |
| + {"[" + strings.ToUpper(host) + "]:443", 400}, {"[shop.demos.example.com.]:443", 400}, |
| + {"[unknown.demos.example.com]", 400}, {"[unknown.demos.example.com]:bad", 400}, |
| } { |
| for _, method := range []string{http.MethodGet, http.MethodHead} { |
| for _, handler := range []http.Handler{e, e.httpFallbackHandler(), http.HandlerFunc(e.unknownHost)} { |
| @@ -121,9 +126,41 @@ func TestDemoPolicyEveryExit(t *testing.T) { |
| if method == http.MethodHead && rec.Body.Len() != 0 { |
| t.Error("HEAD body") |
| } |
| + if method == http.MethodGet && tc.status == 400 && rec.Body.String() != demoCopy["DEMO-GONE"]+"\n" { |
| + t.Errorf("%s: malformed authority body = %q", tc.host, rec.Body.String()) |
| + } |
| } |
| } |
| } |
| + t.Run("bracketed-marked-post-lookup", func(t *testing.T) { |
| + // Publish this marked row between entry and route lookup. A context |
| + // read provides a synchronous boundary without a production test hook. |
| + names, routes := e.demoNames.Load(), e.upstreams.Load() |
| + t.Cleanup(func() { e.demoNames.Store(names); e.upstreams.Store(routes) }) |
| + e.demoNames.Store(&map[string]bool{}) |
| + e.upstreams.Store(&map[string]upstream{}) |
| + published := false |
| + ctx := &demoPublishContext{Context: context.Background(), publish: func() { |
| + published = true |
| + e.upstreams.Store(&map[string]upstream{bad.Host: {route: bad, proxy: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| + t.Error("post-lookup demo dispatched") |
| + })}}) |
| + }} |
| + r := httptest.NewRequest(http.MethodGet, "https://example.com/path", nil).WithContext(ctx) |
| + r.Host = "[" + bad.Host + "]:443" |
| + rec := httptest.NewRecorder() |
| + e.ServeHTTP(rec, r) |
| + if !published { |
| + t.Fatal("request did not pass the entry check") |
| + } |
| + if rec.Code != http.StatusBadRequest || rec.Body.String() != demoCopy["DEMO-GONE"]+"\n" { |
| + t.Errorf("post-lookup refusal = %d %q", rec.Code, rec.Body.String()) |
| + } |
| + assertDemoPolicy(t, rec.Result().Header) |
| + if rec.Header().Get("Location") != "" { |
| + t.Error("post-lookup fallback redirect") |
| + } |
| + }) |
| // Even a stale map entry that escaped reload filtering cannot dispatch. |
| m := e.current() |
| m[bad.Host] = upstream{route: bad, proxy: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("invalid demo dispatched") })} |
| @@ -169,6 +206,59 @@ func TestDemoPolicyEveryExit(t *testing.T) { |
| assertDemoPolicy(t, rec.Header()) |
| } |
| +type demoPublishContext struct { |
| + context.Context |
| + publish func() |
| +} |
| + |
| +func (c *demoPublishContext) Value(key any) any { |
| + if publish := c.publish; publish != nil { |
| + c.publish = nil |
| + publish() |
| + } |
| + return c.Context.Value(key) |
| +} |
| + |
| +func TestDemoPolicyNoWrite(t *testing.T) { |
| + server := httptest.NewServer(http.HandlerFunc(func(dst http.ResponseWriter, r *http.Request) { |
| + dst.Header().Set("Content-Security-Policy", "default-src *") |
| + dst.Header().Set("Refresh", "0; url=https://example.com/") |
| + dst.Header().Set("Location", "https://example.com/") |
| + dst.Header().Set("Trailer", "Set-Cookie, Content-Security-Policy") |
| + dst.Header().Set("Trailer:Set-Cookie", "late=1; Domain=example.com") |
| + dst.Header().Set("Set-Cookie", "sid=one; Domain=example.com; HttpOnly") |
| + w := new(Edge).beginDemoResponse(dst, r) |
| + w.Header().Set("Content-Security-Policy", "default-src *") |
| + w.Header().Set("Set-Cookie", "late=2; Domain=example.com") |
| + // Return without Write, WriteHeader or Flush: net/http commits 200. |
| + })) |
| + t.Cleanup(server.Close) |
| + resp, err := server.Client().Get(server.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 200 || len(body) != 0 { |
| + t.Errorf("response = %d %q", resp.StatusCode, body) |
| + } |
| + assertDemoPolicy(t, resp.Header) |
| + for _, key := range []string{"Refresh", "Location", "Trailer", "Trailer:Set-Cookie"} { |
| + if resp.Header.Get(key) != "" { |
| + t.Errorf("unsafe header survived: %s", key) |
| + } |
| + } |
| + if got := resp.Header.Values("Set-Cookie"); !reflect.DeepEqual(got, []string{"sid=one; HttpOnly"}) { |
| + t.Errorf("cookies = %v", got) |
| + } |
| + if len(resp.Trailer) != 0 { |
| + t.Errorf("trailers = %v", resp.Trailer) |
| + } |
| +} |
| + |
| func TestDemoCookieRewrite(t *testing.T) { |
| h := http.Header{"Set-Cookie": { |
| "sid=one; Domain=example.com; Path=/; dOmAiN=.demos.example.com; Secure; HttpOnly; SameSite=Lax", |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 6ebc4c915..69bc13f9f 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -2004,7 +2004,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // no marked route may enter ordinary dispatch even outside the demo zone. |
| if ok && up.route.IsDemo() { |
| status, copyID := http.StatusNotFound, "DEMO-GONE" |
| - if e.demoRouteOK(host, up.route) && !up.alias && !up.platformAlias { |
| + if _, valid := demoAuthority(r.Host); !valid { |
| + status = http.StatusBadRequest |
| + } else if e.demoRouteOK(host, up.route) && !up.alias && !up.platformAlias { |
| status, copyID = http.StatusServiceUnavailable, "DEMO-UNAVAILABLE" |
| } |
| serveDemoPlain(w, r, status, copyID) |