plan: linked deployments slice 1 rev 4 (round-3 fixes, simulations)
Connection generation at home, console sync retry loop, re-runnable unlink, one upstream selection site, public origin throughout, no home caching for linked requests, and Task 11 revocation simulations.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+40
−17
docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md+40 −17
CI failed — run details
diff --git a/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md| index 487267875..d28f4978c 100644 |
| --- a/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md |
| +++ b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md |
| @@ -20,7 +20,7 @@ |
| - No new per-box object-store polling (spec anti-goal 4). Everything flows through console APIs and the shared registry. |
| - New registry tables and columns are added to `Fingerprint()` (`registry.go:3990`) unless a task says otherwise, to `consoleRegistry` (`internal/console/view.go:522`) when the console uses them, and to `internal/registry/remote_dispatch.go` when the agent uses them through `OpenRemote`. |
| - Every new console route that is a parity member gets its row in the parity table checked by `internal/console/parity_test.go`, and every new top-level CLI command gets its heading on the CLI reference page checked by `internal/docsite/cli_test.go` (Tasks 5, 6, 7, 9). |
| -- Plan revision: rev 3. Round 1: both NOT READY (`docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md`). Round 2: Astra NOT READY, Fable READY AFTER FIXES (`...-R2.md`). Three round-2 P1s recurred in round-1 fault families (AGENTS.md rule 2); Paul chose on 2026-11-10 (amadan discussion 812): (1) **one writer** for link channel state, (2) linked requests run the **normal edge pipeline with a pinned upstream**, (3) **unpublish replaces the whole link connection**. Rev 3 implements those three and the round-2 P2s. |
| +- Plan revision: rev 4. Round 3 (`...-R3.md`): Fable READY AFTER FIXES, Astra NOT READY with two P1s in the revocation family; Paul chose on 2026-11-10 (discussion 812) to apply the fixes below, check the family with the randomized simulations of Task 11, and skip a fourth plan round. Round 1: both NOT READY (`docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md`). Round 2: Astra NOT READY, Fable READY AFTER FIXES (`...-R2.md`). Three round-2 P1s recurred in round-1 fault families (AGENTS.md rule 2); Paul chose on 2026-11-10 (amadan discussion 812): (1) **one writer** for link channel state, (2) linked requests run the **normal edge pipeline with a pinned upstream**, (3) **unpublish replaces the whole link connection**. Rev 3 implements those three and the round-2 P2s. |
| - Parity rows go only to routes that are console parity members; `/api/cli/` doors and the `kindLink` doors are not members (`parity_test.go:41-42`). |
| - Migrations are additive: `CREATE TABLE IF NOT EXISTS` and `ALTER TABLE ADD COLUMN` with duplicate-column errors swallowed, following `migrateFleets` (registry) and `Store.migrate()` (console). New `apps` columns go in by ALTER after `migrateAppsKey` runs. |
| - User-facing strings come from the approved copy deck (Task 0) verbatim. Neutral names only in examples and tests (`shop`, `blog`, `example.com`). |
| @@ -80,12 +80,12 @@ Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appear |
| - `func (r *Registry) LinkForwards(linkID string) ([]Route, error)` — every forward row placed `link/<linkID>`; unlink deletes from this list, not from console app rows. |
| - `SetLinkSeen` carries the connection's registration sequence: `SetLinkSeen(linkID string, seq uint64, connected bool, at time.Time) error` applies a disconnect only when the stored `seq` equals `seq` (a re-register's newer connect is never overwritten by the older connection's close). `func (r *Registry) ResetLinkSeen() error` marks every link disconnected; the hub calls it at start. |
| -Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL, rev INTEGER NOT NULL DEFAULT 0, connected INTEGER NOT NULL DEFAULT 0, seen_at INTEGER NOT NULL DEFAULT 0, seq INTEGER NOT NULL DEFAULT 0)`. |
| +Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL, generation INTEGER NOT NULL DEFAULT 0, connected INTEGER NOT NULL DEFAULT 0, seen_at INTEGER NOT NULL DEFAULT 0, seq INTEGER NOT NULL DEFAULT 0)`. |
| - [ ] **Step 1: Write failing tests** in `links_test.go`: |
| - `TestLinkChannelNameNeverAFleet`: for 2,000 random `ValidTunnelName` strings `f` and labels, `LinkOfChannel(f+"/"+l)` is false; `LinkOfChannel(LinkChannelName(id))` round-trips for valid IDs; `LinkPlacement("fleet/x")` and `LinkPlacement("link/NOTHEX")` are false. |
| - `TestLinkChannelAuthOnlyActive`: put two links, revoke one; `LinkChannelAuth()` has exactly the active one keyed `link:<id>/home`; `LinkOwners()` likewise. |
| - - `TestPutForwardAcceptsLinkPlacement`: `PutForward(Route{Kind: KindForward, Host: "shop.acct1.apps.example.com", App: "shop", Account: "acct1", Region: "link/0123456789ab"})` succeeds; `Region: "link/bad"` returns `ErrNotForward`. |
| + - `TestPutForwardAcceptsLinkPlacement`: with an active channel for link `0123456789ab` owned by `acct1`, `PutForward(Route{Kind: KindForward, Host: "shop.acct1.apps.example.com", App: "shop", Account: "acct1", Region: "link/0123456789ab"})` succeeds; `Region: "link/bad"` returns `ErrNotForward`. |
| - `TestLinkSeenDoesNotMoveFingerprint`: `Fingerprint()` before and after `SetLinkSeen` is equal; after `PutLinkChannel` it differs. |
| - `TestForwardClassesDisjoint`: with a link row on host H, `PutForward` of a fleet row on H returns `ErrHostHeld` and H is unchanged; the reverse also holds; a link row of link L2 cannot replace L1's; `DeleteForward(H)` returns false for the link row and `DeleteLinkForward(H, L2)` returns false. |
| - `TestLinkSeenOrdering`: connect seq 1, connect seq 2, disconnect seq 1 → still connected; disconnect seq 2 → disconnected; `ResetLinkSeen` clears all. |
| @@ -174,7 +174,8 @@ Risk: authority. Gets its own review. |
| - `POST /auth/cli/start` accepts JSON `{"purpose":"link","name":"<home name>"}`; any other purpose value is 400. Without `purpose` it behaves exactly as today. A link start's response echoes `"purpose":"link"`; the home side (Task 7) aborts with the deck's "serving console too old" string when the echo is missing, because an older console ignores unknown fields and would start an ordinary person login. |
| - Approval for a link request shows an account picker limited to accounts where the approver holds the role `handleAPICreateApp` requires, and passes step-up (`requireFreshAuth`) as today. Approving stores `account_id` on the request. |
| - `PollCLIAuth` for an approved link request, in one transaction: mints the token with `kind='link'`, `account_id`, `name=<linkID>`; inserts the `links` row with `token_hash` and `generation = 1`; commits; then calls `syncLinkChannel`. The token is delivered in the poll response even if that sync fails, because the console row is authoritative and the channel is derived from it: the sync runs again at console start and before every `/api/link/` handler, and can only ever write the console's current state. |
| - - **One writer (Paul's choice 1).** Console `links` gains `token_hash TEXT NOT NULL` and `generation INTEGER NOT NULL`. `func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error` reads the `links` row and writes the registry from it alone: `PutLinkChannel{TokenHash: row.token_hash, Generation: row.generation, Status: active}` for a live link, `RevokeLinkChannel` for a revoked one. It never takes a hash from a request. Rotate and unlink change the console row in one transaction (rotate: new hash, `generation+1`, old token revoked; unlink: `revoked_at`), then call `syncLinkChannel`. It is the only caller of `PutLinkChannel` and `RevokeLinkChannel`. The poll response for a link adds `link_id`, `account` (sqid), `tunnel_url` (`https://` + `TunnelHost` + `/register`; `tunnelclient.Dial` accepts only `https` and `http`, `tunnelclient.go:204-220`) and `apps_domain`. |
| + - **One writer (Paul's choice 1).** Console `links` gains `token_hash TEXT NOT NULL` and `generation INTEGER NOT NULL`. `func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error` reads the `links` row and writes the registry from it alone: `PutLinkChannel{TokenHash: row.token_hash, Generation: row.generation, Status: active}` for a live link, `RevokeLinkChannel` for a revoked one. It never takes a hash from a request. Rotate and unlink change the console row in one transaction (rotate: new hash, `generation+1`, old token revoked; unlink: `revoked_at`), then call `syncLinkChannel`. It is the only caller of `PutLinkChannel` and `RevokeLinkChannel`. On success it records `links.synced_generation` (and `links.revoke_synced = 1` for a revoked link) in the console DB. |
| + - **Delivery retry.** `func (s *Server) linkSyncLoop(ctx context.Context)` runs every 10 s on the serving console and calls `syncLinkChannel` for every link whose `synced_generation < generation` or that is revoked with `revoke_synced = 0`. It reads only the console DB and writes only the registry (no bucket reads). Rotate and unlink also retry their own sync three times with a short backoff before returning. So a failed registry write is repaired without any further API call or restart, revoked links included. The poll response for a link adds `link_id`, `account` (sqid), `tunnel_url` (`https://` + `TunnelHost` + `/register`; `tunnelclient.Dial` accepts only `https` and `http`, `tunnelclient.go:204-220`) and `apps_domain`. |
| - Link tokens never expire: `expires_at = 0` for `kind='link'`, and the expiry purge (`authstore.go:478`) skips them. They are excluded from `CLITokens(address)` listings (`authstore.go:718-720`), `RevokeCLIToken` (`:763`) and `RevokeAccountToken` (`svcprincipal.go:534`); the only ways to end one are rotate and unlink (Task 5, Task 6), which also revoke the channel. |
| - The rate key for link principals is the link ID (`principalKey`, `svcprincipal.go:577`), not the account. |
| @@ -182,7 +183,7 @@ Risk: authority. Gets its own review. |
| - `TestLinkApprovalMintsLinkToken`: start with purpose link → approve for account A with step-up → poll returns token, `link_id`, `account`, `tunnel_url`; `CLIPrincipal(token)` is `PrincipalLink` for A; registry `LinkOwners()[link_id] == A.Sqid`; `LinkChannelAuth()` holds sha256(token); `tunnelclient.Dial` accepts the returned `tunnel_url`'s scheme against an `httptest` TLS hub. |
| - `TestLinkTokenLifecycle`: the token has `expires_at = 0`, survives the purge with the clock advanced past `CLITokenTTL`, does not appear in `CLITokens(address)`, and is not revoked by `RevokeCLIToken` or `RevokeAccountToken`. |
| - `TestLinkApprovalNeedsCreateRole`: an approver without the create role does not see account A in the picker and a forged POST naming A is refused. |
| - - `TestLinkTokenRefusedEverywhereElse`: walk `routeDecls`; for every route under `/api/cli/` and every person-only door, a request with the link token gets 401 or 403 (never 2xx). Fill every placeholder the declarations use (not only `acct`/`app`/`host`) from one table that fails the test on an unknown placeholder, and enable every configuration gate the declarations carry (`routedecls.go:35`, `:456`) so gated routes are exercised. As a positive control, the same walk with a person token reaches at least one handler past the gate. |
| + - `TestLinkTokenRefusedEverywhereElse`: walk **every** `routeDecl` except `kindLink` (browser, CLI, plain and person-only alike); a request with the link token gets exactly the status the same request gets with no bearer at all. The reverse: every `kindLink` door answers 401 to person, app and service tokens. Fill every placeholder the declarations use (not only `acct`/`app`/`host`) from one table that fails the test on an unknown placeholder, and enable every configuration gate the declarations carry (`routedecls.go:35`, `:456`) so gated routes are exercised. As a positive control, the same walk with a person token reaches at least one handler past the gate. |
| - `TestPlainLoginUnchanged`: start without purpose → token is user-kind as today. |
| - [ ] **Step 2:** `go test ./internal/console -run 'TestLinkApproval|TestLinkTokenRefused|TestPlainLoginUnchanged'` — FAIL. |
| - `TestSyncCannotResurrect`: a request authenticated with token A pauses (test barrier) before its pre-handler sync; rotate installs B (generation 2); the paused request resumes and syncs; the registry still holds B. Same with unlink: the registry stays revoked. |
| @@ -203,11 +204,11 @@ Risk: authority, plan caps. Gets its own review. |
| **Interfaces:** |
| - Consumes: Task 4's `PrincipalLink`, `LinkByID`; Task 1's registry methods; `checkCreateApp` (`plancaps.go:285`) under `planLock`; `allowAppCreate` (`svcprincipal.go:602`); `insertAppRow`; `Config.AppsDomain`. |
| - Produces: |
| - - A new route kind `kindLink` in `routedecls.go`, registered through one gate `func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc` that resolves the bearer with `CLIPrincipal`, admits only `PrincipalLink` (anything else gets `cliNotSignedIn`'s 401), runs `syncLinkChannel` for the link, and puts the principal on the context. Link handlers call no resolver themselves. Extend `registerDecls`, `TestRouteDeclsMatchRegistrations` and the resolver scan in `TestAuthCLIFamilyResolvesOnlyPersons` (`svcroutes_test.go:1423, 1506`) so `linkRoute` is the one permitted resolver site for `kindLink`. `kindLink` is not a parity member (machine-to-machine doors with no browser twin). |
| + - A new route kind `kindLink` in `routedecls.go`, registered through one gate `func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc` that resolves the bearer with `CLIPrincipal`, admits only `PrincipalLink` (anything else gets `cliNotSignedIn`'s 401), runs `syncLinkChannel` for the link (answering 503 when that sync fails), and puts the principal on the context. Link handlers call no resolver themselves. Extend `registerDecls`, `TestRouteDeclsMatchRegistrations` and the resolver scan in `TestAuthCLIFamilyResolvesOnlyPersons` (`svcroutes_test.go:1423, 1506`) so `linkRoute` is the one permitted resolver site for `kindLink`. `kindLink` is not a parity member (machine-to-machine doors with no browser twin). |
| - The doors (all `kindLink`): |
| - `GET /api/link` → `{"link_id","account","name","publications":[{"app","url","created_at"}]}` |
| - `POST /api/link/publications` body `{"app":"<name>"}` → 201 `{"app","url"}`. Name rules as for app create. Refusals: name taken in the account by anything other than this link's own linked app (409, deck string), cap (409 `{"code":"cap"}` as today), rate limit (429). Writes the `apps` row with `LinkID` set, then `reg.PutForward(Route{Kind: KindForward, Host: app+"."+acct.Sqid+"."+AppsDomain, App: app, Account: acct.Sqid, Region: "link/"+linkID})`. **Idempotent for the same link:** when this link already has a linked app of that name, it re-puts the forward row and answers 200 with the same body, so a retry after a partial failure completes instead of answering "name taken". |
| - - `DELETE /api/link/publications/{app}` → 204. `DeleteLinkForward(host, linkID)` first, then the `apps` row (only where `linked_link_id` = this link). A missing row on either side is not an error. |
| + - `DELETE /api/link/publications/{app}` → 204. `DeleteLinkForward(host, linkID)` first, then the `apps` row (only where `linked_link_id` = this link) through the same cleanup as `PurgeAppRow` (`store.go:2136`: stars, lapse items), so a re-created name inherits nothing. A missing row on either side is not an error. |
| - `POST /api/link/rotate` → 200 `{"token"}`: one console transaction (new token and hash, `generation+1`, old token revoked), then `syncLinkChannel` (the hub then closes the old connection, Task 3). |
| - `DELETE /api/link` → 204: `func (s *Server) unlink(ctx, l *Link, by string) error` — one console transaction sets `revoked_at` and revokes the token; then `syncLinkChannel` (which runs `RevokeLinkChannel`, removing every `link/<id>` forward row atomically in the registry); then every `apps` row with this `linked_link_id` is deleted. |
| - **Linked app rows are removed only by unpublish and unlink.** `claimRawTrashAppRow`, `PurgeAppRow`, the bucket-convergence trash and purge (`materialize.go:402, 431`; `settle.go:102, 144`) and the expiry passes (`expirypass.go:255`, `lifetimes_purge.go:258`) skip or refuse rows with `linked_link_id` set. `ReapAccount`'s caller (`materialize.go:120`) runs `unlink` for each of the account's links first. |
| @@ -241,7 +242,7 @@ Risk: authority, plan caps. Gets its own review. |
| - Produces: |
| - `type accountLinkCard struct { ID, Name, CreatedBy string; CreatedAt time.Time; Reachable bool; LastSeen time.Time; Apps []accountLinkApp }`, `type accountLinkApp struct { Name, URL string }`. Reachability from `reg.LinkSeen()`. |
| - Page field `AccountLinks []accountLinkCard`. |
| - - `POST /a/{sqid}/links/{id}/unlink` (browser, same role as fleet detach, CSRF as the existing fleet POSTs) and `GET /api/cli/links/{account}`, `DELETE /api/cli/links/{account}/{id}` (person CLI). Unlink shares one function with Task 5's `DELETE /api/link`: `func (s *Server) unlink(ctx context.Context, l *Link, by string) error`. |
| + - `POST /a/{sqid}/links/{id}/unlink` (browser, same role as fleet detach, CSRF as the existing fleet POSTs) and `GET /api/cli/links/{account}`, `DELETE /api/cli/links/{account}/{id}` (person CLI). Unlink shares one function with Task 5's `DELETE /api/link`: `func (s *Server) unlink(ctx context.Context, l *Link, by string) error`, which is re-runnable on an already revoked link. The card stays, marked "removing", until the registry has no channel or forward rows for the link and no `apps` row carries its ID; the person doors can run unlink again on such a card. |
| - The apps list marks linked apps with the deck's "served from <home name>" label. The Fleet tab's platform-app count (`accountfleet.go:144`) and `regionlabel.ForRoute` both treat a `link/<id>` row as linked, not as a platform app or a region code. |
| - Parity rows for the new routes. |
| @@ -259,11 +260,11 @@ Risk: authority, plan caps. Gets its own review. |
| **Interfaces:** |
| - Produces (registry, home side): |
| - - Table `home_link(id TEXT PRIMARY KEY, serving_url TEXT, tunnel_url TEXT, token TEXT, account TEXT, apps_domain TEXT, box_label TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT '', created_at INTEGER)` — at most one row in slice 1. `state` (`connected` | `reconnecting` | ``) is written by the claiming agent and excluded from `Fingerprint`. |
| + - Table `home_link(id TEXT PRIMARY KEY, serving_url TEXT, tunnel_url TEXT, token TEXT, account TEXT, apps_domain TEXT, box_label TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT '', conn_gen INTEGER NOT NULL DEFAULT 0, created_at INTEGER)` — at most one row in slice 1. `conn_gen` is in `Fingerprint`. `state` (`connected` | `reconnecting` | ``) is written by the claiming agent and excluded from `Fingerprint`. |
| - `func (r *Registry) SetHomeLinkState(state string) error` |
| - Table `home_link_apps(name TEXT PRIMARY KEY, home_account TEXT NOT NULL, home_app TEXT NOT NULL, home_host TEXT NOT NULL, created_at INTEGER)` — the published set; `name` is the serving-side app name. `home_account`/`home_app` are the authority; `home_host` is where to find the route. |
| - `type HomeLinkApp struct { Name, HomeAccount, HomeApp, HomeHost string }` |
| - - `func (r *Registry) HomeLink() (*HomeLink, error)` (nil when unlinked), `PutHomeLink(HomeLink) error`, `DeleteHomeLink() error` (also clears `home_link_apps`), `ClaimHomeLink(label string) (bool, error)` (conditional update where `box_label = ''`), `HomeLinkApps() ([]HomeLinkApp, error)`, `HomeLinkAppByName(name string) (*HomeLinkApp, error)` (nil when not published; read on **every** link request, Task 8), `PutHomeLinkApp(a HomeLinkApp) error`, `DeleteHomeLinkApp(name string) (bool, error)`. |
| + - `func (r *Registry) HomeLink() (*HomeLink, error)` (nil when unlinked), `PutHomeLink(HomeLink) error`, `DeleteHomeLink() error` (also clears `home_link_apps`), `ClaimHomeLink(label string) (bool, error)` (conditional update where `box_label = ''`), `HomeLinkApps() ([]HomeLinkApp, error)`, `HomeLinkAppByName(name string) (*HomeLinkApp, error)` (nil when not published; read on **every** link request, Task 8), `PutHomeLinkApp(a HomeLinkApp) error`, `DeleteHomeLinkApp(name string) (bool, error)`. `DeleteHomeLinkApp`, and `PutHomeLinkApp` when it changes an existing name's home account, app or host, increment `home_link.conn_gen` in the same transaction. `func (r *Registry) HomeLinkConnGen() (uint64, error)`. |
| - The `token` column is never returned by any console API and never logged. |
| - Produces (console, home side; system-operator gate, the one `carlos system` commands use): |
| - `POST /api/cli/link/start {"to":"<serving console URL>","name":"<home name>"}` → calls the serving `/auth/cli/start` with purpose link and refuses (deck string) when the response does not echo `"purpose":"link"`, and later when the poll's approved response lacks `link_id` or `tunnel_url`; returns `{"verification_uri","user_code"}`; the home console polls the serving console in the background until approved, denied or expired, then `PutHomeLink`. |
| @@ -292,21 +293,27 @@ Risk: the anti-goal 1 guard. Gets its own review. |
| - Consumes: Task 7's registry methods, `tunnelclient.Loop`, `tunnelclient.LinkAppHeader`, `(*Edge).OnReload` (`edge.go:1519`). |
| - Produces: |
| - **Pinned pipeline (Paul's choice 2).** `func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, want LinkedTarget)` with `type LinkedTarget struct { Host, Account, App, PublicHost string }`. It puts `want` on the request context (`withLinkPin`) and runs the edge's **normal** `ServeHTTP` path with `r.Host = want.Host`, so every stage a tailnet request to that host passes (admission, the import gate with its header strip, plan-disabled, the password gate, upgrade tracking, activator) runs unchanged. The pin changes exactly two things: |
| - - **Upstream selection.** With a pin, selection uses only the exact upstream map entry for `want.Host` (never the wildcard or path-map targets of `lookupUpstream`/`lookupUpstreamPath`, `edge.go:1785, 1840`) and admits it only when its route has `Account == want.Account`, `App == want.App`, `Kind == "instance"` and a local socket or activator-owned backend. Anything else answers 502 with the deck's "not on this box" string. With a pin, every edge-owned path handler (ACME, purge, status, devbox, admin, edge-owned static at `edge.go:1193`) is skipped: the only possible outcomes are a stage's refusal or the pinned upstream. |
| - - **What the app sees.** The proxy sends `Host: want.PublicHost` (the public hostname from the hub's `X-Forwarded-Host`) and keeps `X-Forwarded-Proto: https`, so same-origin checks and generated redirects use the public origin. Selection never reads either header. |
| + - **Upstream selection, one site.** `func (e *Edge) selectUpstream(r *http.Request, host, path string) (*upstream, bool)` becomes the only request-path caller of `lookupUpstream`/`lookupUpstreamPath` (`edge.go:1785, 1840`). Every request-path site calls it instead: `edge.go:2126`, the login re-resolution at `:2405`, `demo.go:94` and `:116`, `pagecache.go:533`. With a pin it uses only the exact upstream map entry for `want.Host` (no wildcard or path-map targets) and admits it only when its route has `registry.EffectiveAccount(rt) == want.Account`, `App == want.App`, `Kind == "instance"` and a local socket or activator-owned backend; anything else answers 502 with the deck's "not on this box" string. |
| + - **Edge-owned handlers.** With a pin, the edge-owned handlers inside `ServeHTTP` are skipped: HA control (`edge.go:1984`), hop acceptance (`:2088`), burst notice (`:2094`), the replica probe (`:2137`), demo handling (`:1998`), and edge-owned static/status (`:1193`). The only possible outcomes are a stage's refusal or the pinned upstream. |
| + - **Public origin throughout.** Under a pin the request's public authority is `want.PublicHost` (from the hub's `X-Forwarded-Host`) with scheme https. Origin-sensitive stages use it: the password gate's Origin check (`internal/gate/gate.go:189`) compares against the public origin; at the backend boundary the proxy sends `Host: want.PublicHost`, `X-Forwarded-Host: want.PublicHost` and `X-Forwarded-Proto: https` (after `setForwarded`, `homemap.go:1676`, which would otherwise write the home host). Selection never reads these. |
| + - **No home caching for linked requests.** Pinned requests skip the edge LRU, the page cache and the asset catch in both directions (as forward rows do on the hub, `edge.go:2790`), so a response rendered for one origin is never replayed to the other. A `Carlos-Purge-Host` equal to `want.PublicHost` is treated as the route's own. |
| - `type linkHandler struct { reg linkRegistry; serve func(w, r, LinkedTarget) }` with `ServeHTTP`: reads `LinkAppHeader`; calls `reg.HomeLinkAppByName` **per request** (so an unpublish is refused from the next request, without waiting for a reload); missing header or not published → 404 with the deck string; otherwise `serve` with the published account, app and host. It never selects by the request's Host. |
| - - **Connection replacement (Paul's choice 3).** No per-stream tracking. When a reload shows that a published name has disappeared, the loop cancels the running `tunnelclient.Loop` and starts a new one, which ends every in-flight request and stream on the old connection (WebSockets, SSE, long downloads alike). Other published apps reconnect within about a second. Bound: an unpublished app's open streams end within one registry watch (2 s) plus the cancel. |
| - - `func linkLoop(e *edge.Edge, reg linkRegistry, label string)` — `label` is the agent's box label when it has one, else `os.Hostname()`. It writes the loop's state with `SetHomeLinkState` from `OnState`: on start and on every `OnReload`, reads `HomeLink()` and `HomeLinkApps()` (replacing the connection when a name disappeared); claims with `ClaimHomeLink(label)` when unclaimed; when the link exists and `box_label == label`, runs one `tunnelclient.Loop` with `Name = registry.LinkChannelName(id)`, `Token`, `URL = tunnel_url`, `Handler = linkHandler`; cancels it on unlink, rotation (token change) or loss of the claim. Never claims when `tunnelEnvComplete()` is true (a fleet box). |
| + - **Connection replacement (Paul's choice 3).** No per-stream tracking. When a reload shows that `HomeLinkConnGen()` changed (every unpublish and every retarget bumps it, Task 7), the loop cancels the running `tunnelclient.Loop` and starts a new one, which ends every in-flight request and stream on the old connection (WebSockets, SSE, long downloads alike). Other published apps reconnect within about a second. Bound: an unpublished app's open streams end within one registry watch (2 s) plus the cancel. |
| + - `func linkLoop(e *edge.Edge, reg linkRegistry, label string)` — `label` is the agent's box label when it has one, else `os.Hostname()`. It writes the loop's state with `SetHomeLinkState` from `OnState`: on start and on every `OnReload`, reads `HomeLink()` and `HomeLinkApps()` (replacing the connection when `conn_gen` changed); claims with `ClaimHomeLink(label)` when unclaimed; when the link exists and `box_label == label`, runs one `tunnelclient.Loop` with `Name = registry.LinkChannelName(id)`, `Token`, `URL = tunnel_url`, `Handler = linkHandler`; cancels it on unlink, rotation (token change) or loss of the claim. Never claims when `tunnelEnvComplete()` is true (a fleet box). |
| - [ ] **Step 1: Write failing tests** (real registry in a temp dir, real `edge.New`, a real hub `TunnelHub` from Task 3, real `tunnelclient.Loop`, a Unix-socket test app; pattern `replicaTunnelFixture`): |
| - `TestLinkServesPublishedApp`: publish `shop` → request through the hub reaches the `shop` socket. |
| - `TestLinkRefusesUnpublished`: a second home app `admin` with a route on the same box; hub-side requests carrying `Carlos-Link-App: admin`, no header, and `Carlos-Link-App: shop` with `Host: admin...` → the first two get 404, the third reaches `shop`, and the `admin` socket sees zero requests. |
| - `TestLinkUnpublishStopsServing`: with the home edge's reload paused, unpublish → the next request is 404 from home; an already-open WebSocket and an open SSE response for that app both end within one watch interval after reloads resume, and a request to another published app succeeds after the reconnect. |
| - `TestLinkHostReassigned`: publish `shop` (account a1, app shop, host H); re-point host H in the registry to app `admin` → requests naming `shop` get 502, `admin` sees none. |
| - - `TestLinkIgnoresPathMapAndEdgeHandlers`: a `route_paths` prefix on H pointing at `admin`, and an edge-owned status handler host, are never reached through the link. |
| + - `TestLinkIgnoresPathMapAndEdgeHandlers`: a `route_paths` prefix on H pointing at `admin`, an edge-owned status handler host, and a gate login POST on H with `next=/<admin prefix>/` (judged against `shop`'s gate, never `admin`'s) are never routed to `admin` through the link. |
| + - `TestSelectUpstreamIsTheOnlySite`: a source scan of `internal/edge` fails when any function other than `selectUpstream` and the non-request builders it lists calls `lookupUpstream` or `lookupUpstreamPath`. |
| + - `TestLinkReuseNameBetweenTicks`: with an open SSE response and an open WebSocket for `shop` published as `demo`, unpublish `demo` and publish `admin` as `demo` before the next watch tick; both streams end within one watch interval. |
| + - `TestLinkGateLoginFromPublicOrigin`: a published app that gains a password gate accepts a correct login POST whose `Origin` is the public origin. |
| + - `TestLinkNoHomeCacheReplay`: a cacheable response served through the link is never replayed to a tailnet request for the home host, and the reverse. |
| - `TestLinkGatedAppRefused`: a published app that later gains a password gate gets the gate's answer, not the app. |
| - `TestLinkImportGatedAppRefused`: a published app that later gains an import gate answers 503 through the link, and a client-sent `ImportVerifyHeader` is stripped. |
| - - `TestLinkAppSeesPublicOrigin`: the backend sees `Host` equal to the public hostname and `X-Forwarded-Proto: https`; a backend enforcing `Origin == https://<Host>` accepts a WebSocket and a form POST. |
| + - `TestLinkAppSeesPublicOrigin`: the backend sees `Host` and `X-Forwarded-Host` equal to the public hostname and `X-Forwarded-Proto: https`; a backend enforcing `Origin == https://<Host>` accepts a WebSocket and a form POST. |
| - `TestLinkPinSkipsEdgeHandlers`: with a pin, `/.well-known/acme-challenge/x`, the edge's status path and a purge request reach the pinned app or a refusal, never the edge's own handler. |
| - `TestLinkLoopFollowsRegistry`: link added → loop dials within one reload; token rotated → redials with the new token; unlinked → loop stops. |
| - `TestFleetBoxNeverClaims`: with tunnel env complete, `ClaimHomeLink` is never called. |
| @@ -315,6 +322,21 @@ Risk: the anti-goal 1 guard. Gets its own review. |
| - [ ] **Step 4:** PASS. |
| - [ ] **Step 5:** Commit `host: home link loop that serves only published apps`. |
| +### Task 11: Revocation simulations (one invariant, three sides) |
| + |
| +Risk: the revocation family that recurred in all three plan rounds. Gets its own review. Runs after Tasks 3, 5 and 8 (numbered 11 to keep earlier task numbers stable). |
| + |
| +**Invariant.** After any revocation event (unpublish, retarget, rotate, unlink), within a bound and with no further API call or restart, nothing revoked is served: no hub connection on a revoked hash, no hub row for an unpublished or unlinked publication, and no home request or stream for a publication that is no longer published with the same (name, account, app). The registry is the contract between the sides, so each side is simulated against it. |
| + |
| +**Files:** |
| +- Create: `internal/console/link_sim_test.go`, `internal/edge/link_sim_test.go`, `internal/host/link_sim_test.go` |
| + |
| +- [ ] **Step 1: Serving side** (`internal/console`): seeded random sequences (at least 500 seeds, each up to 40 steps) of publish, unpublish, rotate, unlink, retry, `linkSyncLoop` ticks and injected registry failures (a fault-injecting `consoleRegistry` wrapper that fails a chosen write once). After the sequence plus 3 ticks with no faults, the registry equals the state derived from the console DB: no active channel for a revoked link, the active hash is the current one, and the link forward rows are exactly the live publications. Print the seed on failure. |
| +- [ ] **Step 2: Hub side** (`internal/edge`): seeded random sequences of registry mutations (channel put with higher or stale generation, revoke, forward put and delete) interleaved with home dials using current and stale tokens. After one reload: no channel is connected on a hash that is not the registry's active one, and no request is dialled for a row the registry no longer holds. |
| +- [ ] **Step 3: Home side** (`internal/host`): seeded random sequences of publish, unpublish, retarget and same-name reuse between watch ticks, with open SSE and WebSocket streams. After one watch interval plus the cancel, no request or stream is live for a (name, account, app) that is not currently published, and every request admitted after an unpublish of its name was refused. |
| +- [ ] **Step 4:** `TMPDIR=/tmp/g go test ./internal/console ./internal/edge ./internal/host -run 'LinkSim'` — PASS; run once with `-count=3` before review. |
| +- [ ] **Step 5:** Commit `link: revocation simulations on all three sides`. |
| + |
| ### Task 9: CLI — `carlos link` and `carlos links` |
| **Files:** |
| @@ -349,4 +371,5 @@ Risk: the anti-goal 1 guard. Gets its own review. |
| ## Self-review notes |
| - Spec coverage: §5.1 (Tasks 4, 7, 9), §5.2 (5, 7, 9), §5.3 (5, 6, 7, 9), §5.4 (6), §6.0 (5), §6.1 (4, 5), §6.2 (1, 3, 8), §6.3 (8), §6.4 (3), §6.7 (5, cap and rate; metering is unchanged forward-row behaviour), §6.8 (accepted, no task), §6.9 (version floor: an old hub has no link auth, so `/register` refuses; an old home has no link commands). §6.5 and custom domains are refused in slice 1 (Tasks 5, 7). |
| -- Review Focus lines each have a test: 1 → Tasks 3, 4; 2 → Task 8; 3 → Tasks 3, 5; 4 → Task 2; 5 → Tasks 7, 8. |
| +- Review Focus lines each have a test: 1 → Tasks 3, 4; 2 → Task 8; 3 → Tasks 3, 5, 11; 4 → Task 2; 5 → Tasks 7, 8, 11. |
| +- Execution order: 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 9, 10. |