fix: close demo API origin and proxy review findings
Apply Tasks 1 and 2 review fixes with failing witnesses first. Share strict origin validation, protect catch-all ownership, retain publish attribution, refuse stalled unsigned uploads, and block backend upgrades. Fold in canonical-target, version-header, fixture, diagnostic, and plan corrections. Task 3 remains pending.
docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md+4 −4docs/superpowers/plans/2026-11-05-demo-api-site-route.md+2 −2internal/console/apidemo.go+9 −3internal/console/demo_api_origin.go+3 −2internal/console/demo_api_origin_test.go+93 −1internal/console/domaincatchall.go+1 −1internal/demo/api_origin.go+23 −0internal/demo/api_origin_test.go+16 −0internal/edge/demo_api.go+12 −7internal/edge/demo_api_test.go+61 −5internal/edge/edge.go+1 −1
CI failed — run details
Intent
<task-notification> <task-id>bcjkbhyr5</task-id> <tool-use-id>toolu_0174cP6NmcWNwJ4tgtznachy</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ada77e36-2f79-4efb-88a5-c350ac2ffa6a/tasks/bcjkbhyr5.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 2 implementer to finish" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a522ee331f72e4ecf</task-id> <tool-use-id>toolu_014qSjew5wsDNEVvZbj5CFCE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ada77e36-2f79-4efb-88a5-c350ac2ffa6a/tasks/a522ee331f72e4ecf.output</output-file> <status>completed</status> <summary>Agent "Opus review of Task 1" 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># Review of Task 1, round 1 (`71d426f8..47cb4fd9`) There are no P1s and four P2s, so the verdict is READY AFTER FIXES. The three named tests pass, both on the clean worktree and on an export of `47cb4fd9`. I didn't edit the worktree, and my scratch directory is removed. All paths below are under `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/demo-api-site-route/`. **Sandbox bypass:** the sandbox mounts the default Go cache read-only, which blocked building anything new. You told me to leave `GOCACHE` unset, so I ran my scratch-test and mutation commands with the sandbox off. They only wrote to the Go cache and my scratch directory, and only used loopback. **Scratch export:** the other agent's uncommitted edge edits broke the worktree build partway through, so all witnesses and mutations ran on the export. ## P1 None. ## P2 ### 1. The catch-all door does not see the configured host - **Problem:** the configured host is matched by exact name in `domainHostPolicy`, so it never appears in `platformDomains`. The check for names under a catch-all parent only reads `consoleHosts`, `reservedDomains` and `platformDomains`. - **Evidence:** `internal/console/domaincatchall.go:76`, `internal/console/domainpolicy.go:95`. The doc comment at `domaincatchall.go:47-52` promises to refuse any platform hostname strictly under the parent. - **Witness:** with the origin set to `https://www.example.com`, `catchallParentRefused("example.com", "shop")` returns false. The same name in `DenyDomains` returns true. - **Failure scenario:** a person in the account holding `example.com` attaches `*.example.com`, which covers the operator-only site host. - A proven catch-all held by another account can then make `catchallInstanceName` refuse that host at the attach door (`domaincatchall.go:218-231`). - I read that path but did not run it, and I did not run instance creation at the `www` label. - The API alias is not hijacked, because it intercepts before routing. An apex site host is already refused at `domaincatchall.go:60`. - **Fix:** add the configured host to `entries` at `domaincatchall.go:76`, and add this case to `TestDemoAPIHostOwnership`. - **Invariant (exact-name reservation vs subtree readers):** every reader of the deny tiers must see the new reservation. The plan lists catch-all as affected. ### 2. `validateDemoAPIOrigin` accepts IP-shaped hosts - **Problem:** `demo.ValidDomain` only rejects what `netip.ParseAddr` parses, so legacy IPv4 forms pass. - **Evidence:** `internal/console/demo_api_origin.go:19`, `internal/demo/config.go:127`. - **Witness:** all of these are accepted: `https://127.1`, `https://0x7f.1`, `https://1.2.3`, `https://1.2.3.4.5`, `https://2130706433.0`, `https://example.123`. - **Failure scenario:** an operator typo starts the console, and agents get a `statusUrl` that URL-standard clients read as `127.0.0.1`. It also becomes a nonsense platform-host reservation. - **Fix:** in `validateDemoAPIOrigin`, refuse a final label that is all digits or `0x` hex, and add those inputs to the test table. Leave `ValidDomain` alone, since other code uses it. Task 2's edge parser needs the same rule because the plan requires one grammar. - **Invariant (origin grammar):** no IP literal. ### 3. The publish handler rechecks the proof after the upload, so verified attribution can fall back to loopback - **Problem:** the gate verifies the proof at entry, but `s.clientIP(r)` verifies it again after the body read, and the proof is only valid for 30 seconds. The read deadline is also 30 seconds, and proof timestamps are rounded down to the second. - **Evidence:** `internal/console/apidemo.go:408`, then `:439`. Also `internal/edgeproof/edgeproof.go` (`Skew`, `Sign`), `internal/console/edgeproof.go:75-85`, and the deadline at `apidemo.go:324`. - **Witness:** a publish with a valid, 29-second-old proof and a 3-second body read returns 202 with `creating_ip="127.0.0.1"`. A fresh proof records `192.0.2.77`. I simulated this with a recorder, which applies no read deadline, so the window in production is the last second or so before the deadline. - **Failure scenario:** a client can pace its upload, or a slow upload can happen to land, so that its abuse record names loopback instead of the client. A key refresh between the two checks could cause the same thing. Budgets are not affected, because `:374` and `:386` run before the body. - **Fix:** capture the IP once before the body read and reuse it at `:374`, `:386` and `:439`. If off-mode must stay literally unchanged, do this only when `DemoAPIOrigin` is set. - **Invariant (identity verified once, derived twice):** the plan says `clientIP` "sees the verified chain". ### 4. The 503 refusal waits on the request body - **Problem:** the gate's refusal for a POST omits `Connection: close`, so `net/http` tries to drain the body before sending the reply. The publish handler's own comment guards against this drain (`internal/console/apidemo.go:320-324`). - **Evidence:** `internal/console/demo_api_origin.go:58-60`. - **Witness:** on a real listener, an unsigned loopback POST declaring 10 bytes and sending none got no response within my 3-second deadline. Adding `Connection: close` returned the 503 immediately, and `TestDemoAPIProofRequired` still passed. - **Failure scenario:** a tenant process, or an upload hit by a key mismatch, holds the request open without spending any budget, up to `ReadTimeout` (5 minutes, `internal/console/httpserver.go`). The plan wanted this refused "before budget/body work". The test's `demoUnreadBody` cannot see this because a recorder never drains. - **Fix:** set `Connection: close` and a short read deadline on the refusal, and add one witness on a real listener. - **Invariant (refusal does no body work):** this applies on the wire as well as in the handler. ## P3 (follow-up list) 1. **Malformed A-labels:** `https://xn--a.example.com` and `https://xn--0.com` are accepted. The test deliberately allows valid `xn--` names, so this only needs a Punycode check. The R-LDH name `ab--cd.example.com` is also accepted, which seems fine. 2. **Plan 4 gates:** lines 21, 61 and 192 list the dependencies for activation and acceptance, but don't name the site route. Only the open-questions line (`:224`) does. The live check at `:188` would catch it, but the three lists should agree. 3. **Plan 4 cache header:** line 188 requires `Cache-Control: no-store`, while this plan's Task 2 forces `no-store, private` at the edge. A strict comparison would fail the live gate, so it should say "contains no-store". 4. **Test entry point:** the witnesses enter at `s.mux`, not `s.ServeHTTP`, and there is no form-door case (`internal/console/domainattach.go:140`, `:369`). Those doors share the policy function, so this is only a coverage gap. 5. **Trailing-dot Host:** `requireDemoAPIProof` compares with `normalizeHost`, which keeps a trailing dot, while `edgeproof.canonicalHost` drops it. A Host of `console.example.com.` gets a 503, which fails safe. I read this but did not run it. ## Checked and clean - **Forged or replayed proofs:** - An app's valid proof, a wrong Host, duplicate headers, multi-element or non-canonical XFF, a zone, an expired proof and a wrong key all get a 503. - The gate runs first on both publish and status, and spends no budget or latch. - An edge door caller gets a valid proof, but only for the box's own IP, so it cannot pick its identity. - **Real traffic still passes:** - Ingress and verified hops send a single XFF element (`internal/edge/homemap.go:1537-1555`), so legitimate traffic gets through. - A direct console request through the local edge passes. - An unsigned loopback caller gets a 503, which the plan intends. - An untrusted peer is unaffected. - **Setting off:** the gate returns early, and the link and policy branches are skipped, so behaviour is unchanged. - **Key rotation:** both keys are accepted. A stale cache or a store failure gives a 503 with `Retry-After`, never loopback attribution at the gate. - **Links:** `statusUrl` comes only from configuration, and `claimUrl` keeps the console origin and fragment. No other response field or error names the console host, and the update reply shares the same line. - **Host policy:** - `EXAMPLE.com`, `example.com.`, `EXAMPLE.COM.` and `example.com:443` were all refused on attach. - The first two spellings were also refused on detach and paths (the other two weren't tried there). - The ship code doesn't call the policy function, so an ordinary static ship is unaffected. - **Plan 4 amendment:** lines 81, 83, 84, 123, 129 and 188 match the plan. The 32-byte unknown job ID matches `ValidJobID`. ## Test strength All 9 mutations were caught, so the tests are real witnesses for what they cover: - publish gate removed - status gate removed - Host pin removed - canonical IP compare removed - single-proof check removed (reran after a compile error) - single-XFF check removed - host policy removed - `claimUrl` moved to the site origin - `statusUrl` taken from Host The gaps are the ones in P2 items 1, 2 and 4. ## Verdict **READY AFTER FIXES** (no P1; P2s 1 to 4 above).</result> <usage><subagent_tokens>178565</subagent_tokens><tool_uses>25</tool_uses><duration_ms>798922</duration_ms></usage> </task-notification>
<task-notification> <task-id>a78d445989d8f82d2</task-id> <tool-use-id>toolu_01WrS9iKbtsSyFmJ4R4Waovr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ada77e36-2f79-4efb-88a5-c350ac2ffa6a/tasks/a78d445989d8f82d2.output</output-file> <status>completed</status> <summary>Agent "Opus review of Task 2" 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># Review, round 1: Task 2, demo API site route (`47cb4fd9..129b3c6f`) **Verdict: READY AFTER FIXES.** There is one P2: a backend's 101 answer can open a raw tunnel through the response writer. No P1s. ## Tests and how I checked | Check | Result | |---|---| | `TestDemoAPIAlias(Boundary\|Isolation)` | Pass. Needed one run outside the sandbox for the Unix-socket subtest. | | Named hostenv tests | Pass, plus the Optional/sort tests. | | `gofmt`, `go vet` on both packages | Clean. | | `-race` | Not run. It failed to build here (`runtime/race: package testmain: cannot find package`), which looks like a local toolchain problem. It still needs its one pre-handoff run. | - **Extra probes:** I added them through `go test -overlay`, with no worktree edits, and have removed the scratch directory. They were raw HTTP/1 request targets, a real two-edge TLS hop with a console backend, and 8 source mutations. - **Not exercised:** real HTTP/2 requests. The h2 points below come from reading the code. ## P1 None. ## P2 ### 1. A backend's 101 opens a raw tunnel past the response policy **Evidence** - `internal/edge/demo_api.go:206` lists `upgrade` as private, and `demoAPIScrubResponse` (`:243`) runs as `ModifyResponse`. - Go runs `ModifyResponse` before `handleUpgradeResponse` (`reverseproxy.go:589-593`). The scrub empties the response's upgrade type, so the check `EqualFold("", "")` at `:842` passes. Without the scrub, the stdlib would refuse this mismatch. - `rc.Hijack()` (`reverseproxy.go:854`) then walks `demoAPIResponseWriter.Unwrap` (`demo_api.go:263`) to the real connection. **Reproduced** - Backend hijacks and answers `101` with `Upgrade: evil`, with `CARLOS_RATE_LIMIT=off`. - Client received `HTTP/1.1 101 Switching Protocols ... TUNNELLED`, raw bytes on a request that carried no upgrade. - With `observe`, it gets 503, but only because `slotWriter.Hijack` happens to fail on its type assertion. - From the code, the hop leg (`edge.go:4254`, `assetInformationalScrub{dw}`) has no `slotWriter`, so it reaches the hijack in every rate mode. I did not run that path. **Failure scenario:** a console, a home edge, or an old-binary home row answers 101 to an allowlisted request. The client gets a bidirectional tunnel with no response policy. A client can't trigger this itself, because upgrade requests get 404 and the `Upgrade` header is dropped, so the upstream must misbehave first. That is why this is P2. **Fix** - Add `func (w *demoAPIResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, http.ErrNotSupported }`. `ResponseController` then stops at this writer and `ReverseProxy` calls `demoAPIProxyError`, giving an empty no-store 503. - Add a witness that a backend 101 gets 503 with rate limiting off. **Fault family:** the private writer must be the only exit, including `Hijack` through `Unwrap`. ## P3 (follow-up list) 1. **Duplicate version header.** Local delivery without a 1xx sends `X-Carlos-Version: v1` twice, while ordinary console dispatch sends it once. - Cause: `versionHeader` sets it (`demo_api.go:98`), `ModifyResponse` sets it (`:92`), and `copyHeader` adds rather than replaces. - Current readers use `Get`, so nothing breaks today. Task 3's comparison of direct and alias bytes may trip on it. - Fix: stamp it once, in `ModifyResponse` and the error handler. 2. **Absolute-form targets count as canonical.** `POST http:/api/demo/apps` and `POST http://example.com/api/demo/apps` both reach the console. - The target is rebuilt from the decoded URL, so the console only sees the canonical form. This matches ordinary routing and does not widen access. - It is stricter than the plan's "original canonical spelling". An `r.RequestURI == p` check would close it, but fixtures built with `httptest.NewRequest` would then need relative targets. 3. **The rate test can't prove chain attribution.** The fixture's `RemoteAddr` and hop XFF are the same IP (`demo_api_test.go:65`, `:711`), so a peer-keyed bucket would also pass. Use a different peer address. My two-edge probe shows the real behaviour is correct. 4. **Some gate conditions have no witness.** Removing `up.regional != 0`, `rt.IsDemo()` or the `FleetPlacement` check each survived. - The regional check is covered anyway, because `foldRegional` always sets `alias` (`regional.go:120`, `:142`). - The other two look redundant, based on reading the code. Either add table rows or accept them as belt and braces. 5. **Misleading fatal prefix.** Bad origins log as `edge: load routes: CARLOS_DEMO_API_ORIGIN ...` (`edge.go:4517`). Use a dedicated prefix, or wrap the error so the prefix is accurate. 6. **Operator signal and copy.** - An ineligible console row or a mismatch with the console's `Origin` gives silent 503s on every ingress. A throttled Reload log would help, and the plan's "unsupported console-route explanation" copy has no code yet. - The diagnostics at `demo_api.go:25` and `:29` are listed for copy review. I can't tell from this diff whether that happened. 7. **hostenv scope and validation** (see item 7 under "Checked and sound"). - `Split` (`hostenv.go:331`) puts both names in region scope, so a multi-region deployment must write them per region. The plan's Switch-on doesn't say this. - hostenv also doesn't validate the pair. A partial or bad parameter crash-loops each new box at `RestartSec=1`. The plan accepts this, but a pair check in `Assemble` is worth a follow-up. ## Could only be proved in Task 3 None of these look wrong. - **Survived in Task 2's tests:** dropping the hop XFF carry, the hop request filter, or the hop response hook (M1 to M3 in my mutations). All three need the cross-edge tests. - **What the real TLS hop probe showed:** - The console saw only `203.0.113.9` as XFF, despite a forged `9.9.9.9`. - The proof verified for Host `console.…`. - `Authorization ["", "Bearer x"]` arrived intact and cookies were gone. - The request and response both streamed without buffering. - Trailer `Set-Cookie` was stripped and `X-Result` kept. - Under `enforce`, the same client got a no-store 429 from the home edge, and a different client was admitted. ## Checked and sound 1. **Blast radius when off.** - The hot path gains one string compare plus a call that returns at once, with no allocation. - Reload gains one string concat per reverse-proxy route. - Startup fails only on partial, equal or invalid values, and the message doesn't echo them. - A crash loop with `Restart=always` is the plan's accepted risk, handled by stopping at the first box. 2. **Path gate.** - These all give an empty 404 with no console call and no static fallback: `%2f`, `%2e`, `%64`, `%00`, double slashes, trailing slash, `;x`, `#f`, bare `?`, `HEAD`, `OPTIONS`, lowercase `post`, `CONNECT /api/demo/apps` and upgrades. - A static tree holding `api/demo/apps/index.html` was never served on any tried reserved path. - `/api/demo;x/apps` and `EXAMPLE.COM` aren't reserved, but only got a 404. No hop or console path exists for them. - The console-host arm touches only allowlisted requests. 3. **Destination.** - Tenant rows, aliases, forward rows and tunnels all give 503, tested at both the sender and the home's own gate. - Held and empty homes refuse, and already-hopped requests can't loop. - The proxy and route come from one atomic snapshot. - The ordinary path also lets an exact local row win without a home check, so the hook matches it. 4. **Client IP.** - Forged XFF, Forwarded, proof and hop headers have no effect. - Malformed hops get 503 before anything can attribute them. - Edge and console agree in both delivery modes: a single canonical XFF with a proof signed for the console host. 5. **Headers and bodies.** - The allowlist is exact and duplicates and empties survive. - No-store holds on every exit, including the 404, `rateAdmit` 429 and hop-admission 503. - There is no `GetBody`, no POST retry and no buffering. `ReadFrom` isn't exposed, and `Flush` works. 6. **Layers.** - `rateAdmit` and its release match ordinary dispatch, and `Ticket.Release` is idempotent. - Source ingress applies hop concurrency and fair-share, and the home edge then applies per-client limits. - Tokens, job IDs and Authorization are not logged, because the error handlers discard the error. - The hook skips `admissionRefuses`, but ordinary dispatch also backhauls non-local hosts on a box that isn't admitted, so the forward leg matches. The plan's bypass list doesn't name this, so one line there would help. 7. **hostenv.** The names are sorted and carry no credentials, because the edge requires exactly `https://<host>`. They fit the file's `CARLOS_S3_ENDPOINT` precedent and round-trip through seed, group and write. 8. **Tests.** They run through `Edge.ServeHTTP` and real `Reload`. Removing `rateAdmit` or the trailer filter fails them properly. ## Verdict **READY AFTER FIXES:** P2 #1 only, fixed without reopening the review.</result> <usage><subagent_tokens>221616</subagent_tokens><tool_uses>29</tool_uses><duration_ms>1344305</duration_ms></usage> </task-notification>
Attributed to this commit: 2.96 g CO₂e (316,995 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-api-site-route, 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/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md| index dc1bf2b47..52e269f36 100644 |
| --- a/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md |
| +++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md |
| @@ -18,7 +18,7 @@ |
| - Source is one gzip stream containing ordinary USTAR files/directories: at most 5,000,000 compressed bytes, 20,000,000 expanded file bytes, 256 files, 2,000,000 bytes per file, and 256 directories. Output binary cap: 33,554,432 bytes. No symlinks, hardlinks, PAX/GNU extension records, sparse files, VCS tree, vendor tree or workspace files. |
| - Binary apps read `--socket` and `--db` flags. Demo SQLite stays on its assigned box with no replica. Public demo hosts are never reused. Do not infer a hostname, database recovery or a replacement app from an earlier run. |
| - Provider-neutral website and starter; no cloud SDK, vendor build service, bucket reader, background health polling or new per-box polling. Only an active agent polls its returned site job URL, at bounded intervals. |
| -- The demo journey switches default off; Plan A needs no off switch because sites without twins retain their existing behaviour. Website build switch `CARLOS_START_DEMO=1` selects the new journey; unset builds the account path without anonymous-publish instructions. Console admission remains its existing drop-in switch `CARLOS_DEMO_APPS=1`. Neither switch enables the other. **Switch-on date: dev on the day this plan lands.** Public activation waits for Plan A on the serving edges and Plans 2 and 3 merged, enabled and verified, then accompanies the approved website release. Do not land an unused preparatory slice separately. |
| +- The demo journey switches default off; Plan A needs no off switch because sites without twins retain their existing behaviour. Website build switch `CARLOS_START_DEMO=1` selects the new journey; unset builds the account path without anonymous-publish instructions. Console admission remains its existing drop-in switch `CARLOS_DEMO_APPS=1`. Neither switch enables the other. **Switch-on date: dev on the day this plan lands.** Public activation waits for Plan A on the serving edges, Plans 2 and 3 merged, enabled and verified, and the demo API site route release with its claim-path follow-up, then accompanies the approved website release. Do not land an unused preparatory slice separately. |
| - The dev acceptance target is the existing `dev.trycarlos.com` setup. The console origin is a separate configuration value, never inferred from that name. One `*.trycarlos.com` certificate covers direct demo names; it does not cover invented names below `dev.trycarlos.com`. Use returned URLs and verify their actual TLS. The issuer is the housekeeper, not the ingress. This plan creates no DNS records or certificates. |
| - Demo boxes have 2 GB RAM: no test compilation, browser installation or test suite there. Author/CI checks run off-box; the existing remote builder compiles submitted apps only. Preserve default Go caches; scratch goes under `$TMPDIR` or `~/.cache` and is removed. |
| - Website HTML remains usable without JavaScript. Reuse local clipboard and disclosure scripts, existing light/dark styling and drawn marks. No new browser framework, CDN assets, analytics, client-side publishing or hidden agent instructions. |
| @@ -58,7 +58,7 @@ Read against platform `2914921ceabd4218b0363a9780f8e4db890aab4c` and website `ef |
| **Fixed serving decision (Paul, 2026-11-04).** Build `/start/index.html` with the human introduction and full visible “for your agent” section, plus `/start/index.md` with the agent directives from the same source. Plan A owns Accept negotiation; no User-Agent detection is needed. HTML-only fetchers receive the complete instructions. Keep the website’s static route, build and release workflow. |
| -**Dependency gate.** Plan 1 is merged and live. Before implementing or independently reviewing Plan 4’s website tasks, Plan A must be merged and released to the edge serving the target website; record its merged SHA, release and an observed negotiation check. The claim step also waits for Plan 3 to merge: Task 2 binds its declared contract to the merged handlers. Dev acceptance and public activation require Plans 2 and 3 enabled and verified there, and Plan A on that destination’s serving edges. Do not review against unmerged producers; these gates do not reset review history. |
| +**Dependency gate.** Plan 1 is merged and live. Before implementing or independently reviewing Plan 4’s website tasks, Plan A must be merged and released to the edge serving the target website; record its merged SHA, release and an observed negotiation check. The claim step also waits for Plan 3 to merge: Task 2 binds its declared contract to the merged handlers. Dev acceptance and public activation require Plans 2 and 3 enabled and verified there, Plan A on that destination’s serving edges, and the demo API site route release with its claim-path follow-up. Do not review against unmerged producers; these gates do not reset review history. |
| | Plan 3 declared interface, not shipped yet | Website instruction contract | |
| |---|---| |
| @@ -185,11 +185,11 @@ One source, `W/src/start/agent.md`, contains the following ordered directives. ` |
| **Interfaces:** |
| -- `verifyStartOrigin(origin: URL) -> Promise<Verification>`, where `Verification={origin:string,version:string,markdownSHA256:string,starterSHA256:string,checks:Record<string,boolean>}`, in the live test checks real negotiated responses, TLS, content hash, release header and starter checksum. It also sends a non-mutating, redirect-refusing GET to `<siteOrigin>/api/demo/jobs/<unknownJobID>` with a well-formed unknown ID (32 random bytes encoded as unpadded base64url). Require HTTP 404, `application/json`, the console's `error` response matching its demo-not-found fixture, and `Cache-Control: no-store`; an empty or static 404 fails. It never creates apps by being imported or through the default test command. |
| +- `verifyStartOrigin(origin: URL) -> Promise<Verification>`, where `Verification={origin:string,version:string,markdownSHA256:string,starterSHA256:string,checks:Record<string,boolean>}`, in the live test checks real negotiated responses, TLS, content hash, release header and starter checksum. It also sends a non-mutating, redirect-refusing GET to `<siteOrigin>/api/demo/jobs/<unknownJobID>` with a well-formed unknown ID (32 random bytes encoded as unpadded base64url). Require HTTP 404, `application/json`, the console's `error` response matching its demo-not-found fixture, and a `Cache-Control` value that contains `no-store`; an empty or static 404 fails. It never creates apps by being imported or through the default test command. |
| - Acceptance record holds website/platform/Plan A/Plan 2/Plan 3 SHAs and the serving edge release, starter archive digest, console/site origins, returned public demo/permanent URLs, elapsed times, request counts, agent/harness and result for each scenario. Redact claim links, bearer tokens, email codes, personal email and cookies. Approved human report prose uses the copy table; raw machine evidence is kept separately. |
| - Release script requires explicit console/account/app/channel/site-origin arguments and a clean merged commit. Build artifacts on the author/CI machine and deploy with the public CLI. No implicit flagship defaults, infrastructure provisioning, IAM, direct bucket writes or SSH. Retain the previous static release/version for rollback; ship only built `_site/` output. |
| -- [ ] **Step 1: Establish prerequisites and expected failure.** With the feature off, verify the account path remains usable and no anonymous instructions are advertised. Confirm Plan A is merged and released to the website’s serving edge, and Plans 2 and 3 are merged/live and claim availability is true before claiming a complete journey. Run `node --test test/start-live.test.mjs` against the dev site before the new static content is deployed and record the expected content failure. No test result may silently pass because a live case skipped. |
| +- [ ] **Step 1: Establish prerequisites and expected failure.** With the feature off, verify the account path remains usable and no anonymous instructions are advertised. Confirm Plan A is merged and released to the website’s serving edge, Plans 2 and 3 are merged/live, the demo API site route and its claim-path follow-up are released, and claim availability is true before claiming a complete journey. Run `node --test test/start-live.test.mjs` against the dev site before the new static content is deployed and record the expected content failure. No test result may silently pass because a live case skipped. |
| - [ ] **Step 2: Build and enable the dev release.** Discover and record the dev console/site destination through documented console/CLI configuration and use the existing designated dev scope. Build `_site/` with `CARLOS_START_DEMO=1` and the exact dev origins; deploy through the existing static-site CLI workflow. Keep the route kind, domain claims and placement unchanged. Verify `/start` follows its slash redirect and `/start/` returns HTML or Markdown as Plan A specifies; compare the Markdown bytes with `/start/index.md`. Admission remains the console drop-in already live from Plan 1. |
| - [ ] **Step 3: Run the decisive cloud-agent witness.** In a fresh real cloud coding-agent session, initially without Go or the CLI, paste only the dev equivalent of the homepage line. Use a phone browser for the human side. Describe a small shop list, answer the experience/feel questions, and approve the small build. Permit at most the one explained site-host allowlist step if blocked. Have the agent fetch the served instructions, obtain/modify/pack the starter, POST source, poll the returned status URL and share the actual live URL. Create a row in the app, ask for one visible change, and verify the bearer update preserves that row and the expiry. Inject one compile error to exercise diagnostics/repair. Target less than five minutes from paste to first working URL; record measured time and network intervention rather than claiming success from a mock. |
| - [ ] **Step 4: Complete claim and normal development.** Through that agent, use a designated test email and Plan 3's real challenge to keep the app. Verify the copied row at the returned permanent URL, the demo's moved page, and rejection of the old demo token. Record email-verification time separately from transfer time, with the design's under-one-minute claim target. Exercise account-choice, unavailable-claim and Keymail branches through fixtures plus designated real test identities where available; clearly label any live branch not witnessed. After the person opts in, obtain the public CLI release, sign in, place source in a private scratch repo without secrets, deploy a second visible change to the claimed app and verify its existing row. Do not weaken the no-install demo path to make this post-claim check pass. |
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 d484cff53..42c6945c0 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 |
| @@ -83,7 +83,7 @@ Require a cached signing key even for local delivery; an invalid purported hop t |
| Keep one small private-header streaming writer with `Unwrap()` and flush support, sanitizing headers at writes and trailers at proxy completion. Go's `ReverseProxy` forwards 1xx before `ModifyResponse` and copies trailers after the body, so it does not provide the same guarantee (installed Go source: `/home/paulca/.local/go-dist/src/net/http/httputil/reverseproxy.go:560`, `:599`, `:639`; existing limitations: `internal/edge/cookiescope.go:57`, `:63`). Never log bodies, Authorization, archives or response tokens. |
| -The alias bypasses 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`. |
| +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. |
| @@ -146,7 +146,7 @@ Restore Plan 4's previous build first if consumers switched. Clear `CONSOLE_DEMO |
| ## Switch-on |
| 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. 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`). |
| +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. |
| 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`). |
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index 351c93819..8792d40a2 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -307,6 +307,12 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| if !s.requireDemoAPIProof(w, r) { |
| return |
| } |
| + clientIP := func() string { return s.clientIP(r) } |
| + if s.cfg.DemoAPIOrigin != "" { |
| + // Uploads can outlive the proof. Keep attribution fixed after admission. |
| + ip := s.clientIP(r) |
| + clientIP = func() string { return ip } |
| + } |
| w.Header().Set("Cache-Control", "no-store") |
| if !s.cfg.Demo.Enabled { |
| http.NotFound(w, r) |
| @@ -371,7 +377,7 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| demoError(w, err) |
| return |
| } |
| - if err := s.store.CheckDemoCreateBudget(r.Context(), s.clientIP(r), time.Now(), s.cfg.Demo); err != nil { |
| + if err := s.store.CheckDemoCreateBudget(r.Context(), clientIP(), time.Now(), s.cfg.Demo); err != nil { |
| demoError(w, err) |
| return |
| } |
| @@ -383,7 +389,7 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| demoError(w, err) |
| return |
| } |
| - err = s.store.SpendDemoCreate(r.Context(), s.clientIP(r), time.Now(), s.cfg.Demo) |
| + err = s.store.SpendDemoCreate(r.Context(), clientIP(), time.Now(), s.cfg.Demo) |
| } |
| if err != nil { |
| demoError(w, err) |
| @@ -436,7 +442,7 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| var identity demo.Identity |
| if update == nil { |
| sum := sha256.Sum256(src.Archive) |
| - in := DemoAdmission{Config: s.cfg.Demo, IP: s.clientIP(r), Now: time.Now(), SourceSHA256: sum, Client: r.Header.Get("X-Carlos-Client")} |
| + in := DemoAdmission{Config: s.cfg.Demo, IP: clientIP(), Now: time.Now(), SourceSHA256: sum, Client: r.Header.Get("X-Carlos-Client")} |
| in.job = func(ctx context.Context, tx *sql.Tx, d DemoRow, life AppLife) error { |
| expiresAt = life.ExpiresAt |
| _, err := s.insertDemoJob(ctx, tx, d, life, src) |
diff --git a/internal/console/demo_api_origin.go b/internal/console/demo_api_origin.go| index dfe2a32a8..5d8f75bb2 100644 |
| --- a/internal/console/demo_api_origin.go |
| +++ b/internal/console/demo_api_origin.go |
| @@ -15,8 +15,7 @@ func validateDemoAPIOrigin(raw string) (string, error) { |
| if raw == "" { |
| return "", nil |
| } |
| - u, err := url.Parse(raw) |
| - if err != nil || !demo.ValidDomain(u.Hostname()) || raw != "https://"+u.Hostname() { |
| + if !demo.ValidAPIOrigin(raw) { |
| // Never echo the value: a mistaken URL may contain credentials. |
| return "", errors.New("CONSOLE_DEMO_API_ORIGIN must be a canonical HTTPS DNS origin without a port, credentials, path, query or fragment") |
| } |
| @@ -55,6 +54,8 @@ func (s *Server) requireDemoAPIProof(w http.ResponseWriter, r *http.Request) boo |
| } |
| } |
| } |
| + w.Header().Set("Connection", "close") |
| + _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(time.Second)) |
| w.Header().Set("Cache-Control", "no-store") |
| w.Header().Set("Retry-After", "2") |
| w.WriteHeader(http.StatusServiceUnavailable) |
diff --git a/internal/console/demo_api_origin_test.go b/internal/console/demo_api_origin_test.go| index 5f82be092..b9d4de68e 100644 |
| --- a/internal/console/demo_api_origin_test.go |
| +++ b/internal/console/demo_api_origin_test.go |
| @@ -1,9 +1,12 @@ |
| package console |
| import ( |
| + "bufio" |
| "bytes" |
| "encoding/hex" |
| "encoding/json" |
| + "io" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "strings" |
| @@ -68,7 +71,7 @@ func TestDemoPublicAPIOrigin(t *testing.T) { |
| t.Error("origin fallback changed") |
| } |
| } |
| - for _, raw := range []string{"http://example.com", "//example.com", "https://example.com/", "https://example.com/path", "https://example.com?", "https://example.com?x=1", "https://example.com#", "https://example.com#x", "https://user:secret@example.com", "https://example.com:443", "https://example.com:", "https://example.com:8443", "https://*.example.com", "https://127.0.0.1", "https://[::1]", "https://EXAMPLE.com", "HTTPS://example.com", "https://example.com.", " https://example.com", "https://example.com\n", "https://-shop.example.com", "https://shop_.example.com", "https://localhost", "https://" + strings.Repeat("a", 64) + ".com"} { |
| + for _, raw := range []string{"http://example.com", "//example.com", "https://example.com/", "https://example.com/path", "https://example.com?", "https://example.com?x=1", "https://example.com#", "https://example.com#x", "https://user:secret@example.com", "https://example.com:443", "https://example.com:", "https://example.com:8443", "https://*.example.com", "https://127.0.0.1", "https://127.1", "https://0x7f.1", "https://1.2.3", "https://1.2.3.4.5", "https://2130706433.0", "https://example.123", "https://example.0x7f", "https://[::1]", "https://EXAMPLE.com", "HTTPS://example.com", "https://example.com.", " https://example.com", "https://example.com\n", "https://-shop.example.com", "https://shop_.example.com", "https://localhost", "https://" + strings.Repeat("a", 64) + ".com"} { |
| if _, err := NewServer(Config{Origin: "https://console.example.com", DemoAPIOrigin: raw}, st); err == nil { |
| t.Error("invalid origin accepted") |
| } else if strings.Contains(err.Error(), "secret") { |
| @@ -220,6 +223,15 @@ func TestDemoAPIProofRequired(t *testing.T) { |
| } |
| func TestDemoAPIHostOwnership(t *testing.T) { |
| + t.Run("catchall parent", func(t *testing.T) { |
| + s := &Server{cfg: Config{Origin: "https://console.example.net", DemoAPIOrigin: "https://www.example.com"}} |
| + if !s.catchallParentRefused("example.com", "shop") { |
| + t.Error("catch-all could cover configured public API host") |
| + } |
| + if s.catchallParentRefused("other.example.net", "shop") { |
| + t.Error("configured public API host reserved unrelated catch-all") |
| + } |
| + }) |
| fx := newConsoleFixture(t) |
| s := fx.srv |
| s.cfg.DemoAPIOrigin = "https://example.com" |
| @@ -316,3 +328,83 @@ func TestDemoAPIHostOwnership(t *testing.T) { |
| t.Error("unset retained reservation") |
| } |
| } |
| + |
| +// Delay the first body read until the admitted proof has expired. |
| +type demoAPIExpiryBody struct { |
| + io.Reader |
| + delay time.Duration |
| +} |
| + |
| +func (b *demoAPIExpiryBody) Read(p []byte) (int, error) { |
| + if b.delay != 0 { |
| + time.Sleep(b.delay) |
| + b.delay = 0 |
| + } |
| + return b.Reader.Read(p) |
| +} |
| + |
| +func TestDemoAPIProofRequiredPublishExpiry(t *testing.T) { |
| + s, _ := demoJobServer(t) |
| + s.cfg.Origin = "https://console.example.com" |
| + s.cfg.DemoAPIOrigin = "https://example.com" |
| + key := []byte(strings.Repeat("a", 32)) |
| + if _, err := s.cfg.Releases.Put(t.Context(), edgeproof.MeshKeyObject, []byte(hex.EncodeToString(key)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest("POST", s.cfg.Origin+"/api/demo/apps", &demoAPIExpiryBody{Reader: bytes.NewReader(demoHTTPSource(t)), delay: 3 * time.Second}) |
| + r.RemoteAddr = "127.0.0.1:1234" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + 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().Add(-29*time.Second))) |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 202 { |
| + t.Fatalf("publish status = %d", w.Code) |
| + } |
| + if edgeproof.Verify(key, nil, r.Host, "192.0.2.1", r.Header.Get(edgeproof.Header), time.Now()) { |
| + t.Fatal("proof did not expire during upload") |
| + } |
| + var ip string |
| + if err := s.store.db.QueryRow(`SELECT creating_ip FROM demo_apps`).Scan(&ip); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ip != "192.0.2.1" { |
| + t.Errorf("creating_ip = %s, want verified client", ip) |
| + } |
| +} |
| + |
| +func TestDemoAPIProofRequiredRefusesStalledBody(t *testing.T) { |
| + s := demoTestServer(t) |
| + s.cfg.Origin = "https://console.example.com" |
| + s.cfg.DemoAPIOrigin = "https://example.com" |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: s.mux}} |
| + srv.Start() |
| + defer srv.Close() |
| + conn, err := net.Dial("tcp", ln.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + 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 { |
| + t.Fatal(err) |
| + } |
| + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) |
| + if err != nil { |
| + t.Fatalf("refusal waited for request body: %v", err) |
| + } |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(resp.Body) |
| + 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") |
| + } |
| +} |
diff --git a/internal/console/domaincatchall.go b/internal/console/domaincatchall.go| index bb243c364..60130c380 100644 |
| --- a/internal/console/domaincatchall.go |
| +++ b/internal/console/domaincatchall.go |
| @@ -73,7 +73,7 @@ func (s *Server) catchallParentRefused(parent, account string) bool { |
| if under(s.cfg.AppsDomain) { |
| return true |
| } |
| - entries := slices.Concat(s.consoleHosts(), s.reservedDomains(false), s.platformDomains(false)) |
| + entries := slices.Concat(s.consoleHosts(), s.reservedDomains(false), s.platformDomains(false), []string{strings.TrimPrefix(s.cfg.DemoAPIOrigin, "https://")}) |
| return slices.ContainsFunc(entries, under) |
| } |
diff --git a/internal/demo/api_origin.go b/internal/demo/api_origin.go| new file mode 100644 |
| index 000000000..f9e25b613 |
| --- /dev/null |
| +++ b/internal/demo/api_origin.go |
| @@ -0,0 +1,23 @@ |
| +package demo |
| + |
| +import ( |
| + "net/url" |
| + "strings" |
| +) |
| + |
| +// ValidAPIOrigin is the shared grammar for console and edge demo API origins. |
| +func ValidAPIOrigin(raw string) bool { |
| + u, err := url.Parse(raw) |
| + if err != nil || !ValidDomain(u.Hostname()) || raw != "https://"+u.Hostname() { |
| + return false |
| + } |
| + // Browsers can interpret numeric final labels as noncanonical IP addresses. |
| + host := u.Hostname() |
| + last := host[strings.LastIndexByte(host, '.')+1:] |
| + digits := "0123456789" |
| + if strings.HasPrefix(last, "0x") { |
| + last = last[2:] |
| + digits += "abcdef" |
| + } |
| + return strings.Trim(last, digits) != "" |
| +} |
diff --git a/internal/demo/api_origin_test.go b/internal/demo/api_origin_test.go| new file mode 100644 |
| index 000000000..52bf04f02 |
| --- /dev/null |
| +++ b/internal/demo/api_origin_test.go |
| @@ -0,0 +1,16 @@ |
| +package demo |
| + |
| +import "testing" |
| + |
| +func TestDemoAPIOrigin(t *testing.T) { |
| + for _, origin := range []string{"https://example.com", "https://123.example.com", "https://0x7f.example.com", "https://xn--bcher-kva.example.com", "https://example.c0ffee", "https://example.0xshop"} { |
| + if !ValidAPIOrigin(origin) { |
| + t.Errorf("rejected DNS origin %q", origin) |
| + } |
| + } |
| + for _, origin := range []string{"", "http://example.com", "https://example.com/", "https://example.com:443", "https://example.com?", "https://example.com#", "https://Example.com", "https://example.com.", "https://127.1", "https://0x7f.1", "https://1.2.3", "https://1.2.3.4.5", "https://2130706433.0", "https://example.123", "https://example.0x", "https://example.0x7f", "https://example.0xabcdef", "https://example.0001", "https://[::1]"} { |
| + if ValidAPIOrigin(origin) { |
| + t.Errorf("accepted invalid origin %q", origin) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/demo_api.go b/internal/edge/demo_api.go| index 5a9e23c90..571ae8008 100644 |
| --- a/internal/edge/demo_api.go |
| +++ b/internal/edge/demo_api.go |
| @@ -1,10 +1,11 @@ |
| package edge |
| import ( |
| + "bufio" |
| "errors" |
| + "net" |
| "net/http" |
| "net/http/httputil" |
| - "net/url" |
| "path" |
| "strings" |
| @@ -21,8 +22,7 @@ func parseDemoAPIAliasConfig(getenv func(string) string) (demoAPIAliasConfig, er |
| return c, nil |
| } |
| for _, raw := range []string{c.Origin, c.ConsoleOrigin} { |
| - u, err := url.Parse(raw) |
| - if err != nil || !demo.ValidDomain(u.Hostname()) || raw != "https://"+u.Hostname() { |
| + if !demo.ValidAPIOrigin(raw) { |
| return demoAPIAliasConfig{}, errors.New("CARLOS_DEMO_API_ORIGIN and CARLOS_DEMO_API_CONSOLE_ORIGIN must both be canonical HTTPS DNS origins without ports, credentials, paths, queries or fragments") |
| } |
| } |
| @@ -38,7 +38,7 @@ func demoAPIPath(r *http.Request) (reserved, allowed bool) { |
| p := r.URL.Path |
| inNamespace := func(p string) bool { return p == "/api/demo" || strings.HasPrefix(p, "/api/demo/") } |
| reserved = inNamespace(p) || inNamespace(path.Clean(p)) |
| - if !reserved || r.URL.RawPath != "" || r.URL.EscapedPath() != p || path.Clean(p) != p || r.URL.RawQuery != "" || r.URL.ForceQuery || isUpgradeRequest(r) || len(r.Header.Values("Upgrade")) != 0 { |
| + if !reserved || r.RequestURI != p || r.URL.RawPath != "" || r.URL.EscapedPath() != p || path.Clean(p) != p || r.URL.RawQuery != "" || r.URL.ForceQuery || isUpgradeRequest(r) || len(r.Header.Values("Upgrade")) != 0 { |
| return reserved, false |
| } |
| if r.Method == http.MethodPost && p == "/api/demo/apps" { |
| @@ -93,9 +93,11 @@ func newDemoAPIProxy(p *httputil.ReverseProxy, version string) http.Handler { |
| } |
| return nil |
| } |
| - cp.ErrorHandler = demoAPIProxyError |
| - if version != "" { |
| - return versionHeader(version, &cp) |
| + cp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { |
| + if version != "" { |
| + w.Header().Set("X-Carlos-Version", version) |
| + } |
| + demoAPIProxyError(w, r, err) |
| } |
| return &cp |
| } |
| @@ -261,6 +263,9 @@ type demoAPIResponseWriter struct { |
| func (w *demoAPIResponseWriter) Header() http.Header { return w.header } |
| func (w *demoAPIResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w *demoAPIResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| + return nil, nil, http.ErrNotSupported |
| +} |
| func (w *demoAPIResponseWriter) WriteHeader(code int) { |
| if w.committed { |
| return |
diff --git a/internal/edge/demo_api_test.go b/internal/edge/demo_api_test.go| index 0293cdd00..43642d84c 100644 |
| --- a/internal/edge/demo_api_test.go |
| +++ b/internal/edge/demo_api_test.go |
| @@ -61,8 +61,12 @@ func demoAPIBackend(t *testing.T, e *Edge, handler http.Handler) registry.Route |
| } |
| func demoAPIRequest(e *Edge, host, method, target string, h http.Header) *httptest.ResponseRecorder { |
| - r := httptest.NewRequest(method, "https://"+host+target, nil) |
| + r := httptest.NewRequest(method, target, nil) |
| + r.Host = host |
| r.RemoteAddr = "192.0.2.1:40000" |
| + if h.Get(hopHeader) != "" { |
| + r.RemoteAddr = "198.51.100.9:40000" |
| + } |
| if h != nil { |
| r.Header = h.Clone() |
| } |
| @@ -105,7 +109,7 @@ func TestDemoAPIAliasBoundary(t *testing.T) { |
| t.Errorf("config accepted=%v, want %v", err == nil, c.valid) |
| } |
| } |
| - for _, bad := range []string{"http://example.com", "https://Example.com", "https://example.com:443", "https://example.com/", "https://example.com?", "https://example.com#", "https://user@example.com", "https://127.0.0.1", "https://[::1]", "https://*.example.com", "https://example.com."} { |
| + for _, bad := range []string{"http://example.com", "https://Example.com", "https://example.com:443", "https://example.com/", "https://example.com?", "https://example.com#", "https://user@example.com", "https://127.0.0.1", "https://127.1", "https://0x7f.1", "https://1.2.3", "https://1.2.3.4.5", "https://2130706433.0", "https://example.123", "https://example.0x7f", "https://[::1]", "https://*.example.com", "https://example.com."} { |
| for _, name := range []string{"CARLOS_DEMO_API_ORIGIN", "CARLOS_DEMO_API_CONSOLE_ORIGIN"} { |
| demoAPISettings(t) |
| t.Setenv(name, bad) |
| @@ -162,7 +166,7 @@ func TestDemoAPIAliasBoundary(t *testing.T) { |
| {"HEAD", "/api/demo/jobs/a", 404}, {"OPTIONS", "/api/demo/apps", 404}, {"DELETE", "/api/demo/jobs/a", 404}, {"POST", "/api/demo/jobs/a", 404}, |
| {"GET", "/api/demo/jobs/", 404}, {"GET", "/api/demo/jobs/a/b", 404}, {"GET", "/api/demo/jobs/a.b", 404}, {"GET", "/api/demo/jobs/a/", 404}, |
| {"POST", "/api/demo/claims", 404}, {"POST", "/api/demo/claims/verify", 404}, {"POST", "/api/demo/claims/select", 404}, {"GET", "/api/demo/claims/status", 404}, {"POST", "/api/demo/reports", 404}, |
| - {"POST", "/api/demo/apps?", 404}, {"POST", "/api/demo/apps?a=b", 404}, |
| + {"POST", "http://example.com/api/demo/apps", 404}, {"POST", "https://example.com/api/demo/apps", 404}, {"POST", "/api/demo/apps?", 404}, {"POST", "/api/demo/apps?a=b", 404}, |
| {"POST", "/api/%64emo/apps", 404}, {"POST", "/api/demo%2fapps", 404}, {"POST", "/api/demo/%2e%2e/demo/apps", 404}, |
| {"POST", "/x/../api/demo/apps", 404}, {"POST", "//api//demo/apps", 404}, {"POST", "/api/demo/../apps", 404}, {"POST", "/api/demo/apps/", 404}, {"GET", "/api/demo/jobs/a%5cb", 404}, {"GET", "/api/demo/jobs/a%2fb", 404}, |
| } { |
| @@ -172,6 +176,9 @@ func TestDemoAPIAliasBoundary(t *testing.T) { |
| t.Errorf("%s %s = %d, want %d", c.method, c.path, w.Code, c.status) |
| } |
| demoAPINoStore(t, w.Result().Header) |
| + if c.status == 202 && !reflect.DeepEqual(w.Header().Values("X-Carlos-Version"), []string{"v1"}) { |
| + t.Error("duplicate or missing version header") |
| + } |
| if c.status == 404 && (w.Body.Len() != 0 || calls.Load() != before) { |
| t.Errorf("refused path dispatched or got body: %s", c.path) |
| } |
| @@ -232,7 +239,7 @@ func TestDemoAPIAliasBoundary(t *testing.T) { |
| t.Fatal("configured attached source did not dispatch") |
| } |
| before = calls.Load() |
| - r := httptest.NewRequest("POST", "https://example.com/api/demo/apps", nil) |
| + r := httptest.NewRequest("POST", "/api/demo/apps", nil) |
| r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "shop", App: "shop"})) |
| w := httptest.NewRecorder() |
| e.ServeHTTP(w, r) |
| @@ -550,7 +557,7 @@ func TestDemoAPIAliasIsolation(t *testing.T) { |
| })) |
| for _, values := range [][]string{nil, {""}, {"Bearer example"}, {"", "Bearer example"}} { |
| wanted = values |
| - r := httptest.NewRequest("POST", "https://example.com/api/demo/apps", strings.NewReader("body")) |
| + r := httptest.NewRequest("POST", "/api/demo/apps", strings.NewReader("body")) |
| if values != nil { |
| r.Header["Authorization"] = values |
| } |
| @@ -662,6 +669,9 @@ func TestDemoAPIAliasIsolation(t *testing.T) { |
| t.Fatal("response status, bytes or 103 changed") |
| } |
| demoAPINoStore(t, resp.Header) |
| + if !reflect.DeepEqual(resp.Header.Values("X-Carlos-Version"), []string{"v1"}) { |
| + t.Error("duplicate or missing version header") |
| + } |
| if resp.Header.Get("Retry-After") != "7" || resp.Header.Get("Location") != "https://other.example.com/" || resp.Header.Get("X-Carlos-Version") != "v1" { |
| t.Fatal("end-to-end headers changed") |
| } |
| @@ -731,3 +741,49 @@ func TestDemoAPIAliasIsolation(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +func TestDemoAPIAliasIsolationBackendUpgrade(t *testing.T) { |
| + demoAPISettings(t) |
| + t.Setenv("CARLOS_RATE_LIMIT", "off") |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + conn, rw, err := http.NewResponseController(w).Hijack() |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + defer conn.Close() |
| + io.WriteString(rw, "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: example\r\n\r\nraw backend bytes") |
| + rw.Flush() |
| + })) |
| + srv := httptest.NewServer(e) |
| + defer srv.Close() |
| + req, err := http.NewRequest("POST", srv.URL+"/api/demo/apps", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = demoAPISite |
| + client := srv.Client() |
| + client.Timeout = 2 * time.Second |
| + resp, err := client.Do(req) |
| + 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 != 503 || len(body) != 0 || resp.Header.Get("Retry-After") != "2" { |
| + t.Fatalf("backend upgrade response: status=%d bytes=%d", resp.StatusCode, len(body)) |
| + } |
| + demoAPINoStore(t, resp.Header) |
| + if !reflect.DeepEqual(resp.Header.Values("X-Carlos-Version"), []string{"v1"}) { |
| + t.Error("error response version missing or duplicated") |
| + } |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index f8fde7520..2211417ac 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -4514,7 +4514,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| // injects the hibernation activator (edge + activator in one process). |
| e, err := New(reg, act) |
| if err != nil { |
| - log.Fatalf("edge: load routes: %v", err) |
| + log.Fatalf("edge: initialize: %v", err) |
| } |
| defer e.stopReplicaProbes() |
| for _, opt := range opts { |