console: link fixes: async first sync, links end with their account
Task 4 fix round 1 (Astra, Fable). The poll hands over the committed link credential at once; the first channel sync runs in the background and linkSyncLoop heals it, so a hung registry can no longer cost a burnt token. Both account-deletion transactions revoke the account's links and link tokens; a link principal needs a live account; the sync revokes a live link whose account is gone instead of erroring every tick. Non-deck strings move to named drafts in links_copy.go for the copy addendum, including a link-specific failed-approval line and check question. "purpose": null is a 400. Walk names are neutral and the settings revoke door's status is asserted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+326
−37
internal/console/authcli.go+28 −17internal/console/authstore.go+12 −0internal/console/jobs.go+1 −1internal/console/links_auth_test.go+176 −3internal/console/links_copy.go+28 −0internal/console/links_store.go+30 −12internal/console/links_sync.go+36 −2internal/console/ownership.go+5 −0internal/console/server.go+3 −0internal/console/store.go+5 −0internal/console/templates/cli_approve.html+2 −2
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index 3313ebc6b..085bbc850 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -777,9 +777,11 @@ func cleanLabel(in string) string { |
| // request without one is exactly the person's login it always was. |
| func (s *Server) handleCLIStart(w http.ResponseWriter, r *http.Request) { |
| var req struct { |
| - Label string `json:"label"` |
| - Purpose *string `json:"purpose"` |
| - Name string `json:"name"` |
| + Label string `json:"label"` |
| + // Raw, so presence is told from absence: "purpose": null is a |
| + // purpose that is not "link" (400), never a person's login. |
| + Purpose json.RawMessage `json:"purpose"` |
| + Name string `json:"name"` |
| } |
| if !readJSON(w, r, &req) { |
| return |
| @@ -787,20 +789,22 @@ func (s *Server) handleCLIStart(w http.ResponseWriter, r *http.Request) { |
| link := req.Purpose != nil |
| var linkName string |
| if link { |
| - if *req.Purpose != cliPurposeLink { |
| - jsonError(w, http.StatusBadRequest, `purpose must be "link" or absent`) |
| + var purpose string |
| + // null unmarshals to "", which is not "link". |
| + if err := json.Unmarshal(req.Purpose, &purpose); err != nil || purpose != cliPurposeLink { |
| + jsonError(w, http.StatusBadRequest, copyLinkStartBadPurpose) |
| return |
| } |
| // The name is shown on the approval page as the deployment's own |
| // claim, so it gets the label's printable-ASCII cleaning. |
| if linkName = cleanLabel(req.Name); linkName == "" { |
| - jsonError(w, http.StatusBadRequest, "a link request needs the deployment's name") |
| + jsonError(w, http.StatusBadRequest, copyLinkStartNoName) |
| return |
| } |
| // A link's answer carries the tunnel address the home dials; a |
| // console with no hub has none to give, so it takes no links. |
| if s.cfg.TunnelHost == "" { |
| - jsonError(w, http.StatusBadRequest, "this console does not take links: it has no tunnel host") |
| + jsonError(w, http.StatusBadRequest, copyLinkStartNoTunnel) |
| return |
| } |
| } |
| @@ -865,16 +869,12 @@ func (s *Server) handleCLIPoll(w http.ResponseWriter, r *http.Request) { |
| switch { |
| case res.Status != CLIAuthApproved: |
| case res.Purpose == cliPurposeLink: |
| - // The credential and its links row are committed. The channel is |
| - // derived from that row, so the token is delivered whether or not |
| - // this first sync lands: linkSyncLoop and the link doors' own sync |
| - // write it from the same row. Not cut short by a client that |
| - // stops waiting. |
| - ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Second) |
| - if err := s.syncLinkChannel(ctx, res.LinkID); err != nil { |
| - log.Printf("console: link %s: first channel sync: %v (linkSyncLoop retries)", res.LinkID, err) |
| - } |
| - cancel() |
| + // The credential and its links row are committed and the request |
| + // is burnt, so the token goes out now, never behind the registry. |
| + // The channel is derived from that row: the first sync runs in the |
| + // background, and linkSyncLoop (and the link doors' own sync) |
| + // write it from the same row if that one fails or hangs. |
| + s.firstLinkSync(res.LinkID) |
| out["token"] = res.Token |
| out["purpose"] = cliPurposeLink |
| out["link_id"] = res.LinkID |
| @@ -1017,6 +1017,14 @@ func (p cliPage) Lede() string { |
| return copyText("cli.lede", "label", label, "console", p.Brand) |
| } |
| +// LinkCheck is the link request's check question above the code. |
| +func (p cliPage) LinkCheck() string { return copyLinkCheck } |
| + |
| +// LinkOption is one account in the link picker. |
| +func (p cliPage) LinkOption(a Account) string { |
| + return linkCopy(copyLinkPickerOption, "name", a.Name, "sqid", a.Sqid) |
| +} |
| + |
| // Heading is the approval page's title: LD-C01 for a link request. |
| func (p cliPage) Heading() string { |
| if p.Request != nil && p.Request.IsLink() { |
| @@ -1292,6 +1300,9 @@ func (s *Server) handleCLIApprove(w http.ResponseWriter, r *http.Request) { |
| if err != nil { |
| s.cliBudgetSpend(s.cli.guessAddr, s.cli.guessIP, addr, ip, now) |
| p.Error = "That code has expired or was already used. Run carlos auth login again for a fresh one." |
| + if (lerr == nil && req.IsLink()) || (lerr != nil && s.store.cliAuthPurpose(code) == cliPurposeLink) { |
| + p.Error = copyLinkApproveExpired |
| + } |
| s.renderCLI(w, http.StatusOK, "cli_approve", p) |
| return |
| } |
diff --git a/internal/console/authstore.go b/internal/console/authstore.go| index c39471331..2b4ed103e 100644 |
| --- a/internal/console/authstore.go |
| +++ b/internal/console/authstore.go |
| @@ -542,6 +542,18 @@ FROM cli_auth_requests WHERE user_code = ?`, NormalizeUserCode(userCode)). |
| return &r, nil |
| } |
| +// cliAuthPurpose is a request's purpose by its user code, whatever its state |
| +// or expiry ("" when there is no row): what a failed decision needs to say |
| +// which flow to start again. |
| +func (s *Store) cliAuthPurpose(userCode string) string { |
| + var purpose string |
| + if err := s.db.QueryRow(`SELECT purpose FROM cli_auth_requests WHERE user_code = ?`, |
| + NormalizeUserCode(userCode)).Scan(&purpose); err != nil { |
| + return "" |
| + } |
| + return purpose |
| +} |
| + |
| // ApproveCLIAuth records that address approved the request. The token is NOT |
| // minted here: it is minted when the CLI collects it (PollCLIAuth), so no |
| // bearer credential is ever at rest waiting to be picked up. It approves a |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| index 6b3cf490a..fc26aea09 100644 |
| --- a/internal/console/jobs.go |
| +++ b/internal/console/jobs.go |
| @@ -325,7 +325,7 @@ var jobLabels = map[string]string{ |
| "StartEgressReport": "Outbound transfer report", |
| "FleetRelabel": "Fleet box placement", |
| "ManagedFleets": "Managed fleet provisioning", // COPY |
| - "LinkSync": "Linked deployment sync", |
| + "LinkSync": copyLinkJobLabel, |
| } |
| // The job status words (OPS-80 to OPS-82). |
diff --git a/internal/console/links_auth_test.go b/internal/console/links_auth_test.go| index 28eabd5ac..d05e140e6 100644 |
| --- a/internal/console/links_auth_test.go |
| +++ b/internal/console/links_auth_test.go |
| @@ -62,6 +62,7 @@ func linkCeremony(t *testing.T, fx *consoleFixture, browser *http.Client, name, |
| if str(t, poll, "status") != CLIAuthApproved || str(t, poll, "token") == "" { |
| t.Fatalf("link poll = %v, want approved with a token", poll) |
| } |
| + fx.srv.linkFirstSyncs.Wait() // the poll's background first sync |
| return poll |
| } |
| @@ -106,6 +107,7 @@ func TestLinkApprovalMintsLinkToken(t *testing.T) { |
| esc(copyLD04), |
| esc(linkCopy(copyLD05, "home", "shop-home")), |
| esc(copyLD08), |
| + esc(copyLinkCheck), |
| `name="account"`, |
| `value="` + fx.sqid + `"`, |
| } { |
| @@ -126,6 +128,7 @@ func TestLinkApprovalMintsLinkToken(t *testing.T) { |
| t.Fatalf("approved page lacks %q:\n%s", want, body) |
| } |
| _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": deviceCode}, "") |
| + fx.srv.linkFirstSyncs.Wait() // the poll's background first sync |
| token, linkID := str(t, poll, "token"), str(t, poll, "link_id") |
| if str(t, poll, "status") != CLIAuthApproved || token == "" { |
| t.Fatalf("poll = %v", poll) |
| @@ -229,7 +232,10 @@ func TestLinkTokenLifecycle(t *testing.T) { |
| } |
| // The settings page's revoke door, by the id, from the approver's |
| // session: the same refusal through HTTP. |
| - postGated(t, fx, browser, fx.ts.URL+"/auth/cli/tokens/revoke", url.Values{"id": {hash}, "csrf": {sessionToken(t, fx, browser)}}) |
| + status, loc, _ := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/tokens/revoke", url.Values{"id": {hash}, "csrf": {sessionToken(t, fx, browser)}}) |
| + if status != http.StatusSeeOther || loc != "/settings" { |
| + t.Fatalf("settings revoke of the link token = %d -> %q, want 303 -> /settings (refused with a flash)", status, loc) |
| + } |
| if _, ok := fx.st.CLIPrincipal(token, time.Now()); !ok { |
| t.Fatal("the settings revoke door ended the link token") |
| } |
| @@ -308,6 +314,7 @@ func TestPlainLoginUnchanged(t *testing.T) { |
| for _, body := range []map[string]any{ |
| {"purpose": "fleet"}, |
| {"purpose": ""}, |
| + {"purpose": nil}, |
| {"purpose": "link"}, |
| {"purpose": "link", "name": "\u202e"}, |
| } { |
| @@ -464,8 +471,8 @@ var linkWalkFill = map[string]string{ |
| "$": "", |
| "account": linkWalkSqid, |
| "sqid": linkWalkSqid, |
| - "app": "kass", |
| - "host": "web.go.tito.io", |
| + "app": "shop", |
| + "host": "shop.example.com", |
| "fleet": "edge", |
| "label": "box1", |
| "name": "hub", |
| @@ -615,6 +622,13 @@ func mintWalkLink(t *testing.T, st *Store) string { |
| if err != nil || acct == nil { |
| t.Fatal(acct, err) |
| } |
| + return mintWalkLinkIn(t, st, acct.ID) |
| +} |
| + |
| +// mintWalkLinkIn mints a link token for account id, approved by paul. |
| +func mintWalkLinkIn(t *testing.T, st *Store, id int64) string { |
| + t.Helper() |
| + acct := &Account{ID: id} |
| now := time.Now() |
| userCode, deviceCode, err := st.NewLinkAuth("walk-home", "operator@home", "192.0.2.9", now) |
| if err != nil { |
| @@ -757,3 +771,162 @@ func TestLinkMintRechecksTheRole(t *testing.T) { |
| t.Fatalf("second poll = %+v, want the request burnt", res) |
| } |
| } |
| + |
| +// blockingLinkRegistry holds its first PutLinkChannel until release closes, |
| +// then fails it; later calls pass through. |
| +type blockingLinkRegistry struct { |
| + consoleRegistry |
| + entered, release chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (b *blockingLinkRegistry) PutLinkChannel(c registry.LinkChannel) (bool, error) { |
| + first := false |
| + b.once.Do(func() { first = true }) |
| + if first { |
| + close(b.entered) |
| + <-b.release |
| + return false, errors.New("injected: the registry hung, then failed") |
| + } |
| + return b.consoleRegistry.PutLinkChannel(c) |
| +} |
| + |
| +// TestPollReturnsWhileRegistryBlocks: the poll hands over the committed |
| +// credential without waiting on the registry. A first sync that hangs costs |
| +// the channel a later linkSyncLoop pass, never the token. |
| +func TestPollReturnsWhileRegistryBlocks(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + real := linkRegistryOf(t, fx) |
| + blocking := &blockingLinkRegistry{consoleRegistry: real, entered: make(chan struct{}), release: make(chan struct{})} |
| + fx.srv.linkRegistry = func() (consoleRegistry, error) { return blocking, nil } |
| + released := false |
| + t.Cleanup(func() { |
| + if !released { |
| + close(blocking.release) |
| + } |
| + fx.srv.linkFirstSyncs.Wait() |
| + }) |
| + browser := signInPaul(t, fx) |
| + userCode, deviceCode := linkStart(t, fx, "shop-home") |
| + if code, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve", url.Values{ |
| + "code": {userCode}, "action": {"approve"}, "account": {fx.sqid}, "csrf": {sessionToken(t, fx, browser)}}); code != http.StatusOK { |
| + t.Fatalf("approve = %d:\n%s", code, body) |
| + } |
| + |
| + start := time.Now() |
| + _, poll := postJSON(t, fx.ts.URL+"/auth/cli/poll", map[string]string{"device_code": deviceCode}, "") |
| + took := time.Since(start) |
| + token, linkID := str(t, poll, "token"), str(t, poll, "link_id") |
| + if str(t, poll, "status") != CLIAuthApproved || token == "" || linkID == "" { |
| + t.Fatalf("poll = %v, want the token while the registry hangs", poll) |
| + } |
| + select { |
| + case <-blocking.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the first sync never reached the registry") |
| + } |
| + if took > 5*time.Second { |
| + t.Fatalf("the poll took %v, want it not to wait on the registry", took) |
| + } |
| + // The token works while the first sync is still stuck. |
| + if p, ok := fx.st.CLIPrincipal(token, time.Now()); !ok || p.LinkID != linkID { |
| + t.Fatalf("token = %+v %v", p, ok) |
| + } |
| + |
| + close(blocking.release) |
| + released = true |
| + fx.srv.linkFirstSyncs.Wait() |
| + auth, err := real.LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, has := auth[registry.LinkChannelName(linkID)]; has { |
| + t.Fatal("the failed first sync wrote the channel") |
| + } |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if auth, err := real.LinkChannelAuth(); err != nil || auth[registry.LinkChannelName(linkID)] != hashToken(token) { |
| + t.Fatalf("after the loop's pass LinkChannelAuth = %v %v, want the token's hash", auth, err) |
| + } |
| +} |
| + |
| +// TestAccountDeletionEndsItsLinks: a link does not outlive its account. Both |
| +// deletion transactions revoke the link and its credential, and the sync |
| +// pass revokes the channel; an account deleted any other way (or with no |
| +// row) is caught by the sync itself. |
| +func TestAccountDeletionEndsItsLinks(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + delete func(*Store, int64) error |
| + }{ |
| + {"DeleteAccount", func(st *Store, id int64) error { return st.DeleteAccount(id, time.Now()) }}, |
| + {"ReapAccount", func(st *Store, id int64) error { return st.ReapAccount(id, time.Now()) }}, |
| + {"marked-elsewhere", func(st *Store, id int64) error { |
| + _, err := st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, time.Now().Unix(), id) |
| + return err |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + id := testAccountID() |
| + if err := fx.st.CreateAccount(id, "shopacct", "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + token := mintWalkLinkIn(t, fx.st, id) |
| + p, _ := fx.st.CLIPrincipal(token, time.Now()) |
| + if err := fx.srv.syncLinkChannel(context.Background(), p.LinkID); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := linkRegistryOf(t, fx) |
| + if auth, _ := reg.LinkChannelAuth(); auth[registry.LinkChannelName(p.LinkID)] == "" { |
| + t.Fatal("the channel was not written before the deletion") |
| + } |
| + |
| + if err := tc.delete(fx.st, id); err != nil { |
| + t.Fatal(err) |
| + } |
| + if q, ok := fx.st.CLIPrincipal(token, time.Now()); ok { |
| + t.Fatalf("the link token resolves after its account was deleted: %+v", q) |
| + } |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + auth, err := reg.LinkChannelAuth() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, has := auth[registry.LinkChannelName(p.LinkID)]; has { |
| + t.Fatal("the channel is still active after the account was deleted and a sync pass ran") |
| + } |
| + l, err := fx.st.LinkByID(p.LinkID) |
| + if err != nil || l == nil || l.RevokedAt.IsZero() { |
| + t.Fatalf("link row after deletion = %+v %v, want revoked", l, err) |
| + } |
| + // Settled: nothing left for the loop, so it does not retry (or |
| + // fail) forever. |
| + if ids, err := fx.st.linksNeedingSync(); err != nil || len(ids) != 0 { |
| + t.Fatalf("linksNeedingSync = %v %v, want none", ids, err) |
| + } |
| + if err := fx.srv.linkSyncPass(context.Background()); err != nil { |
| + t.Fatalf("a second pass errs: %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestLinkApprovalExpiredSaysLinkCreate: a failed link approval points at |
| +// carlos link create, not at carlos auth login. |
| +func TestLinkApprovalExpiredSaysLinkCreate(t *testing.T) { |
| + fx := newLinkFixture(t, "tunnel.example.com") |
| + browser := signInPaul(t, fx) |
| + userCode, _ := linkStart(t, fx, "shop-home") |
| + if err := fx.st.DenyCLIAuth(userCode, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, body := postGated(t, fx, browser, fx.ts.URL+"/auth/cli/approve", url.Values{ |
| + "code": {userCode}, "action": {"approve"}, "account": {fx.sqid}, "csrf": {sessionToken(t, fx, browser)}}) |
| + if !strings.Contains(body, esc(copyLinkApproveExpired)) || strings.Contains(body, "carlos auth login") { |
| + t.Fatalf("failed link approval page, want the link wording:\n%s", body) |
| + } |
| +} |
diff --git a/internal/console/links_copy.go b/internal/console/links_copy.go| index 22ab81995..2e44c3f76 100644 |
| --- a/internal/console/links_copy.go |
| +++ b/internal/console/links_copy.go |
| @@ -35,3 +35,31 @@ func linkCopy(s string, kv ...string) string { |
| } |
| return strings.NewReplacer(pairs...).Replace(s) |
| } |
| + |
| +// Linked deployments' strings NOT in the approved deck: drafts awaiting the |
| +// copy-review addendum, one place so the review can read them together and |
| +// the approved text lands in one edit. |
| +const ( |
| + // The 400 from POST /auth/cli/start for a purpose other than "link" |
| + // (null included); read by the home CLI. |
| + copyLinkStartBadPurpose = `purpose must be "link" or absent` |
| + // The 400 from POST /auth/cli/start for a link request with no usable |
| + // name; read by the home CLI. |
| + copyLinkStartNoName = "a link request needs the deployment's name" |
| + // The 400 from POST /auth/cli/start for a link request on a console |
| + // with no tunnel host (CARLOS_TUNNEL_HOST); read by the home CLI. |
| + copyLinkStartNoTunnel = "this console does not take links: it has no tunnel host" |
| + // The LinkSync worker's label on the operator jobs pages. |
| + copyLinkJobLabel = "Linked deployment sync" |
| + // One account in the link approval page's picker: the account's name |
| + // and its sqid, so two accounts of the same name are told apart. |
| + copyLinkPickerOption = "{name} ({sqid})" |
| + // The check question above the code on the link approval page, in |
| + // place of the person login's "Does your agent or terminal show this |
| + // code?". |
| + copyLinkCheck = "Does the terminal where you ran carlos link create show this code?" |
| + // The error on the link approval page when approving fails because the |
| + // code expired or was already used, in place of the person login's |
| + // "Run carlos auth login again". |
| + copyLinkApproveExpired = "That code has expired or was already used. Run carlos link create again for a fresh one." |
| +) |
diff --git a/internal/console/links_store.go b/internal/console/links_store.go| index 76d61b2ef..c350cefca 100644 |
| --- a/internal/console/links_store.go |
| +++ b/internal/console/links_store.go |
| @@ -132,11 +132,25 @@ VALUES (?, ?, ?, ?, ?, ?, 1)`, id, accountID, name, approvedBy, now.Unix(), hash |
| return id, nil |
| } |
| +// revokeAccountLinksTx ends, inside an account deletion's transaction tx, |
| +// every live link of accountID and its credentials: the console rows only. |
| +// linkSyncLoop then revokes each channel through syncLinkChannel. |
| +func revokeAccountLinksTx(tx *sql.Tx, accountID int64, now time.Time) error { |
| + if _, err := tx.Exec(`UPDATE cli_tokens SET revoked_at = ? WHERE kind = ? AND account_id = ? AND revoked_at = 0`, |
| + now.Unix(), cliKindLink, accountID); err != nil { |
| + return err |
| + } |
| + _, err := tx.Exec(`UPDATE links SET revoked_at = ? WHERE account_id = ? AND revoked_at = 0`, now.Unix(), accountID) |
| + return err |
| +} |
| + |
| // linkState is a links row whole: the Link, the account's sqid ("" when the |
| -// account row is gone), and the channel fields syncLinkChannel reads. |
| +// account row is gone), whether the account is gone (no row, or deleted), |
| +// and the channel fields syncLinkChannel reads. |
| type linkState struct { |
| Link |
| sqid string |
| + accountGone bool |
| tokenHash string |
| generation int64 |
| syncedGeneration int64 |
| @@ -144,15 +158,16 @@ type linkState struct { |
| } |
| const linkStateCols = `l.id, l.account_id, l.name, l.created_by, l.created_at, l.revoked_at, |
| -COALESCE(a.sqid, ''), l.token_hash, l.generation, l.synced_generation, l.revoke_synced` |
| +COALESCE(a.sqid, ''), COALESCE(a.deleted_at, -1), l.token_hash, l.generation, l.synced_generation, l.revoke_synced` |
| func scanLinkState(scan func(...any) error) (*linkState, error) { |
| var l linkState |
| - var created, revoked, revokeSynced int64 |
| + var created, revoked, revokeSynced, deleted int64 |
| if err := scan(&l.ID, &l.AccountID, &l.Name, &l.CreatedBy, &created, &revoked, |
| - &l.sqid, &l.tokenHash, &l.generation, &l.syncedGeneration, &revokeSynced); err != nil { |
| + &l.sqid, &deleted, &l.tokenHash, &l.generation, &l.syncedGeneration, &revokeSynced); err != nil { |
| return nil, err |
| } |
| + l.accountGone = deleted != 0 |
| l.CreatedAt = time.Unix(created, 0).UTC() |
| if revoked != 0 { |
| l.RevokedAt = time.Unix(revoked, 0).UTC() |
| @@ -201,11 +216,13 @@ FROM links l LEFT JOIN accounts a ON a.id = l.account_id WHERE l.account_id = ? |
| } |
| // linksNeedingSync lists the links whose channel the hub registry has not |
| -// yet been told: a generation not yet written, or a revocation not yet |
| -// written. linkSyncLoop's work list. |
| +// yet been told: a generation not yet written, a revocation not yet |
| +// written, or a live link whose account is gone (no row, or deleted), which |
| +// syncLinkChannel revokes. linkSyncLoop's work list. |
| func (s *Store) linksNeedingSync() ([]string, error) { |
| - rows, err := s.db.Query(`SELECT id FROM links |
| -WHERE synced_generation < generation OR (revoked_at != 0 AND revoke_synced = 0) ORDER BY id`) |
| + rows, err := s.db.Query(`SELECT l.id FROM links l LEFT JOIN accounts a ON a.id = l.account_id |
| +WHERE l.synced_generation < l.generation OR (l.revoked_at != 0 AND l.revoke_synced = 0) |
| + OR (l.revoked_at = 0 AND COALESCE(a.deleted_at, -1) != 0) ORDER BY l.id`) |
| if err != nil { |
| return nil, err |
| } |
| @@ -314,12 +331,13 @@ func (s *Store) RevokeLink(id string, now time.Time) error { |
| // linkPrincipalLive reports whether a kind='link' credential (its hash, |
| // account and link ID) is the live credential of a live link: the links |
| -// row exists, is not revoked, belongs to the same account, and holds this |
| -// hash as its current one. |
| +// row exists, is not revoked, belongs to the same account, which is live |
| +// (deleted_at 0), and holds this hash as its current one. |
| func (s *Store) linkPrincipalLive(hash string, accountID int64, linkID string) bool { |
| var acct, revoked int64 |
| var current string |
| - err := s.db.QueryRow(`SELECT account_id, revoked_at, token_hash FROM links WHERE id = ?`, linkID). |
| - Scan(&acct, &revoked, ¤t) |
| + err := s.db.QueryRow(`SELECT l.account_id, l.revoked_at, l.token_hash |
| +FROM links l JOIN accounts a ON a.id = l.account_id |
| +WHERE l.id = ? AND a.deleted_at = 0`, linkID).Scan(&acct, &revoked, ¤t) |
| return err == nil && revoked == 0 && acct == accountID && current == hash |
| } |
diff --git a/internal/console/links_sync.go b/internal/console/links_sync.go| index 50f10ba62..ed82b417d 100644 |
| --- a/internal/console/links_sync.go |
| +++ b/internal/console/links_sync.go |
| @@ -22,6 +22,7 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| + "log" |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -64,8 +65,15 @@ func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error { |
| return fmt.Errorf("link %s: %w", linkID, ErrNoLink) |
| } |
| revoked := !row.RevokedAt.IsZero() |
| - if !revoked && row.sqid == "" { |
| - return fmt.Errorf("link %s: account %d has no row", linkID, row.AccountID) |
| + if !revoked && row.accountGone { |
| + // A live link of an account that is gone (deleted outside the |
| + // deletion transactions, which revoke links themselves, or no row |
| + // at all) is ended on the console first, then revoked below like |
| + // any other: never kept active, and never an error every tick. |
| + if err := s.store.RevokeLink(linkID, time.Now()); err != nil { |
| + return fmt.Errorf("link %s: revoke for a gone account: %w", linkID, err) |
| + } |
| + revoked = true |
| } |
| reg, err := s.linkReg() |
| if err != nil { |
| @@ -74,6 +82,11 @@ func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error { |
| if s.linkSyncHook != nil { |
| s.linkSyncHook(linkID, linkSyncBeforeWrite) |
| } |
| + // The registry calls take no context; a caller's deadline is honoured |
| + // up to here. |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| if revoked { |
| if _, err := reg.RevokeLinkChannel(linkID); err != nil { |
| return fmt.Errorf("link %s: revoke channel: %w", linkID, err) |
| @@ -100,6 +113,27 @@ func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error { |
| return nil |
| } |
| +// linkFirstSyncTimeout bounds the poll's background first sync up to its |
| +// registry write (syncLinkChannel checks it between steps). |
| +const linkFirstSyncTimeout = 10 * time.Second |
| + |
| +// firstLinkSync writes a just-minted link's channel in the background. The |
| +// poll that minted it has already committed the credential and must hand it |
| +// over without waiting on the registry: a slow or failing registry costs the |
| +// channel a later linkSyncLoop tick, never the token. Failures are logged. |
| +// linkFirstSyncs lets a test wait for it. |
| +func (s *Server) firstLinkSync(linkID string) { |
| + s.linkFirstSyncs.Add(1) |
| + go func() { |
| + defer s.linkFirstSyncs.Done() |
| + ctx, cancel := context.WithTimeout(context.Background(), linkFirstSyncTimeout) |
| + defer cancel() |
| + if err := s.syncLinkChannel(ctx, linkID); err != nil { |
| + log.Printf("console: link %s: first channel sync: %v (linkSyncLoop retries)", linkID, err) |
| + } |
| + }() |
| +} |
| + |
| // linkSyncLoop runs linkSyncPass now and then every linkSyncInterval until |
| // ctx is done: the delivery retry for a channel write that failed. It reads |
| // only the console database and writes only the registry. |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 01f442259..c45713dd5 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -845,6 +845,11 @@ func (s *Store) DeleteAccount(accountID int64, now time.Time) error { |
| if _, err := tx.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, now.Unix(), accountID); err != nil { |
| return err |
| } |
| + // The account's linked deployments end with it: their rows revoked here, |
| + // their channels revoked by the link sync (the one writer) after commit. |
| + if err := revokeAccountLinksTx(tx, accountID, now); err != nil { |
| + return err |
| + } |
| // Anyone whose landing spot was this account gets sent back to the picker |
| // rather than to a 404 they cannot explain. |
| if _, err := tx.Exec(`UPDATE users SET last_account = 0 WHERE last_account = ?`, accountID); err != nil { |
diff --git a/internal/console/server.go b/internal/console/server.go| index ea64ec73b..d53c48af4 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1400,6 +1400,9 @@ type Server struct { |
| // pauses a sync between its steps. |
| linkRegistry func() (consoleRegistry, error) |
| linkSyncHook func(linkID, stage string) |
| + // linkFirstSyncs counts the poll's background first syncs |
| + // (firstLinkSync), so a test can wait for them. |
| + linkFirstSyncs sync.WaitGroup |
| // delegationZone and lookupCNAME are the wildcard-capability door's two |
| // seams (apidomains.go). delegationZone is cfg.DelegationZone, shape- |
| // validated and normalized once here (normalizeDelegationZone); |
diff --git a/internal/console/store.go b/internal/console/store.go| index ec8c98044..8aa500108 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -1849,6 +1849,11 @@ func (s *Store) ReapAccount(accountID int64, now time.Time) error { |
| if _, err := tx.Exec(`UPDATE users SET last_account = 0 WHERE last_account = ?`, accountID); err != nil { |
| return err |
| } |
| + // The account's linked deployments end with it: their rows revoked here, |
| + // their channels revoked by the link sync (the one writer) after commit. |
| + if err := revokeAccountLinksTx(tx, accountID, now); err != nil { |
| + return err |
| + } |
| if _, err := tx.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ? AND deleted_at = 0`, |
| now.Unix(), accountID); err != nil { |
| return err |
diff --git a/internal/console/templates/cli_approve.html b/internal/console/templates/cli_approve.html| index cda992e01..4e40735f7 100644 |
| --- a/internal/console/templates/cli_approve.html |
| +++ b/internal/console/templates/cli_approve.html |
| @@ -4,7 +4,7 @@ |
| {{if and .Request .Request.IsLink}} |
| <p class="lede">{{.LinkLede}}</p> |
| <p class="tile-value"><code>{{.Request.UserCode}}</code></p> |
| -<p><strong>{{.CLIText "cli.check"}}</strong></p> |
| +<p><strong>{{.LinkCheck}}</strong></p> |
| <div class="banner"> |
| <p><strong>{{.Request.LinkName}}</strong>. |
| <span class="small">{{.LinkNote}}</span></p> |
| @@ -21,7 +21,7 @@ |
| <label for="link-account">{{.LinkPick}}</label> |
| <select id="link-account" name="account"> |
| {{- range .LinkAccounts}} |
| - <option value="{{.Sqid}}">{{.Name}} ({{.Sqid}})</option> |
| + <option value="{{.Sqid}}">{{$.LinkOption .}}</option> |
| {{- end}} |
| </select> |
| <button type="submit" name="action" value="approve">Approve</button> |