| index 135822530..a9ab86e82 100644 |
| --- a/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md |
| +++ b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md |
| @@ -18,7 +18,9 @@ |
| - Hub-set header naming the published app: `Carlos-Link-App`. Stripped from every inbound client request and set only by the hub on requests going down a link channel. |
| - Link credential: a `cli_tokens` row with `kind = "link"`; its sha256 hex is also the channel's token hash in the hub registry. One secret, two uses. |
| - 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 `remote_dispatch.go` when the agent uses them through `OpenRemote`. |
| +- 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 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 2, after round 1 (Astra and Fable, both NOT READY; findings in `docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md`). |
| - 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`). |
| - Socket tests run with `TMPDIR=/tmp/g` (Unix socket path length). |
| @@ -28,7 +30,7 @@ |
| ## Review Focus |
| |
| 1. **A link credential used anywhere but its own doors.** A link token presented to the store door, the replica coordinator, interactive/run/demo box doors, any `/api/cli/` route, or `/register` under another name must be refused. Tests in Tasks 3 and 4. |
| -2. **Unpublished app reached through the tunnel.** Missing header, header naming an unpublished app, a client-supplied `Carlos-Link-App`, a Host header naming another home app: the home handler must refuse each without touching an instance. Test in Task 8. |
| +2. **Unpublished app reached through the tunnel.** Missing header, header naming an unpublished app, a client-supplied `Carlos-Link-App`, a Host header naming another home app, a host later re-pointed to another app, a path-map prefix: the home handler must refuse each without touching an instance. Tests in Task 8. |
| 3. **Revocation that doesn't cut a live connection.** Rotate and unlink while the tunnel is connected: the old channel closes within one hub reload and the old token cannot redial. Test in Task 3 (edge) and Task 5 (console end to end). |
| 4. **Link rows deleted or altered by other passes.** A full hub `provision.Reconcile` pass and a `domains` reconcile pass leave link rows untouched and mint no platform alias for them. Test in Task 2. |
| 5. **Unpublish ordering.** Unpublish while requests are in flight: the home set drops the app before the serving console is called, so a hub that has not reloaded yet still gets a refusal from home. Test in Task 7. |
| @@ -57,7 +59,7 @@ Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appear |
| |
| **Files:** |
| - Create: `internal/registry/links.go`, `internal/registry/links_test.go` |
| -- Modify: `internal/registry/registry.go` (migrate chain after `migrateHADuties`; `Fingerprint` section), `internal/registry/forward.go:363-371` (accept link placement), `internal/host/remote_dispatch.go`, `internal/console/view.go:522` |
| +- Modify: `internal/registry/registry.go` (migrate chain after `migrateHADuties`; `Fingerprint` section), `internal/registry/forward.go:363-371` (accept link placement), `internal/registry/remote_dispatch.go`, `internal/console/view.go:522` |
| |
| **Interfaces:** |
| - Produces: |
| @@ -72,17 +74,22 @@ Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appear |
| - `func (r *Registry) LinkChannelAuth() (map[string]string, error)` — active rows keyed by `LinkChannelName`. |
| - `func (r *Registry) LinkOwners() (map[string]string, error)` — active link ID → account sqid. |
| - `func (r *Registry) SetLinkSeen(linkID string, connected bool, at time.Time) error` and `func (r *Registry) LinkSeen() (map[string]LinkSeen, error)` with `type LinkSeen struct { Connected bool; At time.Time }`. These columns are **excluded** from `Fingerprint` (they change on every connect and must not trigger reloads). |
| - - `PutForward` accepts `Region` for which `LinkPlacement` is ok, alongside fleet placements. |
| + - `PutForward` accepts `Region` for which `LinkPlacement` is ok, alongside fleet placements. **Placement classes are disjoint:** in the same transaction, `PutForward` returns `ErrHostHeld` when a forward row already holds the host with a different class (fleet vs link) or, for link rows, a different link ID. Fleet rows written by the provision pass can therefore never overwrite a link row, nor a link row a fleet row. |
| + - `func (r *Registry) DeleteLinkForward(host, linkID string) (bool, error)` — deletes only a forward row whose Region is exactly `link/<linkID>`. `DeleteForward` refuses (returns false) for any link-placed row, so only the link's own owner path can remove it. |
| + - `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)`. |
| +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)`. |
| |
| - [ ] **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`. |
| - `TestLinkSeenDoesNotMoveFingerprint`: `Fingerprint()` before and after `SetLinkSeen` is equal; after `PutLinkChannel` it differs. |
| -- [ ] **Step 2:** `go test ./internal/registry -run 'TestLink|TestPutForwardAcceptsLinkPlacement'` — FAIL (undefined). |
| -- [ ] **Step 3:** Implement `links.go`, the migration, the `PutForward` placement check, the Fingerprint section, and the `consoleRegistry` / `remote_dispatch.go` entries for `PutLinkChannel`, `RevokeLinkChannel`, `LinkChannelAuth`, `LinkOwners`, `SetLinkSeen`, `LinkSeen`, plus the home-side methods of Task 7 when that task lands. |
| +- [ ] **Step 2:** `go test ./internal/registry -run 'TestLink|TestPutForwardAcceptsLinkPlacement|TestForwardClassesDisjoint'` — FAIL (undefined). |
| + - `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. |
| +- [ ] **Step 3:** Implement `links.go`, the migration, the `PutForward` placement check, the Fingerprint section (with `connected`, `seen_at` and `seq` excluded), and the `consoleRegistry` / `internal/registry/remote_dispatch.go` entries for `PutLinkChannel`, `RevokeLinkChannel`, `LinkChannelAuth`, `LinkOwners`, `SetLinkSeen`, `ResetLinkSeen`, `LinkSeen`, `LinkForwards`, `DeleteLinkForward`, and also `PutForward` (missing from `consoleRegistry` today), plus the home-side methods of Task 7 when that task lands. |
| - [ ] **Step 4:** Same command — PASS. Also `go test ./internal/registry ./internal/host -run 'Remote|Fingerprint'`. |
| - [ ] **Step 5:** Commit `registry: link channels and link placement for forward rows`. |
| |
| @@ -100,7 +107,7 @@ Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash |
| - `TestNonHubReconcileKeepsLinkRows`: same on a non-hub cfg (today every forward row is retired there); the link row survives. |
| - `TestDomainsReconcileSkipsLinkRows`: domains reconcile over a registry with a link row mints no platform alias and removes nothing for it. |
| - [ ] **Step 2:** `go test ./internal/provision ./internal/domains -run 'LinkRows'` — FAIL on the retirement. |
| -- [ ] **Step 3:** In `retirements`, skip any row for which `registry.LinkPlacement(rt.Region)` is ok. Confirm `decideForward` cannot write over a link host (a bucket record with the same host is refused as host-held, through `PutForward`'s existing `ErrHostHeld`/kind checks; add the assertion to the first test). |
| +- [ ] **Step 3:** In `retirements`, skip any row for which `registry.LinkPlacement(rt.Region)` is ok. `mint` (`internal/provision/forward.go:288-302`) treats an existing forward row as its own today; make it report a link-placed row as held (skip, with the existing held reporting), relying on Task 1's disjoint `PutForward` as the backstop. Add to the first test: a bucket record naming the link host leaves the link row unchanged and is reported held. |
| - [ ] **Step 4:** Same command — PASS. |
| - [ ] **Step 5:** Commit `provision: keep link forward rows out of the retirement pass`. |
| |
| @@ -109,7 +116,7 @@ Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash |
| Risk: security gate and production serving path. Gets its own review. |
| |
| **Files:** |
| -- Modify: `internal/edge/edge.go` (Reload ~956-1053, ~1433; `fleetProxy` ~4057-4072; inbound strip ~2120; `scrubTunnelMarkers` ~3984), `internal/edge/fleetforward.go:57-115, 261`, `internal/edge/tunnel.go:391` (`SetDynamicAuth`), `internal/edge/storedoor.go:169-205`, `internal/console/apiinteractivebox.go:117` |
| +- Modify: `internal/edge/edge.go` (Reload ~956-1053, ~1433; `fleetProxy` ~4057-4072; inbound strip ~2120; `scrubTunnelMarkers` ~3984; upgrade admission ~2687), `internal/edge/upgrades.go:210` (tenancy match), `internal/edge/fleetforward.go:117-176, 230, 261-286`, `internal/edge/tunnel.go` (`VerifyDynamic` :334-352, `ServeHTTP` :165-274, `SetDynamicAuth` :391), `internal/edge/storedoor.go:169-205`, `internal/console/apiinteractivebox.go:117`, and every `FleetArmVerdict` caller: `internal/host/hub.go:26-36, 72` (`fleetArmInputs`), `internal/host/edgesfile.go:649`, `internal/console/apiinstances.go:429` |
| - Create: `internal/edge/linkforward.go`, `internal/edge/linkoffline.go` |
| - Test: `internal/edge/link_e2e_test.go`, `internal/edge/linkforward_test.go`, `internal/console/fleetidentity_link_test.go` |
| |
| @@ -117,10 +124,16 @@ Risk: security gate and production serving path. Gets its own review. |
| - Consumes: Task 1's registry methods. |
| - Produces: |
| - `const LinkAppHeader = "Carlos-Link-App"` (in `internal/tunnelclient` beside `UpgradeHeader`, so the home side shares it). |
| - - `FleetServeEligible` and `FleetArmVerdict` take link owners too: signature becomes `FleetServeEligible(rt registry.Route, hub bool, owners, linkOwners map[string]string) (ok bool, why string)`. A link row is eligible iff hub, `InertForward()`, `LinkPlacement` ok, and `rt.Account != "" && rt.Account == linkOwners[id]`. One function judges both kinds. |
| + - `type ForwardOwners struct { Fleets, Links map[string]string }` replaces the bare owners map in both judges: |
| + - `FleetServeEligible(rt registry.Route, hub bool, owners ForwardOwners) (ok bool, why string)`. A link row is eligible iff hub, `InertForward()`, `LinkPlacement` ok, and `rt.Account != "" && rt.Account == owners.Links[id]`. One function judges both kinds. |
| + - `FleetArmVerdict(routes []registry.Route, owners ForwardOwners, hub, tunnels bool) FleetVerdict`. `FleetServed` gains `Link string`; the `Arm` map gets an entry for eligible link rows (today it is filled only for `FleetPlacement`, `fleetforward.go:284-286`), and `DispatchArm` returns a new `ArmLink` for them. |
| + - `fleetArmInputs` (`internal/host/hub.go:26-36`) returns `ForwardOwners` with `LinkOwners()`; the edges file (`edgesfile.go:649`) and the console's instance view (`apiinstances.go:429`) pass the same, so link hosts are published for backhaul like fleet hosts. |
| + - The fleet owners snapshot stored for the store door (`edge.go:1435`, read by `fleetAccount`) keeps **fleet owners only**; link owners live in a separate snapshot. |
| + - `VerifyDynamic` refuses every link channel name (returns false). A new `(h *TunnelHub) verifyLink(name, token string) (linkID string, ok bool)` is what `ServeHTTP` uses for names where `registry.LinkOfChannel` is ok. No fleet helper ever returns a link ID as a fleet. |
| + - Upgrade admission: the `tenancy` value gains `Link string`; a request on an `ArmLink` row is admitted for upgrade with `{Arm: ArmLink, Account, App, Link}` and matches at reserve time (`upgrades.go:210`) the same way fleet tenancies do. |
| - `func linkProxy(linkID, app string, hub *TunnelHub) *httputil.ReverseProxy` — dials `LinkChannelName(linkID)`; sets `LinkAppHeader: app` after the shared `tunnelRewrite`. |
| - `SetDynamicAuth` closes a channel whose token hash **changed** when the name is a link channel (`registry.LinkOfChannel`). Fleet rotation keeps today's behaviour. |
| - - On link channel state change the hub calls `reg.SetLinkSeen` (connect and disconnect only, not per request). |
| + - The hub calls `reg.ResetLinkSeen()` once when tunnels are enabled, then `reg.SetLinkSeen(id, seq, connected, now)` on each link channel's register and close (not per request). `seq` is the hub's per-registration sequence already used to tell a replaced connection from the current one (`tunnel.go:269-276`); add one if none is exposed. |
| |
| - [ ] **Step 1: Write failing tests:** |
| - `TestLinkEndToEnd` (pattern: `TestTunnelEndToEnd`, `startFakeRemoteHost`): registry with a link channel and a link forward row for `shop.acct1.apps.example.com`; hub-armed edge; fake home dials `link:<id>/home` with the token; `GET https://shop.acct1.apps.example.com/up` returns the home handler's body, and the handler saw `Carlos-Link-App: shop`. |
| @@ -131,8 +144,11 @@ Risk: security gate and production serving path. Gets its own review. |
| - `TestLinkCredentialRefusedByStoreDoor`: a link channel name and token against `/store/o/...` → 404. |
| - `TestFleetIdentityRefusesLinkChannel` (console): `fleetIdentityOK(reg, "link:<id>/home", token, "link:<id>", acct)` is false, and so is every fleet name. |
| - `TestConnectedOfFleetIgnoresLinks`: a connected link channel never appears in `ConnectedOfFleet(f)` for any fleet `f`. |
| - - `TestLinkSeenRecorded`: connect then disconnect flips `LinkSeen()[id].Connected`. |
| -- [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/edge ./internal/console -run 'Link|FleetIdentityRefusesLink'` — FAIL. |
| + - `TestLinkSeenRecorded`: connect then disconnect flips `LinkSeen()[id].Connected`; a re-register (second connection with the same name) leaves it connected after the first connection closes. |
| + - `TestLinkWebSocket`: a WebSocket upgrade through the link reaches the home handler and echoes; after `RevokeLinkChannel` and a reload the socket is closed. |
| + - `TestVerifyDynamicRefusesLinks`: `VerifyDynamic("link:<id>/home", token)` is false even with the right token; `verifyLink` accepts it. |
| + - `TestLinkHostsPublishedForBackhaul` (`internal/host`): the edges file built from a registry with an eligible link row lists the link host for the hub, as for a fleet row. |
| +- [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/edge ./internal/console ./internal/host -run 'Link|FleetIdentityRefusesLink|VerifyDynamicRefusesLinks'` — FAIL. |
| - [ ] **Step 3:** Implement. In Reload, merge `LinkChannelAuth()` into the map passed to `SetDynamicAuth`, load `LinkOwners()` beside `FleetOwners()`, arm link rows with `linkProxy`. In the store door, refuse when `registry.LinkOfChannel(name)` is ok before `fleetAccount`. In `fleetIdentityOK`, refuse link channel names first. The offline page follows `internal/edge/plandisabled.go`'s pattern (template built once, `no-store`, `noindex`) with `Retry-After: 30`; `noteCause` stays `apperr.CauseFleetDark`. |
| - [ ] **Step 4:** Same command — PASS. Then `go test ./internal/edge -run 'Fleet|Tunnel|Upgrade'` to check fleet behaviour is unchanged. |
| - [ ] **Step 5:** Commit `edge: serve link forward rows down link channels, with an offline page`. |
| @@ -151,14 +167,17 @@ Risk: authority. Gets its own review. |
| - `type Link struct { ID string; AccountID int64; Name, CreatedBy string; CreatedAt, RevokedAt time.Time }` |
| - `func (s *Store) LinkByID(id string) (*Link, error)`, `func (s *Store) LinksForAccount(accountID int64) ([]Link, error)` |
| - `PrincipalLink` added to `PrincipalKind`; `Principal.LinkID string`. `CLIPrincipal` returns `{Kind: PrincipalLink, AccountID, LinkID}` for an unrevoked `kind = "link"` token whose link is not revoked. |
| - - `POST /auth/cli/start` accepts JSON `{"purpose":"link","name":"<home name>"}`; any other purpose value is 400. Without `purpose` it behaves exactly as today. |
| + - `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; then (after commit) calls `reg.PutLinkChannel(LinkChannel{LinkID, Account: sqid, TokenHash, Status: "active"})`. The poll response for a link adds `link_id`, `account` (sqid), `tunnel_url` (`wss://` + `TunnelHost` + `/register`) and `apps_domain`. |
| + - `PollCLIAuth` for an approved link request, in one transaction: mints the token with `kind='link'`, `account_id`, `name=<linkID>`; inserts the `links` row; then (after commit) calls `reg.PutLinkChannel(LinkChannel{LinkID, Account: sqid, TokenHash, Status: "active"})`. Every `/api/link/` call (Task 5) re-asserts the channel with `PutLinkChannel` when the registry row is missing or differs, so a failure here heals on the home side's next call. 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. |
| |
| - [ ] **Step 1: Write failing tests** (`newConsoleFixture`, `cliToken` helpers): |
| - - `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). |
| + - `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). Build the path from the declared pattern with `acct`/`app`/`host` filled in. |
| + - `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. |
| - `TestPlainLoginUnchanged`: start without purpose → token is user-kind as today. |
| - [ ] **Step 2:** `go test ./internal/console -run 'TestLinkApproval|TestLinkTokenRefused|TestPlainLoginUnchanged'` — FAIL. |
| - [ ] **Step 3:** Implement. Link principals must fail every existing gate by construction: check `cliGateRefused` and `serviceBinding` refuse `PrincipalLink` explicitly, and route link principals only to the `/api/link/` doors of Task 5. |
| @@ -171,26 +190,31 @@ Risk: authority, plan caps. Gets its own review. |
| |
| **Files:** |
| - Create: `internal/console/apilinks.go`, `internal/console/apilinks_test.go` |
| -- Modify: `internal/console/routedecls.go` (new routes), `internal/console/lifetimes_store.go:430-449` (`newAppRow.LinkID`), console `apps` ALTER `linked_link_id TEXT NOT NULL DEFAULT ''`, `internal/console/apicli.go:69-98` (`apiAccountAppSaying`) |
| +- Create: `internal/console/linkedpolicy.go` |
| +- Modify: `internal/console/routedecls.go` (new routes), the parity table read by `internal/console/parity_test.go`, `internal/console/lifetimes_store.go:430-449` (`newAppRow.LinkID`), console `apps` ALTER `linked_link_id TEXT NOT NULL DEFAULT ''`, `internal/console/apicli.go:69-98` (`apiAccountAppSaying`), `internal/console/server.go:5648` (`accountApp`) |
| |
| **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 (all require a `PrincipalLink`; anything else gets 401): |
| - `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 (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})`. |
| - - `DELETE /api/link/publications/{app}` → 204. Deletes the forward row first, then the `apps` row (only where `linked_link_id` = this link). |
| + - `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. |
| - `POST /api/link/rotate` → 200 `{"token"}`: new token, old one revoked, `PutLinkChannel` with the new hash (the hub then closes the channel, Task 3). |
| - - `DELETE /api/link` → 204: every publication deleted as above, token revoked, `RevokeLinkChannel`, `links.revoked_at` set. |
| - - `func linkedAppRefusal(acct *Account, app string) *doorRefusal` consulted by `apiAccountAppSaying` for **every** method (not only mutations), returning 409 with the deck's "managed by its home deployment" string. |
| + - `DELETE /api/link` → 204: for every row in `reg.LinkForwards(linkID)` (the registry is the source of truth, not the `apps` table) `DeleteLinkForward`, then every `apps` row with this `linked_link_id`; token revoked, `RevokeLinkChannel`, `links.revoked_at` set. |
| + - **One linked-app policy for every app door, browser and CLI.** `func linkedAppPolicy(pattern string) linkedPolicy` in `internal/console/linkedpolicy.go`, with `linkedPolicy` one of `linkedAllow` (reads the spec keeps: analytics, protection, usage, the app's overview) or `linkedRefuse` (everything that acts on code, config, instances, data, the app's identity or lifetime: deploy, promote, rollback, environments, config/secrets, instances, runs, exec, logs, db, moves, regions, replicas, schedules, retention, pipeline, place, sidecars, store, relay, email, ledgers, rename, delete, transfer) and, in slice 1, domains. The table is keyed by route pattern from `routeDecls`. |
| + - `func (s *Server) linkedAppRefusal(r *http.Request, acct *Account, app string) *doorRefusal` returns 409 with the deck's "managed by its home deployment" string when the app is linked and the matched pattern's policy is `linkedRefuse`. It is consulted by `apiAccountAppSaying` (all methods, not only mutations) **and** by the browser app resolver `accountApp` (`server.go:5648` and its callers such as `envform.go:722`). |
| |
| - [ ] **Step 1: Write failing tests:** |
| - `TestPublishCreatesLinkedAppAndRow`: publish `shop` → `apps` row with `linked_link_id`, registry forward row with `Region link/<id>`, response URL `https://shop.<sqid>.<AppsDomain>`. |
| - `TestPublishRefusesTakenName`, `TestPublishRespectsCap` (cap fixture at the limit → `{"code":"cap"}`). |
| - `TestUnpublishRemovesRowThenApp`, `TestUnlinkRemovesEverything` (two publications, then unlink: no rows, no apps, link token refused by `CLIPrincipal`, `LinkChannelAuth` empty). |
| - `TestRotateReplacesHash`: old token refused, new token works, registry hash changed. |
| - - `TestLinkedAppRefusedOnAppRoutes`: walk `routeDecls`; every route whose pattern contains `{app}` and reaches `apiAccountAppSaying` refuses a linked app with 409 and the deck string, for GET and non-GET alike. The test fails on any such route that does not consult the guard. |
| + - `TestLinkedPolicyCoversEveryAppRoute`: walk `routeDecls`; every route whose pattern contains `{app}` (under `/api/cli/` and `/a/{sqid}/apps/{app}` alike) must have an entry in `linkedAppPolicy`'s table. The test fails on any unclassified route, independently of which helper the handler uses. |
| + - `TestLinkedAppRefusedOnAppRoutes`: for every `linkedRefuse` route, a request for a linked app (person token or browser session with the right role) gets 409 and the deck string, GET and non-GET alike, and the handler's side effect did not happen; for every `linkedAllow` route it does not get the linked refusal. |
| + - `TestPublishIsIdempotent`: publish `shop`, delete its forward row behind the console's back, publish `shop` again from the same link → 200, row restored; from another link → 409. |
| + - `TestUnlinkUsesRegistryRows`: a link forward row with no matching `apps` row is still deleted by unlink. |
| - `TestLinkCannotTouchAnotherLinksApps`: link L1 cannot unpublish an app published by L2 in the same account. |
| -- [ ] **Step 2:** `go test ./internal/console -run 'Publish|Unpublish|Unlink|Rotate|LinkedAppRefused|AnotherLinks'` — FAIL. |
| +- [ ] **Step 2:** `go test ./internal/console -run 'Publish|Unpublish|Unlink|Rotate|LinkedPolicy|LinkedAppRefused|AnotherLinks|Parity'` — FAIL. |
| - [ ] **Step 3:** Implement. |
| - [ ] **Step 4:** Same command — PASS. |
| - [ ] **Step 5:** Commit `console: link API, linked apps and the linked-app guard`. |
| @@ -206,7 +230,8 @@ Risk: authority, plan caps. Gets its own review. |
| - `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`. |
| - - The apps list marks linked apps with the deck's "served from <home name>" label. |
| + - 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. |
| |
| - [ ] **Step 1: Write failing tests:** `TestFleetTabShowsLinkedDeployments` (name, reachable state from a `SetLinkSeen` fixture, both published apps with URLs; empty state when none), `TestUnlinkFromConsole` (POST removes everything, as `TestUnlinkRemovesEverything`), `TestLinksListCLI`. |
| - [ ] **Step 2:** `go test ./internal/console -run 'LinkedDeployments|UnlinkFromConsole|LinksListCLI'` — FAIL. |
| @@ -218,24 +243,25 @@ Risk: authority, plan caps. Gets its own review. |
| |
| **Files:** |
| - Create: `internal/registry/homelink.go` (+ test), `internal/console/homelink.go`, `internal/console/linkclient.go`, `internal/console/homelink_test.go` |
| -- Modify: `internal/console/routedecls.go`, `internal/registry/registry.go` (migrate, Fingerprint), `internal/host/remote_dispatch.go`, `internal/console/view.go:522` |
| +- Modify: `internal/console/routedecls.go` and the parity table, `internal/registry/registry.go` (migrate, Fingerprint), `internal/registry/remote_dispatch.go`, `internal/console/view.go:522` |
| |
| **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`. |
| - `func (r *Registry) SetHomeLinkState(state string) error` |
| - - Table `home_link_apps(name TEXT PRIMARY KEY, home_host TEXT NOT NULL, created_at INTEGER)` — the published set; `name` is the serving-side app name. |
| - - `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() (map[string]string, error)` (name → home host), `PutHomeLinkApp(name, homeHost string) error`, `DeleteHomeLinkApp(name string) (bool, 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)`. |
| - 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; returns `{"verification_uri","user_code"}`; the home console polls the serving console in the background until approved, denied or expired, then `PutHomeLink`. |
| + - `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`. |
| - `GET /api/cli/link` → serving console, account, claimed box, the agent's tunnel `state`, and each published app with its URL. |
| - - `POST /api/cli/link/publications {"account":"<home acct>","app":"<home app>","name":"<public name, default app>"}` → checks the home app exists and is not static (static refused with the deck string, slice 2), resolves its home host (the app's primary ready route), calls serving `POST /api/link/publications`, then `PutHomeLinkApp`. |
| + - `POST /api/cli/link/publications {"account":"<home acct>","app":"<home app>","name":"<public name, default app>"}` → checks the home app exists, is an instance app (static refused with the deck string, slice 2) and has no password gate or admission hold (refused with deck strings; slice 1 does not carry those gates through a link), resolves its home host (the app's primary ready route), calls serving `POST /api/link/publications`, then `PutHomeLinkApp`. |
| - `DELETE /api/cli/link/publications/{name}` → `DeleteHomeLinkApp` **first**, then serving `DELETE /api/link/publications/{name}`. |
| - `POST /api/cli/link/rotate`, `DELETE /api/cli/link` → serving calls, then update or `DeleteHomeLink`. |
| - `type linkClient struct` in `linkclient.go` (pattern: `keymail.go:55-71`): base URL, bearer token, no redirects, 30 s timeout; methods `Start`, `Poll`, `Status`, `Publish`, `Unpublish`, `Rotate`, `Remove`. |
| |
| -- [ ] **Step 1: Write failing tests:** `TestHomeLinkClaimOnce` (two labels race, exactly one wins), `TestHomeStartPollStores` (fake serving console from `newConsoleFixture`; approve; home registry has the link with token, account, tunnel URL), `TestHomePublishRefusesStatic`, `TestHomeUnpublishDropsHomeSetFirst` (serving fake that records call order and asserts `HomeLinkApps()` no longer has the app when the DELETE arrives), `TestHomeLinkTokenNeverReturned` (no API response body contains the token). |
| +- [ ] **Step 1: Write failing tests:** `TestHomeLinkClaimOnce` (two labels race, exactly one wins), `TestHomeStartPollStores` (fake serving console from `newConsoleFixture`; approve; home registry has the link with token, account, tunnel URL), `TestHomeStartRefusesOldServingConsole` (a fake `/auth/cli/start` that ignores `purpose`), `TestHomePublishRefusesStatic`, `TestHomePublishRefusesGatedApp`, `TestHomeUnpublishDropsHomeSetFirst` (serving fake that records call order and asserts `HomeLinkApps()` no longer has the app when the DELETE arrives), `TestHomeLinkTokenNeverReturned` (no API response body contains the token). |
| - [ ] **Step 2:** `go test ./internal/registry ./internal/console -run 'HomeLink|HomeStart|HomePublish|HomeUnpublish'` — FAIL. |
| - [ ] **Step 3:** Implement. |
| - [ ] **Step 4:** PASS. |
| @@ -252,14 +278,22 @@ Risk: the anti-goal 1 guard. Gets its own review. |
| **Interfaces:** |
| - Consumes: Task 7's registry methods, `tunnelclient.Loop`, `tunnelclient.LinkAppHeader`, `(*Edge).OnReload` (`edge.go:1519`). |
| - Produces: |
| - - `func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, host string) bool` — serves the request to the exact registry host's upstream, through the activator when the route is activator-owned (the dispatch tail at `edge.go:2690-2696`), with `r.Host = host`. Returns false, writing nothing, when the host has no ready local upstream. It reaches no other edge surface (no ACME, purge, devbox, admin or health paths). |
| - - `type linkHandler struct { apps atomic.Pointer[map[string]string]; serve func(w, r, host string) bool }` with `ServeHTTP`: reads `LinkAppHeader`; missing, or naming no app in `apps` → 404 with the deck string; `serve` returns false → 502 with the deck's "not on this box" string. It never uses the request's Host. |
| - - `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()`; 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). |
| + - `func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, want LinkedTarget) bool` with `type LinkedTarget struct { Host, Account, App string }`. It: |
| + - looks up the **exact** upstream map entry for `want.Host` (never `lookupUpstream`/`lookupUpstreamPath`, `edge.go:1785, 1840`, which add wildcard and path-map targets); |
| + - admits it only when the entry's route has `Account == want.Account`, `App == want.App`, `Kind == "instance"`, `Status == "ready"`, and is a local socket or activator-owned backend; edge-owned static and status handlers (`edge.go:1193`) never qualify; |
| + - keeps these stages of the normal path, in this order: `admissionRefuses` (`edge.go:2134`, holds and imports), the password gate (`:2611`, defence in depth behind Task 7's publish refusal), `trackUpgrade` (`:2666`) for upgrades, then the activator (`act.ServeHTTP`) or the proxy, with `r.Host = want.Host`; |
| + - returns false, writing nothing, when the entry is missing or fails the admission check. It reaches no other edge surface (no ACME, purge, devbox, admin or health paths). |
| + - `type linkHandler struct { reg linkRegistry; serve func(w, r, LinkedTarget) bool; streams *linkStreams }` 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; `serve` returns false → 502 with the deck's "not on this box" string. It never uses the request's Host. |
| + - `type linkStreams struct` — tracks upgraded (WebSocket) connections per published name; on every reload the loop closes the streams of names no longer published, so open sockets end within one registry watch (2 s) at home, whatever the hub does. |
| + - `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()` (closing streams for names that 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). |
| |
| - [ ] **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`: unpublish → next request 404 from home even before the hub reloads. |
| + - `TestLinkUnpublishStopsServing`: with the home edge's reload paused, unpublish → the next request is 404 from home; an already-open WebSocket for that app is closed within one watch interval after reloads resume. |
| + - `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. |
| + - `TestLinkGatedAppRefused`: a published app that later gains a password gate gets the gate's answer, not the app. |
| - `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. |
| - [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/host ./internal/edge -run 'TestLink|TestFleetBoxNeverClaims|ServeLinked'` — FAIL. |
| @@ -275,10 +309,10 @@ Risk: the anti-goal 1 guard. Gets its own review. |
| |
| **Interfaces:** |
| - Consumes: Task 7's home API, Task 6's `GET /api/cli/links/{account}`. |
| -- Produces: `carlos link create --to <url> [--name <n>]` (prints the approval link and code, waits, prints the linked account), `carlos link status`, `carlos link publish <app> [--account <a>] [--name <n>]` (prints the public URL), `carlos link unpublish <name>`, `carlos link rotate`, `carlos link remove`. These talk to the home console (`--console` or `CARLOS_CONSOLE`, `resolveMode`). `carlos links ls --account <a>` talks to the serving console (default console). Registered with `raw(...)` like `fleetsCommand()`. |
| +- Produces: `carlos link create --to <url> [--name <n>]` (prints the approval link and code, waits, prints the linked account), `carlos link status`, `carlos link publish <app> [--account <a>] [--name <n>]` (prints the public URL), `carlos link unpublish <name>`, `carlos link rotate`, `carlos link remove`. These talk to the home console (`--console` or `CARLOS_CONSOLE`, `resolveMode`). `carlos links ls --account <a>` talks to the serving console (default console). Registered with `raw(...)` like `fleetsCommand()`. Headings for `carlos link` and `carlos links` on the CLI reference page (`internal/docsite/cli_test.go:80` checks them), and the command projection/parity docs regenerated with the repo's generator. |
| |
| - [ ] **Step 1: Write failing tests** with a fake console (`newFakeConsole` pattern): each command's request path, body and printed output (deck strings). |
| -- [ ] **Step 2:** `go test . -run 'TestLink'` — FAIL. |
| +- [ ] **Step 2:** `go test . ./internal/docsite -run 'TestLink|TestCLI'` — FAIL. |
| - [ ] **Step 3:** Implement. |
| - [ ] **Step 4:** PASS. Also the CLI registry golden test if `Golden` is set on the new nodes. |
| - [ ] **Step 5:** Commit `cli: carlos link and carlos links`. |
| @@ -288,7 +322,7 @@ Risk: the anti-goal 1 guard. Gets its own review. |
| **Files:** |
| - Create: `docs/site/linked-deployments.md` (user guide; humane-docs + copy review) |
| |
| -- [ ] **Step 1:** Write the guide: link, publish, unpublish, what Carloku can and cannot reach, offline behaviour. |
| +- [ ] **Step 1:** Write the guide: link, publish, unpublish, what Carloku can and cannot reach, offline behaviour, and recovery when a rotate's response is lost (the home side then holds a revoked token: `carlos link remove` at home and `carlos link create` again). |
| - [ ] **Step 2:** After merge and a dev release (Paul's go for the roll), link a single-box home deployment to the dev console and record on the branch discussion: |
| - the public URL serves the published app from outside the tailnet; |
| - an unpublished app on the same box is not reachable by any header or Host; |