carlos / platform Public

Prove demo claim paths through the site host; keep attribution (#527)

Plan 3's merge added the four claim paths and the proof gate. This proves them
through real edge delivery. Claim start and verify now keep the admitted client
IP past the proof's life. Demo-off publish refusals no longer wait on a stalled
body. hostenv refuses a bad origin pair at write time. Not released.

Review: Opus READY, no P1 or P2. Census approved on #280.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from demo-api-claim-paths into main.
Co-Authored-By: claude <claude~paul@keymail.dev>
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 25ca6faf30f68c2bff350b382381597642c06067 parent 0eea2ab
15 files changed, +405 −44
  • README.md +2 −2
  • docs/superpowers/notes/census-proposal-demo-api-claim-paths.md +11 −0
  • docs/superpowers/plans/2026-11-05-demo-api-site-route.md +7 −3
  • docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-API-CLAIM-PATHS.md +27 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-API-CLAIM-PATHS.md +13 −0
  • internal/console/apidemo.go +8 −8
  • internal/console/demo_api_alias_integration_test.go +132 −24
  • internal/console/demo_api_origin_test.go +40 −4
  • internal/console/demo_claim_auth.go +16 −2
  • internal/edge/demo_api_integration_test.go +76 −1
  • internal/hostenv/group.go +3 −0
  • internal/hostenv/hostenv.go +15 −0
  • internal/hostenv/hostenv_test.go +51 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-demo-api-claim-paths.tsv +3 −0

CI cancelled — superseded by a newer push — run details

diff --git a/README.md b/README.md
index 420933e9e..20709b6c0 100644
--- a/README.md
+++ b/README.md
@@ -659,9 +659,9 @@ Take down every existing Plan 1 demo through `carlos system demos takedown --hos
<!-- DEMO-API-SITE-ROUTE: approved by delegation, Luna copy pass, 2026-11-05. -->
#### Serve the demo API on the site origin
-The site can serve anonymous demo requests for create, update and status operations on its own hostname. The alias is off by default. Confirm that the site host is already claimed by the intended account before enabling it. Once the console setting is enabled, only operators can change that host's claim.
+The site host can serve demo requests for create, update, status and claim operations. The alias is off by default. Confirm that the site host is already claimed by the intended account before enabling it. Once the console setting is enabled, only operators can change that host's claim.
-Set `CARLOS_DEMO_API_ORIGIN` to the site's HTTPS origin and `CARLOS_DEMO_API_CONSOLE_ORIGIN` to the canonical `CONSOLE_ORIGIN`. Set both on every public ingress that can receive the site, including regions without a local console, and on the console's home edge. Both must be canonical HTTPS DNS origins without ports, paths, credentials, queries or fragments. They must differ. With valid, different values, setting both enables the alias. Setting only one, using an invalid value, or setting equal values prevents edge startup.
+Set `CARLOS_DEMO_API_ORIGIN` to the site's HTTPS origin and `CARLOS_DEMO_API_CONSOLE_ORIGIN` to the canonical `CONSOLE_ORIGIN`. Set both on every public ingress that can receive the site, including regions without a local console, and on the console's home edge. Both must be canonical HTTPS DNS origins without ports, paths, credentials, queries or fragments. They must differ. With valid, different values, setting both enables the alias. Setting only one, using a value that is not a valid origin, or setting equal values makes the host-env writer refuse the pair. An edge started with such values by another route also refuses to start.
Deliver both settings through root-owned `/etc/carlos/host.env`. For group boxes, update the operator parameters in every participating region and use the existing `system host-env write --group` workflow without `--install`. Confirm replacement bootstrap releases recognize both names first. Fixed boxes keep their existing host.env workflow. Do not rewrite a fixed box with the group writer.
diff --git a/docs/superpowers/notes/census-proposal-demo-api-claim-paths.md b/docs/superpowers/notes/census-proposal-demo-api-claim-paths.md
new file mode 100644
index 000000000..0d1f385fe
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-demo-api-claim-paths.md
@@ -0,0 +1,11 @@
+# Census approval: demo-api-claim-paths
+
+Ruling `census-ruling-demo-api-claim-paths`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/hostenv`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939` → `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-demo-api-claim-paths.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
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..48649b225 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,11 @@ 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.
+
+### After Plan 3
+
+Three facts the tables above predate. The request filter also forwards `Sec-Fetch-Site`, because the claim handlers read it. Exact site Origin is admitted on the four claim API paths only: those paths honour no cookie, and `Sec-Fetch-Site` still applies, so script on the operator-only site origin gains nothing beyond an agent with no Origin. Both origin parameters change one at a time, so during Switch-on or Rollback a group box launched between the two writes fails at `host-env write`; set or clear the pair with no scale-out in between.
## Task 1: Configure public agent links and operator ownership
@@ -148,7 +152,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/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-API-CLAIM-PATHS.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-API-CLAIM-PATHS.md
new file mode 100644
index 000000000..104571189
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-DEMO-API-CLAIM-PATHS.md
@@ -0,0 +1,27 @@
+# Copy pass brief: claim paths on the site host (branch demo-api-claim-paths)
+
+You are the copy-review gate itself for this set. Paul delegated copy review to you on 2026-10-25; your verdicts ARE the review. Do NOT run the copy-review skill or start any server. Do not edit any file. Answer in your final message only.
+
+These are small changes to an operator README section you already passed (`LUNA-COPY-RESULT-DEMO-API-SITE-ROUTE.md`). The audience is an operator running their own deployment.
+
+## House rules
+
+Plain words, short sentences, no marketing tone. No em dashes or en dashes used as dashes. Leave setting names, paths and backticked text exactly as they are. Do not add steps or conditions.
+
+## Facts that must stay true
+
+- The site host now also serves the claim API, as well as create, update and status.
+- Only the claim API is forwarded. The browser claim page stays on the console.
+- The host-env writer now refuses a pair where only one name is set, the two are equal, or either is not a valid origin. An edge started with such values by another route still refuses to start.
+
+## Output
+
+One markdown table, `| key | new | why |`, every row in order, `unchanged` in why when you keep a string. Then a short **Flags** list for anything wrong or unclear in fact.
+
+## Deck
+
+| key | Surface | Draft text |
+|---|---|---|
+| readmeIntroSentence | First sentence of the section's intro | The site can serve anonymous demo requests for create, update, status and claim operations on its own hostname. |
+| readmeSettingsLast | Replaces the last sentence of the settings paragraph | Setting only one, using an invalid value, or setting equal values prevents edge startup. The host-env writer refuses the same values. |
+| readmeConsoleLast | Replaces "Claim API paths are not available through this alias yet." at the end of the console paragraph | Agents use the claim API on the site host. The browser claim page stays on the console. |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-API-CLAIM-PATHS.md b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-API-CLAIM-PATHS.md
new file mode 100644
index 000000000..82d01a5a5
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-DEMO-API-CLAIM-PATHS.md
@@ -0,0 +1,13 @@
+# Luna copy result: claim paths on the site host
+
+Brief: LUNA-COPY-BRIEF-DEMO-API-CLAIM-PATHS.md. Rows 1 and 2 applied verbatim. Row 3 not applied: Plan 3's merge had already replaced that sentence with accurate text, and Luna's version ("Only the claim API is forwarded to the site host") is false, since create, update and status are forwarded too.
+
+| key | new | why |
+|---|---|---|
+| readmeIntroSentence | The site host can serve demo requests for create, update, status and claim operations. | Removes the unsupported “anonymous” claim. |
+| readmeSettingsLast | Setting only one, using a value that is not a valid origin, or setting equal values makes the host-env writer refuse the pair. An edge started with such values by another route also refuses to start. | Names every rejection case and startup behavior. |
+| readmeConsoleLast | Only the claim API is forwarded to the site host. Agents use it there. The browser claim page stays on the console. | Clarifies the forwarding boundary and both claim surfaces. |
+
+**Flags**
+
+- The intro draft incorrectly says all demo requests are anonymous.
\ No newline at end of file
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)
+ }
+ })
+ }
+ }
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index afcc85ae7..8262af8d6 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -106,3 +106,4 @@ plan14-root-reads-region-ha-p3b2-rolls.tsv c55b4a022b3d42f40a05b727f93e57dc9f76b
plan14-root-reads-restart-new-box-gap.tsv 18e4df5f599a48a881526fc2f85a9b591e3ea8677bb297d5944c9d935771f5e6
plan14-root-reads-agent-start-demo-3.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
plan14-root-reads-lease-renew-after-pause.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
+plan14-root-reads-demo-api-claim-paths.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
diff --git a/internal/provision/testdata/plan14-root-reads-demo-api-claim-paths.tsv b/internal/provision/testdata/plan14-root-reads-demo-api-claim-paths.tsv
new file mode 100644
index 000000000..cfe502ef9
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-demo-api-claim-paths.tsv
@@ -0,0 +1,3 @@
+# Census overlay demo-api-claim-paths, written by census-propose (#369). census-ruling-demo-api-claim-paths, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-demo-api-claim-paths.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/hostenv d029a45ae549bf90a3585c15895c8c169b59568500d6de07a12c930287a1bdc5