fix: preserve demo claim attribution through the site API
Capture verified claim IPs before body reads, cover all claim paths through local and cross-box delivery, and close early publish refusals promptly. Validate assembled demo origin pairs before host.env writes.
9 files changed,
+344
−42
docs/superpowers/plans/2026-11-05-demo-api-site-route.md+3 −3internal/console/apidemo.go+8 −8internal/console/demo_api_alias_integration_test.go+132 −24internal/console/demo_api_origin_test.go+40 −4internal/console/demo_claim_auth.go+16 −2internal/edge/demo_api_integration_test.go+76 −1internal/hostenv/group.go+3 −0internal/hostenv/hostenv.go+15 −0internal/hostenv/hostenv_test.go+51 −0
diff --git a/docs/superpowers/plans/2026-11-05-demo-api-site-route.md b/docs/superpowers/plans/2026-11-05-demo-api-site-route.md| index 42c6945c0..7ad85ddc5 100644 |
| --- a/docs/superpowers/plans/2026-11-05-demo-api-site-route.md |
| +++ b/docs/superpowers/plans/2026-11-05-demo-api-site-route.md |
| @@ -39,7 +39,7 @@ All implementation choices below are **my call**. This is a general deployment c |
| |---|---| |
| | `POST /api/demo/apps` | Create and bearer-token update share this handler (`internal/console/apidemo.go:276`, `:328`). | |
| | `GET /api/demo/jobs/{jobID}` | Exactly one nonempty base64url-alphabet segment; leave token-length/existence validation and its response to the console (`internal/console/apidemo.go:280`, `:526`; `internal/demobuild/job.go:68`). | |
| -| Future: `POST /api/demo/claims`, `POST /api/demo/claims/verify`, `POST /api/demo/claims/select`, `GET /api/demo/claims/status` | Inventory only: `agent-start-demo-3:internal/console/apidemo.go:272`. Plan 3's declared contract is in `docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md:72`. Add these four entries and contract tests in a small follow-up **after Plan 3 merges**. No review or implementation dependency on its unmerged code. | |
| +| `POST /api/demo/claims`, `POST /api/demo/claims/verify`, `POST /api/demo/claims/select`, `GET /api/demo/claims/status` | Done: paths and gates in e12fe9a1; delivery, attribution and origin witnesses in `demo-api-claim-paths`. | |
| The reservation includes `/api/demo` and `/api/demo/`. An unlisted method/path, HEAD, OPTIONS, upgrade, query (including bare `?`), escaped path, dot segment, repeated slash or trailing slash gets an empty, uncached 404 on the site, without console dispatch or static fallback. Detect the reservation in both decoded and cleaned paths, then require the original canonical spelling; never redirect a malformed spelling into an allowed operation. The supported requests need no query. GET's implicit HEAD registration in Go does not enlarge this allowlist. |
| @@ -85,7 +85,7 @@ Keep one small private-header streaming writer with `Unwrap()` and flush support |
| The alias bypasses `admissionRefuses` (matching ordinary backhaul on the forward leg), site/tenant probe-burst counters, request-protection catalogue, password gates, usage billing, asset cache, shared response cache, gzip and static tree caches. Retain **`rateAdmit` on local console delivery, including verified hops**, console create/status/claim limits and cross-box containment. The hook skips edge abuse/5xx records (`observeRecords`/`emitEdgeError`, `internal/edge/edge.go:2378`). This is an intentional narrow security-policy choice, reviewed in Task 2, not an exemption transferable to other paths. Those layers normally run at `internal/edge/edge.go:2391`, `:2443`, `:2552`, `:2567`, `:2621`, `:2638`. Static kinds already bypass shared caching, but that alone does not cover the earlier asset catch. Explicit outbound identity encoding prevents transport-added gzip/decompression; skip edge recompression and keep the existing pooled transports. HTTP/2 clients stream through the existing HTTP/1.1 backhaul (`internal/edge/edge.go:4297`); no HTTP/2 hop or buffering is required. No body limit is duplicated; console timeout, archive cap and 413 body remain at `internal/console/apidemo.go:317`, `:389`. |
| -No CORS grant or Origin rewrite is added. The current anonymous handlers are directly registered, outside account/session/CSRF wrappers (`internal/console/apidemo.go:276`). Stripping cookies cannot confer account authority; a console bearer remains limited by the actual handler. Rewriting Host to the configured canonical console avoids retired-host redirects (`internal/console/server.go:2352`). Browser claim/report CSRF doors are excluded. The post-merge claim follow-up must apply the same proof gate and prove absent-Origin agent requests work and hostile Origin requests keep the merged console's refusal; never loosen its checks to accommodate this alias. |
| +No CORS grant or Origin rewrite is added. The current anonymous handlers are directly registered, outside account/session/CSRF wrappers (`internal/console/apidemo.go:276`). Stripping cookies cannot confer account authority; a console bearer remains limited by the actual handler. Rewriting Host to the configured canonical console avoids retired-host redirects (`internal/console/server.go:2352`). Browser claim/report CSRF doors are excluded. Claim proof gates landed in e12fe9a1; `demo-api-claim-paths` proves absent-Origin agent requests and hostile-Origin refusals. |
| ## Task 1: Configure public agent links and operator ownership |
| @@ -148,7 +148,7 @@ Restore Plan 4's previous build first if consumers switched. Clear `CONSOLE_DEMO |
| 1. **Dev, landing day:** inspect the current routes, fleet/ingress inventory and console configuration through console/CLI before choosing destinations. Checked-in evidence names dev console box `carlos-dev-ie` (`README.md:280`; the deployment file calls it sophie at `/home/paulca/amadan.net/carlos/platform-infrastructure/dev/region-ie.tf:24`). These are topology hints, not live verification. Set `SITE_ORIGIN` to the actual dev static-site origin and `CONSOLE_ORIGIN` to the configured canonical dev console origin, currently documented as `https://platform.dev.carlosframework.com` (`README.md:282`). First confirm the site host is already claimed by the intended account; preserve that claim, static release and region placement. |
| 2. **Edges before console.** Confirm group/replacement bootstrap releases include the new hostenv allowlist before adding operator parameters. Immediately before rolling each edge, place both settings in its root-owned host.env: group boxes use the reviewed `system host-env write --group` without `--install`; fixed boxes use their existing file workflow. Set `CARLOS_DEMO_API_ORIGIN=<SITE_ORIGIN>` and `CARLOS_DEMO_API_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>` in operator parameters for future group/replacement boots too. `hostenv.Split` (`internal/hostenv/hostenv.go:331`) places both names in region scope, so write both in every participating region of a multi-region deployment. The old edge binary ignores them; the roll's own restart reads them. **Stop at the first box** until startup, ordinary tenant traffic, alias 404 and forwarded status pass; stop on failure, never continue fleet-wide. Cover every public ingress and console home edge, then install console `40-demo-api.conf` with `Environment="CONSOLE_DEMO_API_ORIGIN=<SITE_ORIGIN>"` just before the console roll's restart, including daemon-reload. Until then links retain console origin. No extra edge restart, worker roll or mesh-key grant; keep other console/protection settings unchanged (`README.md:276`). |
| 3. Witness **every public ingress**, using the new binary and actual TLS host: `/start`, unknown `/api/demo/not-a-route` gets the alias's empty plain 404/no-store, and a well-formed unknown job gets console JSON 404/no-store. Stop if any ingress fails. Verify actual create/status/update, console 413/429, no cookies/cache, original IP and missing-console 503; a region without a console route must reach its home. Keep agent API egress site-only. Use an authorized dev demo and existing APIs for cleanup. Infrastructure changes need scoped approval (`AGENTS.md:129`); this authoring task grants none. |
| -4. Plan 4's later website build uses `CARLOS_START_SITE_ORIGIN=<SITE_ORIGIN>` for page and API and retains `CARLOS_START_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>` for browser/CLI links. Apply Task 1's amendment and non-mutating release check. Public claim instructions wait for merged Plan 3, the four-path code follow-up and its tests; no mutable operator path list. |
| +4. Plan 4's later website build uses `CARLOS_START_SITE_ORIGIN=<SITE_ORIGIN>` for page and API and retains `CARLOS_START_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>` for browser/CLI links. Apply Task 1's amendment and non-mutating release check. Claim paths landed in e12fe9a1; their follow-up tests are done in `demo-api-claim-paths`. No mutable operator path list. |
| 5. **Flagship, separately approved later:** use site origin `https://carlosframework.com`; read the canonical console origin from deployed configuration. Historical files place console in IE (`/home/paulca/github.com/carlosframework/carloku-infrastructure/region-ie.tf:64`), not evidence of current topology. Confirm the site claim, then repeat **all edges first, console second**, placing settings immediately before each roll's restart, stopping at the first box and checking every public ingress. Console and edge public origins equal Plan 4's `siteOrigin`. Follow release-tag/module rules (`AGENTS.md:515`). |
| ## Review budget |
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index bf8bfcfa2..62b3a697f 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -321,6 +321,14 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| clientIP = func() string { return ip } |
| } |
| w.Header().Set("Cache-Control", "no-store") |
| + // Rejected uploads do not need a reusable connection. Keep the deadline |
| + // through Body.Close too, since net/http may drain unread request bytes. |
| + w.Header().Set("Connection", "close") |
| + controller := http.NewResponseController(w) |
| + if err := controller.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil { |
| + demoError(w, err) |
| + return |
| + } |
| if !s.cfg.Demo.Enabled { |
| http.NotFound(w, r) |
| return |
| @@ -330,14 +338,6 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, 503, demoCopy["DEMO-CONFIG"]) |
| return |
| } |
| - // Rejected uploads do not need a reusable connection. Keep the deadline |
| - // through Body.Close too, since net/http may drain unread request bytes. |
| - w.Header().Set("Connection", "close") |
| - controller := http.NewResponseController(w) |
| - if err := controller.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil { |
| - demoError(w, err) |
| - return |
| - } |
| var err error |
| var update *DemoRow |
| var expiresAt int64 |
diff --git a/internal/console/demo_api_alias_integration_test.go b/internal/console/demo_api_alias_integration_test.go| index a55039ff6..6cf422932 100644 |
| --- a/internal/console/demo_api_alias_integration_test.go |
| +++ b/internal/console/demo_api_alias_integration_test.go |
| @@ -4,7 +4,9 @@ import ( |
| "crypto/hmac" |
| "crypto/sha256" |
| "encoding/hex" |
| + "encoding/json" |
| "errors" |
| + "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| "strings" |
| @@ -105,31 +107,39 @@ func TestDemoAPIAliasBudgetIdentity(t *testing.T) { |
| func TestDemoClaimAPIOrigin(t *testing.T) { |
| s, _, _ := claimTestServer(t) |
| s.cfg.DemoAPIOrigin = "https://example.com" |
| - for _, path := range []string{"/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select", "/api/demo/claims/status"} { |
| - for _, origin := range []string{"", s.cfg.Origin, s.cfg.DemoAPIOrigin, "https://other.example.com", "https://example.com/", "null"} { |
| - method := "POST" |
| - if strings.HasSuffix(path, "/status") { |
| - method = "GET" |
| - } |
| - r := httptest.NewRequest(method, s.cfg.Origin+path, strings.NewReader(`{}`)) |
| - r.RemoteAddr = "192.0.2.1:1234" |
| - r.Header.Set("Origin", origin) |
| - w := httptest.NewRecorder() |
| - s.mux.ServeHTTP(w, r) |
| - want := 403 |
| - if origin == "" || origin == s.cfg.Origin || origin == s.cfg.DemoAPIOrigin { |
| - want = 401 |
| - if path == "/api/demo/claims" { |
| - want = 400 |
| + key := []byte(strings.Repeat("k", 32)) |
| + if _, err := s.cfg.Releases.Put(t.Context(), edgeproof.MeshKeyObject, []byte(hex.EncodeToString(key)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, peer := range []string{"192.0.2.1:1234", "127.0.0.1:1234"} { |
| + for _, path := range []string{"/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select", "/api/demo/claims/status"} { |
| + for _, origin := range []string{"", s.cfg.Origin, s.cfg.DemoAPIOrigin, "https://other.example.com", "https://example.com/", "null"} { |
| + method := "POST" |
| + if strings.HasSuffix(path, "/status") { |
| + method = "GET" |
| + } |
| + r := httptest.NewRequest(method, s.cfg.Origin+path, strings.NewReader(`{}`)) |
| + r.RemoteAddr = peer |
| + r.Header.Set("X-Forwarded-For", "192.0.2.1") |
| + r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, "192.0.2.1", time.Now())) |
| + r.Header.Set("Origin", origin) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + want := 403 |
| + if origin == "" || origin == s.cfg.Origin || origin == s.cfg.DemoAPIOrigin { |
| + want = 401 |
| + if path == "/api/demo/claims" { |
| + want = 400 |
| + } |
| + } |
| + if w.Code != want || w.Header().Get("Cache-Control") != "no-store" || len(w.Result().Cookies()) != 0 { |
| + t.Errorf("%s origin %q: status=%d want=%d", path, origin, w.Code, want) |
| + } |
| + r.Header.Set("Origin", s.cfg.DemoAPIOrigin) |
| + r.Header.Set("Sec-Fetch-Site", "cross-site") |
| + if s.demoClaimOrigin(r) { |
| + t.Errorf("%s accepted cross-site fetch", path) |
| } |
| - } |
| - if w.Code != want || w.Header().Get("Cache-Control") != "no-store" || len(w.Result().Cookies()) != 0 { |
| - t.Errorf("%s origin %q: status=%d want=%d", path, origin, w.Code, want) |
| - } |
| - r.Header.Set("Origin", s.cfg.DemoAPIOrigin) |
| - r.Header.Set("Sec-Fetch-Site", "cross-site") |
| - if s.demoClaimOrigin(r) { |
| - t.Errorf("%s accepted cross-site fetch", path) |
| } |
| } |
| } |
| @@ -181,3 +191,101 @@ func TestDemoClaimAliasDispatch(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestDemoAPIProofRequiredClaimExpiry(t *testing.T) { |
| + s, mail, token := claimTestServer(t) |
| + s.cfg.DemoAPIOrigin = "https://example.com" |
| + key := []byte(strings.Repeat("k", 32)) |
| + if _, err := s.cfg.Releases.Put(t.Context(), edgeproof.MeshKeyObject, []byte(hex.EncodeToString(key)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.markEdgeProofSeen() |
| + const client, peer, forged = "192.0.2.1", "127.0.0.1", "203.0.113.9" |
| + send := func(path string, fields map[string]string) *httptest.ResponseRecorder { |
| + b, err := json.Marshal(fields) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest("POST", s.cfg.Origin+path, &demoAPIExpiryBody{Reader: strings.NewReader(string(b)), delay: 3 * time.Second}) |
| + r.RemoteAddr = peer + ":1234" |
| + r.Header.Set("Content-Type", "application/json") |
| + r.Header.Set("Forwarded", "for="+forged) |
| + r.Header.Set("X-Real-IP", forged) |
| + r.Header.Set("X-Forwarded-For", client) |
| + r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, client, time.Now().Add(-29*time.Second))) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if edgeproof.Verify(key, nil, r.Host, client, r.Header.Get(edgeproof.Header), time.Now()) { |
| + t.Fatal("proof did not expire during body read") |
| + } |
| + if strings.Contains(w.Body.String(), "console.example.com") { |
| + t.Fatal("agent reply names console host") |
| + } |
| + return w |
| + } |
| + check := func(name string, window *keyedWindow, want int) { |
| + t.Helper() |
| + s.limits.mu.Lock() |
| + defer s.limits.mu.Unlock() |
| + for _, ip := range []string{client, peer, forged} { |
| + n := 0 |
| + if ip == client { |
| + n = want |
| + } |
| + if got := window.count(ip, time.Now().Add(-time.Hour)); got != n { |
| + t.Errorf("%s for %s = %d, want %d", name, ip, got, n) |
| + } |
| + } |
| + } |
| + w := send("/api/demo/claims", map[string]string{"claimToken": token, "email": "shop@example.com"}) |
| + if w.Code != 202 { |
| + t.Fatalf("start status = %d", w.Code) |
| + } |
| + var start struct { |
| + Flow string `json:"flowToken"` |
| + } |
| + if err := json.Unmarshal(w.Body.Bytes(), &start); err != nil || start.Flow == "" { |
| + t.Fatal("missing claim flow") |
| + } |
| + code, _ := claimMail(t, s, mail) |
| + check("submit", &s.limits.submits, 1) |
| + check("send", &s.limits.ipSends, 1) |
| + w = send("/api/demo/claims/verify", map[string]string{"flowToken": start.Flow, "code": "wrong"}) |
| + if w.Code != 401 { |
| + t.Fatalf("wrong-code status = %d", w.Code) |
| + } |
| + check("guess", &s.limits.ipWrong, 1) |
| + w = send("/api/demo/claims/verify", map[string]string{"flowToken": start.Flow, "code": code}) |
| + if w.Code != 202 { |
| + t.Fatalf("verify status = %d", w.Code) |
| + } |
| + check("signup", &s.limits.ipNewPeople, 1) |
| + check("guess", &s.limits.ipWrong, 1) |
| + op, err := s.store.demoClaimOpForFlow(t.Context(), hashToken(start.Flow)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The proved flow can poll and select without a browser Origin. |
| + for _, path := range []string{"/api/demo/claims/status", "/api/demo/claims/select"} { |
| + method, body := "GET", "" |
| + if strings.HasSuffix(path, "/select") { |
| + method = "POST" |
| + b, _ := json.Marshal(map[string]string{"flowToken": start.Flow, "accountId": op.Target.Sqid}) |
| + body = string(b) |
| + } |
| + r := httptest.NewRequest(method, s.cfg.Origin+path, strings.NewReader(body)) |
| + r.RemoteAddr = peer + ":1234" |
| + r.Header.Set("Authorization", "Bearer "+start.Flow) |
| + r.Header.Set("X-Forwarded-For", client) |
| + r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, client, time.Now())) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + want := http.StatusAccepted |
| + if w.Code != want { |
| + t.Fatalf("%s status = %d", path, w.Code) |
| + } |
| + if strings.Contains(w.Body.String(), "console.example.com") { |
| + t.Fatal("agent reply names console host") |
| + } |
| + } |
| +} |
diff --git a/internal/console/demo_api_origin_test.go b/internal/console/demo_api_origin_test.go| index 2d1235916..33b05e2f6 100644 |
| --- a/internal/console/demo_api_origin_test.go |
| +++ b/internal/console/demo_api_origin_test.go |
| @@ -384,7 +384,19 @@ func TestDemoAPIProofRequiredRefusesStalledBody(t *testing.T) { |
| srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: s.mux}} |
| srv.Start() |
| defer srv.Close() |
| - conn, err := net.Dial("tcp", ln.Addr().String()) |
| + for _, path := range []string{"/api/demo/apps", "/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select"} { |
| + t.Run(path, func(t *testing.T) { |
| + resp, body := demoStalledReply(t, ln.Addr().String(), path) |
| + if resp.StatusCode != 503 || len(body) != 0 || !resp.Close || resp.Header.Get("Cache-Control") != "no-store" || resp.Header.Get("Retry-After") != "2" { |
| + t.Fatal("stalled upload did not receive empty no-store 503 and connection close") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func demoStalledReply(t *testing.T, addr, path string) (*http.Response, []byte) { |
| + t.Helper() |
| + conn, err := net.Dial("tcp", addr) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -392,7 +404,7 @@ func TestDemoAPIProofRequiredRefusesStalledBody(t *testing.T) { |
| if err := conn.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := io.WriteString(conn, "POST /api/demo/apps HTTP/1.1\r\nHost: console.example.com\r\nContent-Length: 10\r\n\r\n"); err != nil { |
| + if _, err := io.WriteString(conn, "POST "+path+" HTTP/1.1\r\nHost: console.example.com\r\nContent-Length: 10\r\n\r\n"); err != nil { |
| t.Fatal(err) |
| } |
| resp, err := http.ReadResponse(bufio.NewReader(conn), nil) |
| @@ -404,7 +416,31 @@ func TestDemoAPIProofRequiredRefusesStalledBody(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if resp.StatusCode != 503 || len(body) != 0 || !resp.Close || resp.Header.Get("Cache-Control") != "no-store" || resp.Header.Get("Retry-After") != "2" { |
| - t.Fatal("stalled upload did not receive empty no-store 503 and connection close") |
| + return resp, body |
| +} |
| + |
| +func TestDemoPublishEarlyRefusesStalledBody(t *testing.T) { |
| + for _, mode := range []string{"off", "config"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s := demoTestServer(t) |
| + want := 503 |
| + if mode == "off" { |
| + s.cfg.Demo.Enabled = false |
| + want = 404 |
| + } else { |
| + s.cfg.Demo.EdgeProtections = false |
| + } |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &httptest.Server{Listener: ln, Config: NewHTTPServer(s.mux)} |
| + srv.Start() |
| + defer srv.Close() |
| + resp, body := demoStalledReply(t, ln.Addr().String(), "/api/demo/apps") |
| + if resp.StatusCode != want || !resp.Close || len(body) == 0 || resp.Header.Get("Cache-Control") != "no-store" { |
| + t.Fatal("early refusal changed or failed to close connection") |
| + } |
| + }) |
| } |
| } |
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go| index 83a4effec..95b2a58e1 100644 |
| --- a/internal/console/demo_claim_auth.go |
| +++ b/internal/console/demo_claim_auth.go |
| @@ -123,6 +123,11 @@ func (s *Server) handleDemoClaimStart(w http.ResponseWriter, r *http.Request) { |
| if !s.requireDemoAPIProof(w, r) { |
| return |
| } |
| + var ip string |
| + if s.cfg.DemoAPIOrigin != "" { |
| + // The body can outlive the proof; keep its admitted attribution. |
| + ip = s.clientIP(r) |
| + } |
| if !s.demoClaimGate(w, r) { |
| return |
| } |
| @@ -149,7 +154,9 @@ func (s *Server) handleDemoClaimStart(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| } |
| - ip := s.clientIP(r) |
| + if s.cfg.DemoAPIOrigin == "" { |
| + ip = s.clientIP(r) |
| + } |
| underCap := s.limits.submit(ip) |
| if s.keymailAddress(r.Context(), address, underCap) { |
| demoClaimReply(w, 200, map[string]any{"state": "browser_required", "claimUrl": s.cfg.Origin + "/demo/claim#" + fields["claimToken"]}) |
| @@ -216,6 +223,11 @@ func (s *Server) handleDemoClaimVerify(w http.ResponseWriter, r *http.Request) { |
| if !s.requireDemoAPIProof(w, r) { |
| return |
| } |
| + var ip string |
| + if s.cfg.DemoAPIOrigin != "" { |
| + // The body can outlive the proof; keep its admitted attribution. |
| + ip = s.clientIP(r) |
| + } |
| if !s.demoClaimGate(w, r) { |
| return |
| } |
| @@ -234,7 +246,9 @@ func (s *Server) handleDemoClaimVerify(w http.ResponseWriter, r *http.Request) { |
| jsonError(w, 401, demoClaimBadProof) |
| return |
| } |
| - ip := s.clientIP(r) |
| + if s.cfg.DemoAPIOrigin == "" { |
| + ip = s.clientIP(r) |
| + } |
| done, ok := s.limits.reserveGuess(c.Address, ip) |
| if !ok { |
| jsonError(w, 401, demoClaimBadProof) |
diff --git a/internal/edge/demo_api_integration_test.go b/internal/edge/demo_api_integration_test.go| index 2d61406b4..68cac3fdd 100644 |
| --- a/internal/edge/demo_api_integration_test.go |
| +++ b/internal/edge/demo_api_integration_test.go |
| @@ -82,7 +82,7 @@ func TestDemoAPIAliasClientIP(t *testing.T) { |
| before := releases.reads.Load() |
| for i := 0; i < 61; i++ { |
| r, _ := http.NewRequest("GET", "https://example.com/api/demo/jobs/"+strings.Repeat("A", 43), nil) |
| - r.Header.Set("X-Forwarded-For", "203.0.113.9") |
| + r.Header.Set("X-Forwarded-For", fmt.Sprintf("203.0.113.%d", i+1)) |
| r.Header.Set("Forwarded", "for=203.0.113.9") |
| r.Header.Set("X-Carlos-Forwarded-Proof", "forged") |
| want := 404 |
| @@ -572,3 +572,78 @@ func TestDemoAPIAliasJourney(t *testing.T) { |
| t.Fatal("disabled reconstruction lost site") |
| } |
| } |
| + |
| +func TestDemoAPIAliasClaimPaths(t *testing.T) { |
| + var scene *edge.DemoAPITestIngress |
| + var calls atomic.Int64 |
| + const responseBody = "{\"state\":\"claiming\"}\n\x00" |
| + const requestBody = "{\"flowToken\":\"test-flow\"}\n" |
| + statuses := map[string]int{ |
| + "/api/demo/claims": 202, "/api/demo/claims/verify": 401, |
| + "/api/demo/claims/select": 429, "/api/demo/claims/status": 503, |
| + } |
| + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + if r.Host != "console.example.com" || !scene.VerifyRequest(r) || r.Header.Get("X-Forwarded-For") != "127.0.0.2" { |
| + t.Error("console host or verified client changed") |
| + } |
| + if r.Header.Get("Forwarded") != "" || r.Header.Get("Cookie") != "" { |
| + t.Error("client headers survived filtering") |
| + } |
| + if !reflect.DeepEqual(r.Header.Values("Authorization"), []string{"Bearer test-flow", ""}) { |
| + t.Error("authorization values changed") |
| + } |
| + body, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + wantBody, wantMethod := requestBody, "POST" |
| + if strings.HasSuffix(r.URL.Path, "/status") { |
| + wantBody, wantMethod = "", "GET" |
| + } |
| + if string(body) != wantBody || r.Method != wantMethod { |
| + t.Error("request changed") |
| + } |
| + status, ok := statuses[r.URL.Path] |
| + if !ok { |
| + t.Error("unexpected path") |
| + status = 500 |
| + } |
| + w.Header().Set("Set-Cookie", "session=private") |
| + w.Header().Set("Cache-Control", "public, max-age=3600") |
| + w.Header()["Retry-After"] = []string{"7", "11"} |
| + w.WriteHeader(status) |
| + _, _ = io.WriteString(w, responseBody) |
| + }) |
| + scene = edge.NewDemoAPITestIngress(t, handler, release.NewDirStore(t.TempDir())) |
| + // Ingress 0 has a local console; ingress 1 must reach its separate home. |
| + scene.ConsoleRoute(1, false) |
| + for _, ingress := range []int{0, 1} { |
| + for _, path := range []string{"/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select", "/api/demo/claims/status"} { |
| + t.Run(fmt.Sprintf("ingress=%d%s", ingress, path), func(t *testing.T) { |
| + client, origin := scene.Client(ingress, "127.0.0.2") |
| + method, body := "POST", requestBody |
| + if strings.HasSuffix(path, "/status") { |
| + method, body = "GET", "" |
| + } |
| + r, err := http.NewRequest(method, origin+path, strings.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Header["Authorization"] = []string{"Bearer test-flow", ""} |
| + r.Header.Set("Cookie", "session=private") |
| + r.Header.Set("X-Forwarded-For", "203.0.113.9") |
| + r.Header.Set("Forwarded", "for=203.0.113.9") |
| + r.Header.Set("X-Carlos-Forwarded-Proof", "forged") |
| + before, homeBefore := calls.Load(), scene.HomeCalls() |
| + b, h := demoAliasRead(t, client, r, statuses[path]) |
| + if string(b) != responseBody || !reflect.DeepEqual(h.Values("Retry-After"), []string{"7", "11"}) { |
| + t.Fatal("console response changed") |
| + } |
| + if calls.Load() != before+1 || scene.HomeCalls() != homeBefore+int64(ingress) { |
| + t.Fatal("console delivery was skipped or repeated") |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/hostenv/group.go b/internal/hostenv/group.go| index b421a2384..b596c8d45 100644 |
| --- a/internal/hostenv/group.go |
| +++ b/internal/hostenv/group.go |
| @@ -132,6 +132,9 @@ func AssembleGroup(shared, regional map[string]string, c GroupConfig, queue stri |
| } |
| env["CARLOS_TERMINATION_QUEUE_URL"] = queue |
| env[BoxReference] = GroupReference |
| + if err := validateDemoAPIOrigins(env); err != nil { |
| + return nil, err |
| + } |
| if _, err := Render(env); err != nil { |
| return nil, err |
| } |
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go| index 3a6a70416..3f9a121cb 100644 |
| --- a/internal/hostenv/hostenv.go |
| +++ b/internal/hostenv/hostenv.go |
| @@ -20,6 +20,7 @@ import ( |
| "errors" |
| "fmt" |
| "github.com/carlosframework/platform/internal/controlname" |
| + "github.com/carlosframework/platform/internal/demo" |
| "regexp" |
| "slices" |
| "sort" |
| @@ -225,9 +226,23 @@ func Assemble(shared, regional map[string]string) (map[string]string, error) { |
| if missing := Missing(env); len(missing) > 0 { |
| return nil, fmt.Errorf("%w: %s", ErrMissing, strings.Join(missing, ", ")) |
| } |
| + if err := validateDemoAPIOrigins(env); err != nil { |
| + return nil, err |
| + } |
| return env, nil |
| } |
| +func validateDemoAPIOrigins(env map[string]string) error { |
| + site, console := env["CARLOS_DEMO_API_ORIGIN"], env["CARLOS_DEMO_API_CONSOLE_ORIGIN"] |
| + if site == "" && console == "" { |
| + return nil |
| + } |
| + if site == console || !demo.ValidAPIOrigin(site) || !demo.ValidAPIOrigin(console) { |
| + return ErrValue |
| + } |
| + return nil |
| +} |
| + |
| // Missing lists the Required variables env has no value for, sorted. |
| func Missing(env map[string]string) []string { |
| var out []string |
diff --git a/internal/hostenv/hostenv_test.go b/internal/hostenv/hostenv_test.go| index de7cbe679..e5a23bdad 100644 |
| --- a/internal/hostenv/hostenv_test.go |
| +++ b/internal/hostenv/hostenv_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "bytes" |
| "context" |
| "errors" |
| + "fmt" |
| "os" |
| "path/filepath" |
| "reflect" |
| @@ -472,3 +473,53 @@ func TestDemoAPIHostEnv(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestDemoAPIOriginPair(t *testing.T) { |
| + const siteKey, consoleKey = "CARLOS_DEMO_API_ORIGIN", "CARLOS_DEMO_API_CONSOLE_ORIGIN" |
| + for _, group := range []bool{false, true} { |
| + for _, layout := range []string{"regional", "shared", "split", "reverse"} { |
| + for _, pair := range []struct { |
| + name, site, console string |
| + valid bool |
| + }{ |
| + {"disabled", "", "", true}, |
| + {"enabled", "https://example.com", "https://console.example.com", true}, |
| + {"siteOnly", "https://example.com", "", false}, |
| + {"consoleOnly", "", "https://console.example.com", false}, |
| + {"equal", "https://example.com", "https://example.com", false}, |
| + {"badSite", "http://example.com", "https://console.example.com", false}, |
| + {"badConsole", "https://example.com", "https://console.example.com/path", false}, |
| + } { |
| + t.Run(fmt.Sprintf("group=%t/%s/%s", group, layout, pair.name), func(t *testing.T) { |
| + c, regional := groupEnvFixture() |
| + if !group { |
| + regional = today() |
| + } |
| + shared := map[string]string{} |
| + siteScope, consoleScope := regional, regional |
| + if layout == "shared" || layout == "reverse" { |
| + siteScope = shared |
| + } |
| + if layout == "shared" || layout == "split" { |
| + consoleScope = shared |
| + } |
| + siteScope[siteKey], consoleScope[consoleKey] = pair.site, pair.console |
| + var env map[string]string |
| + var err error |
| + if group { |
| + env, err = AssembleGroup(shared, regional, c, "queue") |
| + } else { |
| + env, err = Assemble(shared, regional) |
| + } |
| + if pair.valid { |
| + if err != nil || env[siteKey] != pair.site || env[consoleKey] != pair.console { |
| + t.Fatalf("valid pair: %v", err) |
| + } |
| + } else if !errors.Is(err, ErrValue) || env != nil { |
| + t.Fatalf("invalid pair: %v", err) |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |