console: signed-in requests query under the request context
Batch 3 of the Go code-health plan (#1123). The console store has one SQLite connection, and request handlers queried without their request context, so an abandoned request kept its place in the queue. Now the session and CLI bearer gates, account and membership resolution, the app gate, account chrome and the app list, app page, instances list and /api/cli/apps (person and service credentials) pass r.Context() into the store (...Context forms beside old names for many-caller methods). The first-sign-in landing and mint stay detached on purpose. db-no-context in console: 629 to 591; record lowered. Reviewed by Astra (round 1, READY AFTER FIXES; P2 fixed in 9b8bd6be); scoped checks passed for that fix and for the CI fix cf78e933, which re-pins two record-write census sites (approved on #280). Outside the root census. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from console-request-ctx into main.
93 files changed,
+1,012
−387
.amadan/code-health.tsv+1 −39docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-R1-fix.md+20 −0docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-ci-fix.md+26 −0docs/superpowers/reviews/FINDINGS-console-request-ctx-R1.md+28 −0docs/superpowers/reviews/REVIEW-BRIEF-console-request-ctx.md+55 −0internal/console/account_test.go+5 −5internal/console/accountlinks.go+3 −3internal/console/accountplans.go+10 −2internal/console/accountreview.go+5 −4internal/console/accountreview_test.go+7 −7internal/console/apex.go+1 −1internal/console/apicli.go+10 −7internal/console/apicli_test.go+2 −2internal/console/apiinstancemove.go+1 −1internal/console/apiinstances.go+1 −1internal/console/apiinteractive.go+1 −1internal/console/apilinks.go+2 −2internal/console/apitemporary.go+2 −2internal/console/app_source.go+3 −3internal/console/appcopies.go+1 −1internal/console/applist.go+5 −5internal/console/applist_test.go+8 −7internal/console/appregionset.go+2 −2internal/console/appsettings.go+4 −4internal/console/appstarcleanup_test.go+5 −4internal/console/authcli.go+4 −4internal/console/authstore.go+17 −4internal/console/claim_invariant_probes_nonapp_test.go+3 −3internal/console/claim_invariant_probes_world_test.go+1 −1internal/console/deletion_test.go+1 −1internal/console/demo_claim_page.go+1 −1internal/console/demo_claim_target_test.go+2 −2internal/console/demo_domains.go+3 −3internal/console/domainattach.go+1 −1internal/console/domainbuy.go+1 −1internal/console/economicspass.go+1 −1internal/console/emailsignin.go+1 −1internal/console/emailsignin_test.go+2 −1internal/console/fleets.go+11 −3internal/console/fleetsecretskey.go+2 −1internal/console/gettingstarted.go+5 −4internal/console/gettingstarted_handlers_test.go+2 −1internal/console/gettingstarted_page_test.go+2 −2internal/console/gettingstarted_store.go+6 −5internal/console/gettingstarted_store_test.go+13 −12internal/console/invite_held_address_test.go+1 −1internal/console/lastseen.go+6 −3internal/console/lastseen_test.go+4 −3internal/console/link_sim_test.go+1 −1internal/console/linkedpolicy.go+5 −4internal/console/links_auth_test.go+2 −2internal/console/links_store.go+23 −10internal/console/links_sync.go+1 −1internal/console/materialize_test.go+5 −4internal/console/mobilenav.go+1 −1internal/console/opbilling_store_test.go+5 −4internal/console/opdashboard_test.go+1 −1internal/console/opstore.go+3 −2internal/console/opstore_test.go+8 −7internal/console/ownership.go+1 −1internal/console/pending.go+13 −11internal/console/pendinghandlers.go+5 −5internal/console/pipelinepage.go+2 −2internal/console/placement_census_test.go+1 −1internal/console/planexempt_test.go+8 −6internal/console/plangrace_store.go+15 −5internal/console/plangrace_test.go+6 −5internal/console/plangracepass.go+27 −18internal/console/planlapse.go+3 −3internal/console/planlapse_keep.go+4 −3internal/console/planlapse_store.go+8 −2internal/console/planlapse_test.go+1 −1internal/console/planlimits.go+12 −6internal/console/planmail.go+4 −4internal/console/planpdf_test.go+5 −4internal/console/regioncandidates.go+1 −1internal/console/regionconfig.go+5 −4internal/console/regionconfig_test.go+3 −2internal/console/regiondefault.go+1 −1internal/console/regionfacts.go+4 −3internal/console/regionfacts_test.go+1 −1internal/console/requestctx_test.go+316 −0internal/console/server.go+42 −40internal/console/signinmethods_store_test.go+4 −3internal/console/signinmethods_test.go+3 −2internal/console/store.go+80 −27internal/console/store_test.go+11 −10internal/console/svcprincipal.go+10 −3internal/console/svcroutes_test.go+7 −5internal/console/teamdoors.go+1 −1internal/console/tempstore.go+14 −7internal/provision/console_request_ctx_census_test.go+40 −0internal/provision/plan9_b8_census_test.go+1 −1
CI passed — run details
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 16ef2deaa..f7870e1d4 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -1342,14 +1342,11 @@ db-no-context internal/console (*Server).registeredPurchase console.sqlHandle.Qu |
| db-no-context internal/console (*Store).ARRSnapshots console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AcceptInvite console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).AccountAnyBySqid console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).AccountByID console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AccountBySqid console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AccountCLITokens console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AccountDays console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).AccountPlan console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AccountTiers console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).Accounts console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).AccountsFor console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AccountsPage console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AccountsPage console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AddAlertConnectorVerify console.sqlHandle.Begin 1 |
| @@ -1375,14 +1372,11 @@ db-no-context internal/console (*Store).AlertUnsubscribes console.sqlHandle.Quer |
| db-no-context internal/console (*Store).AppAccounts console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AppCount console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AppFlags console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).AppLife console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AppNameState console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).AppRegion console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).AppRows console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).ApproveCLIAuth console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).ApproveLinkAuth console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).AppsFor console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).AppsIn console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AppsIncludingTrashIn console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).AppsWithActionSince console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).BackfillOpsMemberships (*sql.Tx).Exec 2 |
| @@ -1407,12 +1401,6 @@ db-no-context internal/console (*Store).BillingRetiring console.sqlHandle.QueryR |
| db-no-context internal/console (*Store).BindClaimAppIdentity console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).BindClaimAppOperation console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).CLIAuthByUserCode console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).CLIPrincipal console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).CLIPrincipal console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).CLITokenAddress console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).CLITokenAddress console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).CLITokens console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).CapStates console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).ClaimAppID console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).ClearLapse console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).ClearLaunchSponsorship console.sqlHandle.Exec 1 |
| @@ -1421,8 +1409,6 @@ db-no-context internal/console (*Store).CloseBillingProblem console.sqlHandle.Ex |
| db-no-context internal/console (*Store).CloseBillingProblemsByReason console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).CommitAlertStep (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).CommitAlertStep console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).CompleteGettingStarted console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).CompleteGettingStarted console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).ConfirmAlertConnector console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).ConfirmAlertConnectorByToken (*sql.Tx).Exec 3 |
| db-no-context internal/console (*Store).ConfirmAlertConnectorByToken (*sql.Tx).QueryRow 1 |
| @@ -1468,7 +1454,6 @@ db-no-context internal/console (*Store).EnsureAccount (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).EnsureAccount console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).EnsureDefaultPlans console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).EnsureUser console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).Events console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).FinishOutbox (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).FinishOutbox (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).FinishOutbox console.sqlHandle.Begin 1 |
| @@ -1478,22 +1463,17 @@ db-no-context internal/console (*Store).FirstSnapshotDay console.sqlHandle.Query |
| db-no-context internal/console (*Store).FlagRestoreCheck (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).FlagRestoreCheck console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).FreshStepUp console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).GettingStartedMarks console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).GrantAt console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).GrantToken console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).HasApp console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).HasAppIn console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).HasOwners console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).HasPayment console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).HasTrashedAppIn console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).HoldConnectorOutbox console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).HoldEmailChallenge (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).HoldEmailChallenge console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).HoldMoveLog console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).InteractiveEndRecorded console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).IsOperator console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).LapseItems console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).LastAccount console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).LastIncarnation console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).LatestEURRates console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).LatestEURRates console.sqlHandle.QueryRow 1 |
| @@ -1517,7 +1497,6 @@ db-no-context internal/console (*Store).MarkOpApplied (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).MarkOpApplied console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).MarkPlanPublished console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).MarkRetirementRestorable console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).MemberConfirms console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).Members console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).MembershipTransition console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).MoveLogDue console.sqlHandle.Query 1 |
| @@ -1575,7 +1554,6 @@ db-no-context internal/console (*Store).ReapAccount (*sql.Tx).Exec 3 |
| db-no-context internal/console (*Store).ReapAccount (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).ReapAccount console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).RecentAlertIncidents console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).RecordCapNotice console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).RecordPayment (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).RecordPayment (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).RecordPayment console.sqlHandle.Begin 1 |
| @@ -1601,7 +1579,6 @@ db-no-context internal/console (*Store).RevokeLink (*sql.Tx).Exec 2 |
| db-no-context internal/console (*Store).RevokeLink (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).RevokeLink console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).RevokeServicePrincipal console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).Role console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).RotateLinkToken (*sql.Tx).Exec 3 |
| db-no-context internal/console (*Store).RotateLinkToken (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).RotateLinkToken console.sqlHandle.Begin 1 |
| @@ -1611,7 +1588,6 @@ db-no-context internal/console (*Store).SaveBillingSync console.sqlHandle.Begin |
| db-no-context internal/console (*Store).SealedAlertTargets console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).SeedOperatorAlertConnectors console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).ServicePrincipals console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).SessionAddress console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).SessionInfo console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).SessionMethodID console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).SetAccountDisabled console.sqlHandle.Exec 1 |
| @@ -1636,7 +1612,6 @@ db-no-context internal/console (*Store).SetDomainContact console.sqlHandle.Exec |
| db-no-context internal/console (*Store).SetGettingStartedMark (*sql.Tx).Exec 2 |
| db-no-context internal/console (*Store).SetGettingStartedMark console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).SetGrantToken console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).SetLastAccount console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).SetMigrationMarkedETag console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).SetMovePageAttempt console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).SetOperator console.sqlHandle.Exec 1 |
| @@ -1650,7 +1625,6 @@ db-no-context internal/console (*Store).Snooze console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).Snoozed console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).StallRestoreCheck (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).StallRestoreCheck console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).StarredLifetimes console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).StartLaunchSponsorship (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).StartLaunchSponsorship (*sql.Tx).Query 1 |
| db-no-context internal/console (*Store).StartLaunchSponsorship console.sqlHandle.Begin 1 |
| @@ -1665,20 +1639,15 @@ db-no-context internal/console (*Store).TakeEmailLink (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).TakeEmailLink (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).TakeEmailLink console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).TemporaryAppRows console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).TouchLastSeen console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).TransferOwnership (*sql.Tx).Exec 2 |
| db-no-context internal/console (*Store).TransferOwnership (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).TransferOwnership console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).TrashedAppsIn console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).UnsubscribeAlertConnector (*sql.Tx).Exec 3 |
| db-no-context internal/console (*Store).UnsubscribeAlertConnector (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).UnsubscribeAlertConnector console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).UseAlertToken console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).allocationsOrdered console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).appIdentity console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).appLinkID console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).appLives console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).appPlacementRow console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).backfillAppLifetimes (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).backfillAppLifetimes (*sql.Tx).Query 1 |
| db-no-context internal/console (*Store).backfillAppLifetimes console.sqlHandle.Begin 1 |
| @@ -1708,8 +1677,6 @@ db-no-context internal/console (*Store).claimRawNewAppToken console.sqlHandle.Ex |
| db-no-context internal/console (*Store).claimRawNewServicePrincipalScoped (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).claimRawNewServicePrincipalScoped (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).claimRawNewServicePrincipalScoped console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).claimRawPendingChangesFor (*sql.Tx).Query 1 |
| -db-no-context internal/console (*Store).claimRawPendingChangesFor console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).claimRawProposeChange (*sql.Tx).Exec 2 |
| db-no-context internal/console (*Store).claimRawProposeChange console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).claimRawPutLapseItem console.sqlHandle.Exec 1 |
| @@ -1730,11 +1697,7 @@ db-no-context internal/console (*Store).ed25519Key console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).ed25519Key console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).eurRatesFetchedAt console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).feed console.sqlHandle.Query 1 |
| -db-no-context internal/console (*Store).hasClaimedSource console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).insertEmailChallenge (*sql.Tx).Exec 1 |
| -db-no-context internal/console (*Store).linkPrincipalLive console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).linkRow console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).linkedAppHomes console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).linksNeedingSync console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).markLinkSynced console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).migrate console.sqlHandle.Exec 2 |
| @@ -1808,7 +1771,6 @@ db-no-context internal/console billingSetPlan (*sql.Tx).QueryRow 1 |
| db-no-context internal/console bumpDoorKeyRevision (*sql.Tx).Exec 1 |
| db-no-context internal/console bumpDoorKeyRevision (*sql.Tx).QueryRow 1 |
| db-no-context internal/console claimSQLCensus (*sql.DB).Query 4 |
| -db-no-context internal/console confirmsFor (*sql.Tx).Query 1 |
| db-no-context internal/console consumeSeatAuthorisationTx (*sql.Tx).Exec 1 |
| db-no-context internal/console deleteAlertConnectorTx (*sql.Tx).Exec 3 |
| db-no-context internal/console deleteBound (*sql.Tx).Exec 1 |
| @@ -2253,7 +2215,7 @@ file-lines . apimode.go - 4199 |
| file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals |
| file-lines internal/activator activator.go - 3778 |
| file-lines internal/activator activator_test.go - 5499 |
| -file-lines internal/console server.go - 4220 |
| +file-lines internal/console server.go - 4219 |
| file-lines internal/host agent.go - 3214 |
| file-lines internal/provision reconcile_test.go - 3094 |
| file-lines internal/registry registry_test.go - 3261 |
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-R1-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-R1-fix.md| new file mode 100644 |
| index 000000000..e753a5f52 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-R1-fix.md |
| @@ -0,0 +1,20 @@ |
| +# Scoped check: console-request-ctx, after round 1 (not a review round) |
| + |
| +Repo carlos/platform, branch `console-request-ctx` (tip in the prompt). |
| +Round 1 (`docs/superpowers/reviews/FINDINGS-console-request-ctx-R1.md`) |
| +ended READY AFTER FIXES with one P2 on the service-credential binding. |
| +The fix is commit 9b8bd6be. AGENTS.md rule 1: the review does not reopen, |
| +but the changed security gate is checked. Scope: `git show 9b8bd6be` only. |
| + |
| +Check: |
| +1. The P2: resolved, partly, not. |
| +2. serviceBinding now takes the request context (callers handleAPIApps, |
| + apiPrincipalAccountSaying, teamInScope): does every refusal it made |
| + before still refuse, a cancelled read included? Can any path now admit |
| + a service credential it refused before, or bind it to a different |
| + account? |
| +3. The new test cases: would they fail on the old code, any flake risk? |
| + |
| +Answer each: OK, or a finding with file:line, failure scenario and fix, |
| +marked P1 or P2. End with exactly one line: CHECK PASSED, or CHECK FAILED |
| +with the P1s. Do not edit files, spawn reviewers or run full suites. |
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-ci-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-ci-fix.md| new file mode 100644 |
| index 000000000..5066508aa |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-BRIEF-console-request-ctx-ci-fix.md |
| @@ -0,0 +1,26 @@ |
| +# Scoped check: console-request-ctx CI fix (not a review round) |
| + |
| +Repo carlos/platform, branch `console-request-ctx` (tip in the prompt). |
| +After round 1 (`docs/superpowers/reviews/FINDINGS-console-request-ctx-R1.md`) |
| +and its passed scoped check, CI found two real failures. The fix is commit |
| +cf78e933. AGENTS.md rule 1: the review does not reopen; the changed |
| +security behaviour and the record-write census are checked. |
| +Scope: `git show cf78e933` only. |
| + |
| +Check: |
| +1. currentAccount now runs both memberAccount reads under |
| + context.WithoutCancel(ctx), like the mint: the first-sign-in mint |
| + survives a cancelled request again. Any refusal or membership decision |
| + changed? Any way a cancelled or foreign request mints or lands in an |
| + account it should not? |
| +2. Record-write census (9B8): Server.attachDomainAs and |
| + Server.placeAppTarget re-pinned in a new layer |
| + (internal/provision/console_request_ctx_census_test.go) with class and |
| + kinds unchanged. As the census reviewer: is each write the same (same |
| + record, same writer, same guards in front, only a context added)? |
| + Approve or reject each, citing the lines you read. |
| +3. Tests unchanged in substance? |
| + |
| +Answer each: OK, or a finding with file:line, failure scenario and fix, |
| +marked P1 or P2. End with exactly one line: CHECK PASSED, or CHECK FAILED |
| +with the P1s. Do not edit files, spawn reviewers or run full suites. |
diff --git a/docs/superpowers/reviews/FINDINGS-console-request-ctx-R1.md b/docs/superpowers/reviews/FINDINGS-console-request-ctx-R1.md| new file mode 100644 |
| index 000000000..e12817520 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/FINDINGS-console-request-ctx-R1.md |
| @@ -0,0 +1,28 @@ |
| +Reviewed `7e50962dd68738bf9fc77cd49e6e73032ce0148b...b663ba9a646d924888b8ddd3f9e796c1fe419f46`, round 1. The requested tip adds only the brief to its named implementation commit. |
| + |
| +No P1 findings. One P2 finding. No P3 findings. |
| + |
| +**P2 — `/api/cli/apps` still waits without cancellation for service credentials.** |
| + |
| +Location: [apicli.go:765](/home/paulca/amadan.net/carlos/platform-console-request-ctx/internal/console/apicli.go:765), through `serviceBinding` at line 164. |
| + |
| +**Invariant:** Database calls on the selected request paths must leave the connection queue when the request is cancelled. |
| + |
| +The service-principal branch calls `serviceBinding(p)`, which calls `AccountByID`. That compatibility wrapper supplies `context.Background()`. If another request takes the sole connection after bearer resolution, this account lookup remains queued even after the client disconnects. The person-principal branch correctly uses the request context. |
| + |
| +**Fix:** Pass the request context through `serviceBinding` to `AccountByIDContext`, preserving its existing refusal behavior. Add a service-token case to [requestctx_test.go:136](/home/paulca/amadan.net/carlos/platform-console-request-ctx/internal/console/requestctx_test.go:136). Currently both new tests exercise `/api/cli/apps` only with a person’s token, so neither detects this omission. |
| + |
| +The remaining checks: |
| + |
| +- **Authorization:** I found no weakened gate. Session and bearer lookup errors refuse authentication. Membership, role and app checks preserve errors rather than treating them as permission. Linked-app and demo checks refuse failed reads. Cancellation of best-effort token timestamps does not bypass credential validation. |
| +- **Source guards:** Both bearer-resolver scans recognize the old and new names. The plan-exempt scan checks `EffectiveLimitsContext`, while accepting callers of either wrapper. The placement census follows the renamed implementation and still requires `effectivePlacement`. |
| +- **Detached callers and writes:** The five explicitly documented background calls remain outside this slice. First-account creation retains its cancellation-independent mint context. Last-seen cancellation follows the existing failed-write policy, including retaining the hourly reservation. A cancelled banner-notice write can delay notice recording, but cannot fabricate notice or authorize earlier enforcement. |
| +- **Transactions:** The changed pending-changes transaction performs reads only. It uses `BeginTx(ctx)`, context-aware queries, deferred rollback and a checked commit. I found no partial-write path. |
| +- **Tests:** By inspection, both new tests would detect the old implementation. The queue test synchronizes on `WaitCount` and handler completion; its ten-second timer bounds failure rather than scheduling cancellation. The context test checks later queries on the exercised paths, subject to the service-token omission above. |
| +- **Ratchet:** Independently confirmed console `db-no-context` drops from 629 to 591, with no raised allowance. The `server.go` reduction combines two fields into `bannerNotice`; it does not remove explanatory comments. |
| + |
| +Changed Go files pass formatting checks, and `git diff --check` is clean. Targeted tests stopped before compilation because Go attempted to update `go.mod` in the read-only workspace. No full suites ran, and no files were changed. |
| + |
| +This round has no P1, so the review closes under the stopping rule. Apply the P2 fix with the required scoped check of the changed binding gate. |
| + |
| +READY AFTER FIXES |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-console-request-ctx.md b/docs/superpowers/reviews/REVIEW-BRIEF-console-request-ctx.md| new file mode 100644 |
| index 000000000..619961520 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-console-request-ctx.md |
| @@ -0,0 +1,55 @@ |
| +# Review brief: branch console-request-ctx, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `console-request-ctx`, commit febbec4fc05e994d82051269511e64b74d99cb88. |
| +Under review: the diff `origin/main...febbec4fc05e994d82051269511e64b74d99cb88` (base 7e50962). |
| +Authorities: `docs/superpowers/plans/2026-11-16-go-code-health.md` (batch |
| +3, console request cancellation in place), AGENTS.md ("Writing Go here", |
| +"Stopping rules"). Outside the census (internal/console). |
| + |
| +You are the independent reviewer. The console store has one SQLite |
| +connection; this branch threads the request context through the store |
| +calls on the signed-in paths (session, CLI bearer gates, account and |
| +membership, app gate, account chrome, app list, app page, instances list, |
| +/api/cli/apps), adds `...Context` forms beside old names for many-caller |
| +methods, and lowers the ratchet record (console db-no-context 629 to 591). |
| + |
| +## What to check |
| + |
| +1. **Security gates unchanged.** The session, bearer (cliGateRefused, |
| + cliUser, CLIPrincipalContext, CLITokenAddressContext), membership, |
| + role, linked-app and demo guards must refuse exactly what they refused |
| + before. A cancelled or expired context must never turn a refusal into |
| + an admit, or an error into an empty result read as "no rows, allowed". |
| + Check every changed gate for that. |
| +2. **The source-scan security guards** (svcroutes_test.go bearer-resolver |
| + scans, the plan-exempt guard, the placement guard) now name the new |
| + `...Context` forms. Do they still catch every door that must not call a |
| + resolver? Is any door now able to call a new form the scans don't see? |
| +3. **Context-free callers left:** five outside the slice pass |
| + context.Background() with a comment; the first-sign-in account creation |
| + deliberately doesn't take the request's cancellation. Correct choices? |
| + Any write that should finish even if the client goes away but now gets |
| + cancelled half-way (transactions, the last-seen write, the plan banner |
| + notice write after render)? |
| +4. **Transactions:** BeginTx under the request context: a cancel mid-tx |
| + rolls back cleanly? Nothing commits partially? |
| +5. **Tests:** TestCancelledRequestLeavesTheConnectionQueue and |
| + TestSignedInPagesQueryUnderTheRequestContext: would each fail on the old |
| + code; flake risk on a loaded runner? |
| +6. **The ratchet record change:** lowered only, no raise; server.go line |
| + count handled honestly (a field, not comment deletion). |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe (any gate weakened), would not compile, a test fails, or |
| + it would not work. |
| +- **P2**: wrong or missing. Fixed without reopening this review (security |
| + behaviour changes in the fix still get a scoped check). |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix, and |
| +the invariant each breaks. End with exactly one verdict: READY, READY |
| +AFTER FIXES, or NOT READY. Do not edit files, spawn reviewers or run full |
| +suites. |
diff --git a/internal/console/account_test.go b/internal/console/account_test.go| index 2727cab6f..529c3785d 100644 |
| --- a/internal/console/account_test.go |
| +++ b/internal/console/account_test.go |
| @@ -211,20 +211,20 @@ func TestLastAccountRoundTrips(t *testing.T) { |
| t.Fatal(err) |
| } |
| // No history yet is 0, not an error. |
| - if got, err := st.LastAccount("paul@keymail.dev"); err != nil || got != 0 { |
| + if got, err := st.LastAccount(context.Background(), "paul@keymail.dev"); err != nil || got != 0 { |
| t.Fatalf("LastAccount before any visit = %d, %v; want 0, nil", got, err) |
| } |
| - if err := st.SetLastAccount("paul@keymail.dev", 42); err != nil { |
| + if err := st.SetLastAccount(context.Background(), "paul@keymail.dev", 42); err != nil { |
| t.Fatal(err) |
| } |
| - if got, _ := st.LastAccount("paul@keymail.dev"); got != 42 { |
| + if got, _ := st.LastAccount(context.Background(), "paul@keymail.dev"); got != 42 { |
| t.Errorf("LastAccount = %d, want 42", got) |
| } |
| // It works for an address that has never signed in (the invite case). |
| - if err := st.SetLastAccount("newcomer@keymail.dev", 42); err != nil { |
| + if err := st.SetLastAccount(context.Background(), "newcomer@keymail.dev", 42); err != nil { |
| t.Fatal(err) |
| } |
| - if got, _ := st.LastAccount("newcomer@keymail.dev"); got != 42 { |
| + if got, _ := st.LastAccount(context.Background(), "newcomer@keymail.dev"); got != 42 { |
| t.Errorf("LastAccount(newcomer) = %d, want 42", got) |
| } |
| } |
diff --git a/internal/console/accountlinks.go b/internal/console/accountlinks.go| index aa5051133..965ff2176 100644 |
| --- a/internal/console/accountlinks.go |
| +++ b/internal/console/accountlinks.go |
| @@ -231,8 +231,8 @@ type linkedAppView struct { |
| // linkedAppPage is the linked-app view of app in acct for its pages' nav, |
| // or nil for an ordinary app. A failed read is logged and costs only the |
| // linked view: every refused tab still refuses (linkedAppRefusal). |
| -func (s *Server) linkedAppPage(acct *Account, app string) *linkedAppView { |
| - linkID, err := s.store.appLinkID(acct.ID, app) |
| +func (s *Server) linkedAppPage(ctx context.Context, acct *Account, app string) *linkedAppView { |
| + linkID, err := s.store.appLinkIDContext(ctx, acct.ID, app) |
| if err != nil { |
| log.Printf("console: linked app page %s/%s: %v", acct.Sqid, app, err) |
| return nil |
| @@ -241,7 +241,7 @@ func (s *Server) linkedAppPage(acct *Account, app string) *linkedAppView { |
| return nil |
| } |
| v := &linkedAppView{LinkID: linkID, Home: linkID} |
| - if l, err := s.store.LinkByID(linkID); err != nil { |
| + if l, err := s.store.LinkByIDContext(ctx, linkID); err != nil { |
| log.Printf("console: linked app page %s/%s: link %s: %v", acct.Sqid, app, linkID, err) |
| } else if l != nil && l.Name != "" { |
| v.Home = l.Name |
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index fcf78c4b5..c490cff5e 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "database/sql" |
| "encoding/json" |
| "errors" |
| @@ -102,9 +103,16 @@ func scanAccountPlan(sc interface{ Scan(...any) error }) (*AccountPlanRow, error |
| return &r, nil |
| } |
| -// AccountPlan is the account's plan row, or nil when it has none. |
| +// AccountPlan is the account's plan row, or nil when it has none. It is |
| +// AccountPlanContext for callers with no request to follow. |
| func (s *Store) AccountPlan(accountID int64) (*AccountPlanRow, error) { |
| - r, err := scanAccountPlan(s.db.QueryRow(`SELECT `+accountPlanColumns+` |
| + return s.AccountPlanContext(context.Background(), accountID) |
| +} |
| + |
| +// AccountPlanContext is AccountPlan under the caller's context: the plan |
| +// banner on every account page reads it. |
| +func (s *Store) AccountPlanContext(ctx context.Context, accountID int64) (*AccountPlanRow, error) { |
| + r, err := scanAccountPlan(s.db.QueryRowContext(ctx, `SELECT `+accountPlanColumns+` |
| FROM account_plans p JOIN accounts a ON a.id = p.account_id WHERE p.account_id = ?`, accountID)) |
| if errors.Is(err, sql.ErrNoRows) { |
| return nil, nil |
diff --git a/internal/console/accountreview.go b/internal/console/accountreview.go| index 81af04eac..318a92e37 100644 |
| --- a/internal/console/accountreview.go |
| +++ b/internal/console/accountreview.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "net/http" |
| "sort" |
| "strconv" |
| @@ -29,7 +30,7 @@ func (a AccountReview) SummaryText() string { |
| // appAccountReview returns only candidates whose source account the viewer |
| // can access. A source with its own same-named app is a legitimate sibling, |
| // not evidence that the viewed app is half-migrated. |
| -func (s *Server) appAccountReview(address string, viewed *Account, app string) (AccountReview, bool, error) { |
| +func (s *Server) appAccountReview(ctx context.Context, address string, viewed *Account, app string) (AccountReview, bool, error) { |
| reg, err := openRegistry(s.cfg.Registry) |
| if err != nil { |
| return AccountReview{}, false, err |
| @@ -38,7 +39,7 @@ func (s *Server) appAccountReview(address string, viewed *Account, app string) ( |
| if err != nil { |
| return AccountReview{}, false, err |
| } |
| - accounts, err := s.store.AccountsFor(address) |
| + accounts, err := s.store.AccountsForContext(ctx, address) |
| if err != nil { |
| return AccountReview{}, false, err |
| } |
| @@ -62,12 +63,12 @@ func (s *Server) appAccountReview(address string, viewed *Account, app string) ( |
| hidden = true |
| continue |
| } |
| - has, err := s.store.HasAppIn(account.ID, app) |
| + has, err := s.store.HasAppInContext(ctx, account.ID, app) |
| if err != nil { |
| return AccountReview{}, false, err |
| } |
| if !has { |
| - has, err = s.store.HasTrashedAppIn(account.ID, app) |
| + has, err = s.store.HasTrashedAppInContext(ctx, account.ID, app) |
| if err != nil { |
| return AccountReview{}, false, err |
| } |
diff --git a/internal/console/accountreview_test.go b/internal/console/accountreview_test.go| index 74d80d6f2..e6d69d8d9 100644 |
| --- a/internal/console/accountreview_test.go |
| +++ b/internal/console/accountreview_test.go |
| @@ -30,7 +30,7 @@ func TestAccountReviewExcludesLegitimateSameNamedApp(t *testing.T) { |
| if err != nil || viewed == nil { |
| t.Fatal(err) |
| } |
| - review, all, err := fx.srv.appAccountReview("paul@keymail.dev", viewed, "kass") |
| + review, all, err := fx.srv.appAccountReview(context.Background(), "paul@keymail.dev", viewed, "kass") |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -63,14 +63,14 @@ func TestAccountReviewSiblingPreventsUnrelatedMove(t *testing.T) { |
| fx.addRoute(t, registry.Route{Host: "sibling.example", App: "kass", Account: "cdef", Kind: "instance"}) |
| fx.addRoute(t, registry.Route{Host: "candidate.example", App: "kass", Account: "cghi", Kind: "instance"}) |
| viewed, _ := fx.st.AccountBySqid("bab") |
| - review, all, err := fx.srv.appAccountReview("paul@keymail.dev", viewed, "kass") |
| + review, all, err := fx.srv.appAccountReview(context.Background(), "paul@keymail.dev", viewed, "kass") |
| if err != nil { |
| t.Fatal(err) |
| } |
| if review.Count != 1 || all { |
| t.Fatalf("review = %+v all=%v; sibling must prevent move authority", review, all) |
| } |
| - if _, agreed, err := fx.srv.routeAccountFor("paul@keymail.dev", viewed, "kass"); !errors.Is(err, errMoveTargetUnavailable) || agreed { |
| + if _, agreed, err := fx.srv.routeAccountFor(context.Background(), "paul@keymail.dev", viewed, "kass"); !errors.Is(err, errMoveTargetUnavailable) || agreed { |
| t.Fatalf("routeAccountFor agreed=%v err=%v; same-named sibling must hide the move target", agreed, err) |
| } |
| } |
| @@ -79,14 +79,14 @@ func TestAccountReviewHidesInaccessibleSource(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.addRoute(t, registry.Route{Host: "secret.example", App: "kass", Account: "unknown", Kind: "instance"}) |
| viewed, _ := fx.st.AccountBySqid("bab") |
| - review, all, err := fx.srv.appAccountReview("paul@keymail.dev", viewed, "kass") |
| + review, all, err := fx.srv.appAccountReview(context.Background(), "paul@keymail.dev", viewed, "kass") |
| if err != nil { |
| t.Fatal(err) |
| } |
| if review.Count != 0 || all { |
| t.Fatalf("inaccessible source disclosed: %+v all=%v", review, all) |
| } |
| - if _, agreed, err := fx.srv.routeAccountFor("paul@keymail.dev", viewed, "kass"); !errors.Is(err, errMoveTargetUnavailable) || agreed { |
| + if _, agreed, err := fx.srv.routeAccountFor(context.Background(), "paul@keymail.dev", viewed, "kass"); !errors.Is(err, errMoveTargetUnavailable) || agreed { |
| t.Fatalf("routeAccountFor agreed=%v err=%v; an inaccessible source must hide the move target", agreed, err) |
| } |
| } |
| @@ -105,14 +105,14 @@ func TestAccountReviewTreatsTrashedSameNamedAppAsSibling(t *testing.T) { |
| } |
| fx.addRoute(t, registry.Route{Host: "trashed-sibling.example", App: "kass", Account: "cdef", Kind: "instance"}) |
| viewed, _ := fx.st.AccountBySqid("bab") |
| - review, all, err := fx.srv.appAccountReview("paul@keymail.dev", viewed, "kass") |
| + review, all, err := fx.srv.appAccountReview(context.Background(), "paul@keymail.dev", viewed, "kass") |
| if err != nil { |
| t.Fatal(err) |
| } |
| if review.Count != 0 || all { |
| t.Fatalf("trashed sibling became a move candidate: %+v all=%v", review, all) |
| } |
| - if _, agreed, err := fx.srv.routeAccountFor("paul@keymail.dev", viewed, "kass"); !errors.Is(err, errMoveTargetUnavailable) || agreed { |
| + if _, agreed, err := fx.srv.routeAccountFor(context.Background(), "paul@keymail.dev", viewed, "kass"); !errors.Is(err, errMoveTargetUnavailable) || agreed { |
| t.Fatalf("routeAccountFor agreed=%v err=%v; trashed sibling must hide the move target", agreed, err) |
| } |
| } |
diff --git a/internal/console/apex.go b/internal/console/apex.go| index b32abfcf7..8e21836e1 100644 |
| --- a/internal/console/apex.go |
| +++ b/internal/console/apex.go |
| @@ -133,7 +133,7 @@ func (s *Server) hostHolder(ctx context.Context, acct *Account, host, own string |
| if err != nil { |
| return nil, &apexErr{err: err} |
| } |
| - trashed, err := s.store.TrashedAppsIn(acct.ID) |
| + trashed, err := s.store.TrashedAppsIn(ctx, acct.ID) |
| if err != nil { |
| return nil, &apexErr{err: err} |
| } |
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index aa367b4a3..1c5398f8a 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -101,7 +101,7 @@ func (s *Server) apiAccountAppSaying(w http.ResponseWriter, r *http.Request, has |
| return "", nil, "", false |
| } |
| if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| - if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + if ref := s.demoMutationRefusal(r.Context(), acct, app); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return "", nil, "", false |
| } |
| @@ -154,14 +154,17 @@ func auditActor(p Principal, acct *Account) string { |
| // Only a SERVICE principal has a binding here. A link principal is bound to |
| // an account too, but to the link doors alone: it is refused here by kind, |
| // so no service door can ever read it as a binding. |
| -func (s *Server) serviceBinding(p Principal) (*Account, bool) { |
| +// |
| +// The account read runs under ctx, the request's: a store error, a |
| +// cancelled request among them, is a refusal like any other. |
| +func (s *Server) serviceBinding(ctx context.Context, p Principal) (*Account, bool) { |
| if p.Kind != PrincipalService { |
| return nil, false |
| } |
| if p.AccountID == 0 || (p.Name == "" && p.App == "") { |
| return nil, false |
| } |
| - acct, err := s.store.AccountByID(p.AccountID) |
| + acct, err := s.store.AccountByIDContext(ctx, p.AccountID) |
| if err != nil { |
| log.Printf("console: api principal account %d: %v", p.AccountID, err) |
| return nil, false |
| @@ -266,7 +269,7 @@ func (s *Server) apiPrincipalAccountSaying(w http.ResponseWriter, r *http.Reques |
| var addr string |
| switch p.Kind { |
| case PrincipalService: |
| - acct, ok := s.serviceBinding(p) |
| + acct, ok := s.serviceBinding(r.Context(), p) |
| if !ok || seg != acct.Sqid { |
| http.NotFound(w, r) |
| return Principal{}, nil, false |
| @@ -762,12 +765,12 @@ func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) { |
| // an error — the credential's scope is simply empty — and above all |
| // it is not a fall-through to every account, which is the failure |
| // mode serviceBinding exists to refuse. |
| - if acct, ok := s.serviceBinding(p); ok { |
| + if acct, ok := s.serviceBinding(r.Context(), p); ok { |
| accts = []Account{*acct} |
| } |
| case PrincipalUser: |
| var err error |
| - accts, err = s.store.AccountsFor(p.Address) |
| + accts, err = s.store.AccountsForContext(r.Context(), p.Address) |
| if err != nil { |
| log.Printf("console: api apps for %s: %v", p.Address, err) |
| jsonError(w, http.StatusInternalServerError, "could not load accounts") |
| @@ -779,7 +782,7 @@ func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) { |
| } |
| out := make([]map[string]any, 0, len(accts)) |
| for _, a := range accts { |
| - apps, err := s.store.AppsIn(a.ID) |
| + apps, err := s.store.AppsInContext(r.Context(), a.ID) |
| if err != nil { |
| log.Printf("console: api apps in %s: %v", a.Sqid, err) |
| jsonError(w, http.StatusInternalServerError, "could not load apps") |
diff --git a/internal/console/apicli_test.go b/internal/console/apicli_test.go| index ced8f9f48..e3da6f3c4 100644 |
| --- a/internal/console/apicli_test.go |
| +++ b/internal/console/apicli_test.go |
| @@ -2190,7 +2190,7 @@ func TestAPITrashAndRestoreApp(t *testing.T) { |
| // One clock, and it is the MARKER's: the auto-purge pass measures the 30 |
| // days from there, so a row stamped with anything else would give the |
| // Trash page a "days remaining" nothing honours. |
| - trashed, err := fx.st.TrashedAppsIn(OpsAccountID) |
| + trashed, err := fx.st.TrashedAppsIn(context.Background(), OpsAccountID) |
| if err != nil || len(trashed) != 1 || trashed[0].App != "titogo" { |
| t.Fatalf("TrashedAppsIn = %+v %v, want exactly titogo", trashed, err) |
| } |
| @@ -2357,7 +2357,7 @@ func TestAPITrashUnconfirmedWindowIsRefused(t *testing.T) { |
| if want := old.Add(release.TrashCooloff); until.Sub(want) > time.Minute || want.Sub(until) > time.Minute { |
| t.Fatalf("restorable_until = %s, want the ORIGINAL marker's window ~%s", until, want) |
| } |
| - trashed, err := fx.st.TrashedAppsIn(OpsAccountID) |
| + trashed, err := fx.st.TrashedAppsIn(context.Background(), OpsAccountID) |
| if err != nil || len(trashed) != 1 { |
| t.Fatalf("TrashedAppsIn = %+v %v, want exactly titogo", trashed, err) |
| } |
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go| index 8850ee38c..48ebd5170 100644 |
| --- a/internal/console/apiinstancemove.go |
| +++ b/internal/console/apiinstancemove.go |
| @@ -555,7 +555,7 @@ func (s *Server) moveOperatorGate(w http.ResponseWriter, r *http.Request) (acct |
| // token, and whose. A service token, a member's token and an error reading |
| // the operator flag are all "no" (the error is logged). |
| func (s *Server) moveOperator(r *http.Request) (addr string, ok bool) { |
| - addr, ok = s.store.CLITokenAddress(bearer(r), time.Now()) |
| + addr, ok = s.store.CLITokenAddressContext(r.Context(), bearer(r), time.Now()) |
| if !ok { |
| return "", false |
| } |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 11acdc052..552fca003 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1938,7 +1938,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| raw = restoreRegion |
| } else if raw == "" && placed == "" && strings.TrimSpace(req.Role) == "" && |
| (provision.Record{Kind: strings.TrimSpace(req.Kind), Addrs: req.Addrs}).DerivesPaths() { |
| - appRegion, _, err := s.appRegion(acct.ID, app) |
| + appRegion, _, err := s.appRegion(r.Context(), acct.ID, app) |
| if err != nil { |
| log.Printf("console: api instances create %s/%s: read app region: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusBadGateway, msgAppRegionUnreadable) |
diff --git a/internal/console/apiinteractive.go b/internal/console/apiinteractive.go| index ded9c1446..91d01325f 100644 |
| --- a/internal/console/apiinteractive.go |
| +++ b/internal/console/apiinteractive.go |
| @@ -105,7 +105,7 @@ func (s *Server) handleAPIInteractive(w http.ResponseWriter, r *http.Request) { |
| s.journalUnplaced(r, p, sw.status) |
| return |
| } |
| - if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + if ref := s.demoMutationRefusal(r.Context(), acct, app); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| } |
diff --git a/internal/console/apilinks.go b/internal/console/apilinks.go| index d2996efce..0a11a8aaf 100644 |
| --- a/internal/console/apilinks.go |
| +++ b/internal/console/apilinks.go |
| @@ -53,7 +53,7 @@ func linkPrincipalFrom(ctx context.Context) (Principal, bool) { |
| func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc { |
| return func(w http.ResponseWriter, r *http.Request) { |
| tok := bearer(r) |
| - p, ok := s.store.CLIPrincipal(tok, time.Now()) |
| + p, ok := s.store.CLIPrincipalContext(r.Context(), tok, time.Now()) |
| if !ok || p.Kind != PrincipalLink || p.LinkID == "" { |
| // A revoked link's last credential reaches the unlink door and |
| // no other: its only power there is to run the revocation |
| @@ -73,7 +73,7 @@ func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc { |
| jsonError(w, http.StatusServiceUnavailable, copyLD13) |
| return |
| } |
| - if again, ok := s.store.CLIPrincipal(tok, time.Now()); !ok || again.Kind != PrincipalLink || again.LinkID != p.LinkID { |
| + if again, ok := s.store.CLIPrincipalContext(r.Context(), tok, time.Now()); !ok || again.Kind != PrincipalLink || again.LinkID != p.LinkID { |
| s.cliNotSignedIn(w) |
| return |
| } |
diff --git a/internal/console/apitemporary.go b/internal/console/apitemporary.go| index c7b5ee775..7bccb1544 100644 |
| --- a/internal/console/apitemporary.go |
| +++ b/internal/console/apitemporary.go |
| @@ -393,7 +393,7 @@ func (s *Server) handleAPIAppList(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - lives, err := s.store.AppLivesIn(acct.ID) |
| + lives, err := s.store.AppLivesIn(r.Context(), acct.ID) |
| if err != nil { |
| log.Printf("console: api list %s: %v", acct.Sqid, err) |
| jsonError(w, http.StatusInternalServerError, "could not load apps") |
| @@ -419,7 +419,7 @@ func (s *Server) handleAPIAppList(w http.ResponseWriter, r *http.Request) { |
| // SQLite and the one registry listing above. region_name is always |
| // sent by this console, "" when the placement could not be read, so |
| // a CLI can tell an unknown from an older console. |
| - f := s.regionFactsFor(acct, l.App, fleetFromRoutes(routes, acct.Sqid, l.App), routesOK) |
| + f := s.regionFactsFor(r.Context(), acct, l.App, fleetFromRoutes(routes, acct.Sqid, l.App), routesOK) |
| entry["region_name"] = f.Text() |
| if f.Known { |
| entry["region"] = f.Code() |
diff --git a/internal/console/app_source.go b/internal/console/app_source.go| index 994cb319a..b6e681ecc 100644 |
| --- a/internal/console/app_source.go |
| +++ b/internal/console/app_source.go |
| @@ -178,7 +178,7 @@ func (s *Server) sourceAdmission(next http.HandlerFunc, cli bool) http.HandlerFu |
| // gets the same 404 as a stranger, before any storage read. A |
| // link credential is no credential here: it falls through to |
| // the gate's 401, exactly as no bearer does. |
| - p, ok := s.store.CLIPrincipal(bearer(r), time.Now()) |
| + p, ok := s.store.CLIPrincipalContext(r.Context(), bearer(r), time.Now()) |
| if ok && p.Kind == PrincipalService { |
| http.NotFound(w, r) |
| return |
| @@ -284,8 +284,8 @@ func (s *Server) serveAppSource(w http.ResponseWriter, r *http.Request, actor st |
| _, _ = w.Write(b) |
| } |
| -func (s *Store) hasClaimedSource(accountID int64, app string) (bool, error) { |
| +func (s *Store) hasClaimedSource(ctx context.Context, accountID int64, app string) (bool, error) { |
| var exists bool |
| - err := s.db.QueryRow(`SELECT claimed_source!='' FROM apps WHERE account_id=? AND app=?`, accountID, app).Scan(&exists) |
| + err := s.db.QueryRowContext(ctx, `SELECT claimed_source!='' FROM apps WHERE account_id=? AND app=?`, accountID, app).Scan(&exists) |
| return exists, err |
| } |
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go| index 0e197cce8..89639f735 100644 |
| --- a/internal/console/appcopies.go |
| +++ b/internal/console/appcopies.go |
| @@ -177,7 +177,7 @@ func (s *Server) copiesRefusal(ctx context.Context, acct *Account, app string, n |
| return &doorRefusal{Status: http.StatusBadRequest, Msg: copiesBounds} |
| } |
| if n > 1 { |
| - if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + if ref := s.demoMutationRefusal(ctx, acct, app); ref != nil { |
| return ref |
| } |
| if s.cfg.Demo.Account != "" && acct.Sqid == s.cfg.Demo.Account { |
diff --git a/internal/console/applist.go b/internal/console/applist.go| index 5a87df44b..0d9c086fa 100644 |
| --- a/internal/console/applist.go |
| +++ b/internal/console/applist.go |
| @@ -71,8 +71,8 @@ ON CONFLICT (account_id, address, lifetime) DO NOTHING`, accountID, address, lif |
| // StarredLifetimes is the set of app lifetimes address has starred in the |
| // account. |
| -func (s *Store) StarredLifetimes(accountID int64, address string) (map[string]bool, error) { |
| - rows, err := s.db.Query(`SELECT lifetime FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address) |
| +func (s *Store) StarredLifetimes(ctx context.Context, accountID int64, address string) (map[string]bool, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT lifetime FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address) |
| if err != nil { |
| return nil, err |
| } |
| @@ -109,12 +109,12 @@ func partitionApps(rows []appRow) (starred, regular, temporary []appRow) { |
| // app's expiry, then fills the page's three lists from the rows q keeps. |
| // p.Apps stays every live app, so the page can tell "no apps" from "no |
| // matches". |
| -func (s *Server) fillAppLists(p *page, acct *Account, addr, q string) error { |
| - lives, err := s.store.AppLivesIn(acct.ID) |
| +func (s *Server) fillAppLists(ctx context.Context, p *page, acct *Account, addr, q string) error { |
| + lives, err := s.store.AppLivesIn(ctx, acct.ID) |
| if err != nil { |
| return err |
| } |
| - stars, err := s.store.StarredLifetimes(acct.ID, addr) |
| + stars, err := s.store.StarredLifetimes(ctx, acct.ID, addr) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/console/applist_test.go b/internal/console/applist_test.go| index dcb79cd1e..3caeb0deb 100644 |
| --- a/internal/console/applist_test.go |
| +++ b/internal/console/applist_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "github.com/carlosframework/platform/internal/release" |
| "net/http" |
| "net/url" |
| @@ -12,12 +13,12 @@ import ( |
| func starredOf(t *testing.T, fx *consoleFixture, address string) map[string]bool { |
| t.Helper() |
| - lifes, err := fx.st.StarredLifetimes(OpsAccountID, address) |
| + lifes, err := fx.st.StarredLifetimes(context.Background(), OpsAccountID, address) |
| if err != nil { |
| t.Fatal(err) |
| } |
| out := map[string]bool{} |
| - lives, err := fx.st.AppLivesIn(OpsAccountID) |
| + lives, err := fx.st.AppLivesIn(context.Background(), OpsAccountID) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -104,7 +105,7 @@ func TestAppStarGates(t *testing.T) { |
| t.Errorf("non-member star = %d %q, want a bare 404", status, body) |
| } |
| } |
| - if l, _ := fx.st.StarredLifetimes(OpsAccountID, "eve@keymail.dev"); len(l) != 0 { |
| + if l, _ := fx.st.StarredLifetimes(context.Background(), OpsAccountID, "eve@keymail.dev"); len(l) != 0 { |
| t.Fatalf("a non-member's star was written: %v", l) |
| } |
| // Signed out: sent to the front page, nothing written. |
| @@ -136,7 +137,7 @@ func TestAppStarFollowsTheAppLifetime(t *testing.T) { |
| if status, _ := star(t, fx, paul, csrf, "blog", "true"); status != http.StatusSeeOther { |
| t.Fatalf("star = %d", status) |
| } |
| - if l, _ := fx.st.StarredLifetimes(otherID, "paul@keymail.dev"); len(l) != 0 { |
| + if l, _ := fx.st.StarredLifetimes(context.Background(), otherID, "paul@keymail.dev"); len(l) != 0 { |
| t.Fatalf("a star in bab shows in another account: %v", l) |
| } |
| if err := fx.st.RenameAppIn(OpsAccountID, "blog", "blog-two"); err != nil { |
| @@ -218,7 +219,7 @@ func TestAccountHomePartitionsByViewer(t *testing.T) { |
| for _, a := range []string{"kass", "titogo", "tmp-a", "tmp-b"} { |
| p.Apps = append(p.Apps, appRow{App: a}) |
| } |
| - if err := fx.srv.fillAppLists(&p, acct, addr, q); err != nil { |
| + if err := fx.srv.fillAppLists(context.Background(), &p, acct, addr, q); err != nil { |
| t.Fatal(err) |
| } |
| return p |
| @@ -265,10 +266,10 @@ func TestAppStarsSurviveReopen(t *testing.T) { |
| t.Fatal(err) |
| } |
| defer st.Close() |
| - if l, err := st.StarredLifetimes(1, "paul@keymail.dev"); err != nil || !l["life-1"] || len(l) != 1 { |
| + if l, err := st.StarredLifetimes(context.Background(), 1, "paul@keymail.dev"); err != nil || !l["life-1"] || len(l) != 1 { |
| t.Fatalf("after reopen = %v %v", l, err) |
| } |
| - if l, _ := st.StarredLifetimes(2, "paul@keymail.dev"); len(l) != 0 { |
| + if l, _ := st.StarredLifetimes(context.Background(), 2, "paul@keymail.dev"); len(l) != 0 { |
| t.Fatalf("account 2 sees account 1's star: %v", l) |
| } |
| } |
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go| index 829a8a52e..c85a71329 100644 |
| --- a/internal/console/appregionset.go |
| +++ b/internal/console/appregionset.go |
| @@ -212,7 +212,7 @@ func (s *Server) handleAPIAppRegionGet(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusOK, appRegionView{App: app, Region: l.Code, Label: l.Text, Fleet: name}) |
| return |
| } |
| - region, source, err := s.appRegion(acct.ID, app) |
| + region, source, err := s.appRegion(r.Context(), acct.ID, app) |
| if err != nil { |
| log.Printf("console: app region %s/%s: read: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusBadGateway, msgAppRegionUnreadable) |
| @@ -261,7 +261,7 @@ func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| // region it read, or not at all. via is appended to the audit line ("cli" |
| // or "" for the browser). |
| func (s *Server) setAppRegion(ctx context.Context, acct *Account, app string, found AppIncarnation, raw, addr, via string) (appRegionView, *doorRefusal) { |
| - if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + if ref := s.demoMutationRefusal(ctx, acct, app); ref != nil { |
| return appRegionView{}, ref |
| } |
| // A born-HA app's region is its pool's region (G6 Task 4), decided from |
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go| index 5cce435fc..2ab87ddc5 100644 |
| --- a/internal/console/appsettings.go |
| +++ b/internal/console/appsettings.go |
| @@ -1106,7 +1106,7 @@ func (s *Server) appPolicyState(ctx context.Context, acct *Account, name string) |
| // behind, and the moved app, which no create clears for, would take up an |
| // earlier app's at the destination. "" means the move may go ahead. |
| func (s *Server) movePolicyRefusal(ctx context.Context, from, to *Account, app string) string { |
| - if has, err := s.store.hasClaimedSource(from.ID, app); err != nil { |
| + if has, err := s.store.hasClaimedSource(ctx, from.ID, app); err != nil { |
| return sourceUnavailable |
| } else if has { |
| return sourceMoveRefused |
| @@ -1720,7 +1720,7 @@ func (s *Server) handleAppMoveAccount(w http.ResponseWriter, r *http.Request) { |
| back("err", msg) |
| return |
| } |
| - target, agreed, err := s.routeAccountFor(addr, acct, app) |
| + target, agreed, err := s.routeAccountFor(r.Context(), addr, acct, app) |
| if errors.Is(err, errMoveTargetUnavailable) { |
| http.NotFound(w, r) |
| return |
| @@ -1845,8 +1845,8 @@ var errMoveTargetUnavailable = errors.New("move target unavailable to this viewe |
| // routeAccountFor recomputes the viewer-safe diagnostic at action time. It |
| // grants a target only when every relevant route points to one accessible |
| // account which does not already claim its own same-named app. |
| -func (s *Server) routeAccountFor(address string, source *Account, app string) (target string, agreed bool, err error) { |
| - review, all, err := s.appAccountReview(address, source, app) |
| +func (s *Server) routeAccountFor(ctx context.Context, address string, source *Account, app string) (target string, agreed bool, err error) { |
| + review, all, err := s.appAccountReview(ctx, address, source, app) |
| if err != nil { |
| return "", false, err |
| } |
diff --git a/internal/console/appstarcleanup_test.go b/internal/console/appstarcleanup_test.go| index 2b93267bb..332d01404 100644 |
| --- a/internal/console/appstarcleanup_test.go |
| +++ b/internal/console/appstarcleanup_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "testing" |
| "time" |
| ) |
| @@ -18,7 +19,7 @@ func TestAppStarsEndWithMembership(t *testing.T) { |
| if err := st.RemoveMember(id, "member@example.com"); err != nil { |
| t.Fatal(err) |
| } |
| - stars, err := st.StarredLifetimes(id, "member@example.com") |
| + stars, err := st.StarredLifetimes(context.Background(), id, "member@example.com") |
| if err != nil || len(stars) != 0 { |
| t.Fatalf("stars after removal: %v %v", stars, err) |
| } |
| @@ -41,7 +42,7 @@ func TestAppStarsEndWithAccount(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - stars, err := st.StarredLifetimes(id, "member@example.com") |
| + stars, err := st.StarredLifetimes(context.Background(), id, "member@example.com") |
| if err != nil || len(stars) != 0 { |
| t.Fatalf("reap=%v: stars after deletion: %v %v", reap, stars, err) |
| } |
| @@ -62,7 +63,7 @@ func TestAppStarsEndOnlyWhenAppPurged(t *testing.T) { |
| if err := st.PurgeAppRow(id, "demo"); err != nil { |
| t.Fatal(err) |
| } |
| - stars, err := st.StarredLifetimes(id, "member@example.com") |
| + stars, err := st.StarredLifetimes(context.Background(), id, "member@example.com") |
| if err != nil || len(stars) != 1 { |
| t.Fatal("live app lost star") |
| } |
| @@ -72,7 +73,7 @@ func TestAppStarsEndOnlyWhenAppPurged(t *testing.T) { |
| if err := st.PurgeAppRow(id, "demo"); err != nil { |
| t.Fatal(err) |
| } |
| - stars, err = st.StarredLifetimes(id, "member@example.com") |
| + stars, err = st.StarredLifetimes(context.Background(), id, "member@example.com") |
| if err != nil || len(stars) != 0 { |
| t.Fatalf("stars after purge: %v %v", stars, err) |
| } |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index 71c5fd752..fa87a39a8 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -500,7 +500,7 @@ func (s *Server) cliGateRefused(allow svcrole.Set, h http.HandlerFunc, refused f |
| r.Body = s.cliBodyWrap(r) |
| } |
| now := time.Now() |
| - p, ok := s.store.CLIPrincipal(bearer(r), now) |
| + p, ok := s.store.CLIPrincipalContext(r.Context(), bearer(r), now) |
| if !ok { |
| // The same 401, with the same body, cliUser has always given: |
| // an expired token, a revoked one and a fabricated one are not |
| @@ -514,7 +514,7 @@ func (s *Server) cliGateRefused(allow svcrole.Set, h http.HandlerFunc, refused f |
| // (their own gate) admit it. |
| switch p.Kind { |
| case PrincipalUser: |
| - s.noteSeen(p.Address, now) |
| + s.noteSeen(r.Context(), p.Address, now) |
| case PrincipalService: |
| default: |
| s.cliNotSignedIn(w) |
| @@ -729,12 +729,12 @@ func (s *Server) cliNotSignedIn(w http.ResponseWriter) { |
| // and a service credential are not distinguishable from outside. |
| func (s *Server) cliUser(w http.ResponseWriter, r *http.Request) (string, bool) { |
| now := time.Now() |
| - addr, ok := s.store.CLITokenAddress(bearer(r), now) |
| + addr, ok := s.store.CLITokenAddressContext(r.Context(), bearer(r), now) |
| if !ok { |
| s.cliNotSignedIn(w) |
| return "", false |
| } |
| - s.noteSeen(addr, now) |
| + s.noteSeen(r.Context(), addr, now) |
| return addr, true |
| } |
diff --git a/internal/console/authstore.go b/internal/console/authstore.go| index ed98e3ce3..893978003 100644 |
| --- a/internal/console/authstore.go |
| +++ b/internal/console/authstore.go |
| @@ -763,13 +763,19 @@ VALUES (?, ?, ?, '', ?, 0, ?, ?, ?, ?)`, |
| // is false for unknown, revoked and expired tokens. This is the whole |
| // authorization decision for every CLI-facing endpoint. |
| func (s *Store) CLITokenAddress(rawToken string, now time.Time) (string, bool) { |
| + return s.CLITokenAddressContext(context.Background(), rawToken, now) |
| +} |
| + |
| +// CLITokenAddressContext is CLITokenAddress under the caller's context: a |
| +// person's CLI doors resolve their bearer with it. |
| +func (s *Store) CLITokenAddressContext(ctx context.Context, rawToken string, now time.Time) (string, bool) { |
| if rawToken == "" { |
| return "", false |
| } |
| hash := hashToken(rawToken) |
| var storedHash, addr, kind string |
| var expires, revoked int64 |
| - err := s.db.QueryRow(`SELECT token_hash, address, kind, expires_at, revoked_at FROM cli_tokens WHERE token_hash = ?`, |
| + err := s.db.QueryRowContext(ctx, `SELECT token_hash, address, kind, expires_at, revoked_at FROM cli_tokens WHERE token_hash = ?`, |
| hash).Scan(&storedHash, &addr, &kind, &expires, &revoked) |
| if err != nil { |
| return "", false |
| @@ -794,7 +800,7 @@ func (s *Store) CLITokenAddress(rawToken string, now time.Time) (string, bool) { |
| } |
| // Best-effort: "last used" is for the owner's benefit on the tokens page, |
| // and a failed write must not fail the request it is annotating. |
| - s.db.Exec(`UPDATE cli_tokens SET last_used = ? WHERE token_hash = ?`, now.Unix(), hash) |
| + s.db.ExecContext(ctx, `UPDATE cli_tokens SET last_used = ? WHERE token_hash = ?`, now.Unix(), hash) |
| return addr, true |
| } |
| @@ -844,9 +850,16 @@ func scanCLITokenRows(rows *sql.Rows) ([]CLIToken, error) { |
| // |
| // A link credential is not listed: its address is the person who approved |
| // the link, but it does not speak as them, and it is managed (rotated, |
| -// unlinked) on the account, never revoked from a person's settings. |
| +// unlinked) on the account, never revoked from a person's settings. It is |
| +// CLITokensContext for callers with no request to follow. |
| func (s *Store) CLITokens(address string) ([]CLIToken, error) { |
| - rows, err := s.db.Query(`SELECT token_hash, address, label, remote_addr, kind, account_id, app, |
| + return s.CLITokensContext(context.Background(), address) |
| +} |
| + |
| +// CLITokensContext is CLITokens under the caller's context: the account |
| +// home's Getting started card reads it. |
| +func (s *Store) CLITokensContext(ctx context.Context, address string) ([]CLIToken, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT token_hash, address, label, remote_addr, kind, account_id, app, |
| role, name, created_at, expires_at, last_used, revoked_at, rotated_at, rungs, commands, scope |
| FROM cli_tokens WHERE address = ? AND revoked_at = 0 AND kind != ? ORDER BY created_at DESC, token_hash`, address, cliKindLink) |
| if err != nil { |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 60e2e4fba..4d6417813 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -547,7 +547,7 @@ var claimNonAppProbes = map[string]claimProbe{ |
| effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| // "/" is also where a signed-out request is bounced, so the proof is |
| // the session itself: it was live and is gone. |
| - if _, ok := cx.st.SessionAddress(cx.csrf, time.Now()); ok { |
| + if _, ok := cx.st.SessionAddress(context.Background(), cx.csrf, time.Now()); ok { |
| return "the session is still live after sign-out" |
| } |
| return "" |
| @@ -718,7 +718,7 @@ var claimNonAppProbes = map[string]claimProbe{ |
| if err != nil || l == nil { |
| return fmt.Sprintf("read kass: %v", err) |
| } |
| - stars, err := cx.st.StarredLifetimes(OpsAccountID, claimFxOwner) |
| + stars, err := cx.st.StarredLifetimes(context.Background(), OpsAccountID, claimFxOwner) |
| if err != nil { |
| return err.Error() |
| } |
| @@ -1564,7 +1564,7 @@ func claimGettingStartedProbe(action string, kv []string, mark gsMark, want bool |
| do: claimFormReply("/a/bab/getting-started/"+action, form...), |
| status: http.StatusSeeOther, loc: "/a/bab/", |
| effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| - marks, err := cx.st.GettingStartedMarks(OpsAccountID, claimFxOwner) |
| + marks, err := cx.st.GettingStartedMarks(context.Background(), OpsAccountID, claimFxOwner) |
| if err != nil { |
| return err.Error() |
| } |
diff --git a/internal/console/claim_invariant_probes_world_test.go b/internal/console/claim_invariant_probes_world_test.go| index 3ba051883..00d3fc5fd 100644 |
| --- a/internal/console/claim_invariant_probes_world_test.go |
| +++ b/internal/console/claim_invariant_probes_world_test.go |
| @@ -164,7 +164,7 @@ func (cx *claimCase) signedInAs(c *http.Client, address string) bool { |
| if raw == "" { |
| return false |
| } |
| - got, ok := cx.st.SessionAddress(raw, time.Now()) |
| + got, ok := cx.st.SessionAddress(context.Background(), raw, time.Now()) |
| return ok && got == address |
| } |
diff --git a/internal/console/deletion_test.go b/internal/console/deletion_test.go| index 3f4c043e3..eab2fb3aa 100644 |
| --- a/internal/console/deletion_test.go |
| +++ b/internal/console/deletion_test.go |
| @@ -245,7 +245,7 @@ func TestTrashPageSurvivesAnUnreadableMarker(t *testing.T) { |
| } |
| // The ROW's own date stands in, so the page still says when this will be |
| // destroyed rather than showing the zero time. |
| - rows, err := fx.st.TrashedAppsIn(OpsAccountID) |
| + rows, err := fx.st.TrashedAppsIn(context.Background(), OpsAccountID) |
| if err != nil || len(rows) != 1 { |
| t.Fatalf("TrashedAppsIn = %+v %v", rows, err) |
| } |
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go| index 6db225e31..e7d324d12 100644 |
| --- a/internal/console/demo_claim_page.go |
| +++ b/internal/console/demo_claim_page.go |
| @@ -217,7 +217,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) { |
| p.Copy["agentDetail"] = "Give your agent this prompt so it can help you sign in, fetch the source, and deploy changes to this app." |
| p.Copy["agentLine"] = fmt.Sprintf("Continue app %s in account %s (ID %s) on console %s. Follow https://carlosframework.com/start#after-you-keep-it to help me sign in, fetch its claimed source, then build and deploy my changes to that existing app.", p.App, acct.Name, acct.Sqid, s.cfg.Origin) |
| p.Copy["sourceNote"] = "Source was saved when you kept this app. Later deployments do not update it." |
| - if has, err := s.store.hasClaimedSource(acct.ID, p.App); err == nil && has { |
| + if has, err := s.store.hasClaimedSource(r.Context(), acct.ID, p.App); err == nil && has { |
| p.SourceSteps = claimSourceSteps(p.App, acct.Sqid, s.cfg.Origin) |
| } else { |
| p.Copy["sourceNote"] = "No saved source for this app." |
diff --git a/internal/console/demo_claim_target_test.go b/internal/console/demo_claim_target_test.go| index bccb0ae0e..8ec08e781 100644 |
| --- a/internal/console/demo_claim_target_test.go |
| +++ b/internal/console/demo_claim_target_test.go |
| @@ -65,7 +65,7 @@ func TestDemoClaimAccounts(t *testing.T) { |
| claimAccount(t, s, int64(501+i), f.Person, RoleMember) |
| } |
| if n > 0 { |
| - if err := s.store.SetLastAccount(f.Person, 501); err != nil { |
| + if err := s.store.SetLastAccount(context.Background(), f.Person, 501); err != nil { |
| t.Fatal(err) |
| } |
| } |
| @@ -257,7 +257,7 @@ func TestDemoClaimTargetIsolation(t *testing.T) { |
| } |
| }) |
| } |
| - if ref := s.demoMutationRefusal(a, op.Target.App); ref == nil || ref.Status != 409 { |
| + if ref := s.demoMutationRefusal(context.Background(), a, op.Target.App); ref == nil || ref.Status != 409 { |
| t.Fatalf("ordinary doors: %+v", ref) |
| } |
| if err := s.appMutation(withDemoClaimOperation(t.Context(), op.ID), a, op.Target.App, "claim-transfer", func(context.Context) error { return nil }); err != nil { |
diff --git a/internal/console/demo_domains.go b/internal/console/demo_domains.go| index 479e9bb97..188041c1e 100644 |
| --- a/internal/console/demo_domains.go |
| +++ b/internal/console/demo_domains.go |
| @@ -17,11 +17,11 @@ func (s *Server) demoDomainReserved(host string) bool { |
| return domain != "" && (host == domain || strings.HasSuffix(host, "."+domain)) |
| } |
| -func (s *Server) demoMutationRefusal(acct *Account, app string) *doorRefusal { |
| - if ref := s.demoClaimMutationRefusal(context.Background(), acct.ID, app); ref != nil { |
| +func (s *Server) demoMutationRefusal(ctx context.Context, acct *Account, app string) *doorRefusal { |
| + if ref := s.demoClaimMutationRefusal(ctx, acct.ID, app); ref != nil { |
| return ref |
| } |
| - life, err := s.store.AppLife(acct.ID, app) |
| + life, err := s.store.AppLifeContext(ctx, acct.ID, app) |
| if err != nil { |
| log.Printf("console: demo mutation %s/%s: app life: %v", acct.Sqid, app, err) |
| return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: demoCopy["DEMO-CHECK-FAILED"]} |
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go| index 3e0d88de8..00e125718 100644 |
| --- a/internal/console/domainattach.go |
| +++ b/internal/console/domainattach.go |
| @@ -134,7 +134,7 @@ func (s *Server) attachDomainAs(ctx context.Context, view *namespaceView, acct * |
| // Every attach, whichever door or pass asks (a purchase's completion |
| // names its app from the stored purchase): a linked app takes no custom |
| // domain (LD-C12). |
| - if ref := s.linkedRefusalFor(acct, app, linkedRefuseDomains); ref != nil { |
| + if ref := s.linkedRefusalFor(ctx, acct, app, linkedRefuseDomains); ref != nil { |
| return attachResult{}, ref |
| } |
| if msg, status := s.temporaryRefusal(acct, app, "attach a domain to it"); msg != "" { |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index c04f460a9..61e142e27 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -156,7 +156,7 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| // The app comes from the request body, so no route policy saw it: a |
| // linked app takes no custom domain (LD-C12), refused before any |
| // billing. |
| - if ref := s.linkedRefusalFor(acct, app, linkedRefuseDomains); ref != nil { |
| + if ref := s.linkedRefusalFor(ctx, acct, app, linkedRefuseDomains); ref != nil { |
| return nil, "", nil, ref |
| } |
| if err := c.Validate(); err != nil { |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index 8afa5f78f..9c248fee1 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -200,7 +200,7 @@ func (s *Server) censusRecords(ctx context.Context) ([]censusTenancy, error) { |
| if err != nil { |
| return nil, err |
| } |
| - gone, err := s.store.TrashedAppsIn(a.ID) |
| + gone, err := s.store.TrashedAppsIn(ctx, a.ID) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go| index d663c65ce..aa6d04f93 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -325,7 +325,7 @@ func (s *Server) completeSigninSession(w http.ResponseWriter, r *http.Request, p |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.") |
| return "", false |
| } |
| - s.noteSeen(person, now) |
| + s.noteSeen(r.Context(), person, now) |
| s.auditSignInRow(person, created) |
| s.clearCookie(w, authCookie) |
| s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds())) |
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go| index 22b8178bd..4f4cf34cf 100644 |
| --- a/internal/console/emailsignin_test.go |
| +++ b/internal/console/emailsignin_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -762,7 +763,7 @@ func signedOut(t *testing.T, fx *consoleFixture, c *http.Client) bool { |
| if raw == "" { |
| return true |
| } |
| - _, ok := fx.st.SessionAddress(raw, time.Now()) |
| + _, ok := fx.st.SessionAddress(context.Background(), raw, time.Now()) |
| return !ok |
| } |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index d2ecb3b58..aabe82b1d 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -733,8 +733,16 @@ func (s *Server) handleAPIFleetDrainBox(w http.ResponseWriter, r *http.Request) |
| // fleet/<f> route can outlive its app and name a born-HA app recreated |
| // under the same name; effectivePlacement answers "" for that row whatever |
| // its column or its routes say. |
| +// |
| +// appPlacement is appPlacementContext for callers with no request to |
| +// follow. |
| func (s *Server) appPlacement(reg consoleRegistry, acct *Account, app string) (string, error) { |
| - stored, haPool, err := s.store.appPlacementRow(acct.ID, app) |
| + return s.appPlacementContext(context.Background(), reg, acct, app) |
| +} |
| + |
| +// appPlacementContext is appPlacement with its store read under ctx. |
| +func (s *Server) appPlacementContext(ctx context.Context, reg consoleRegistry, acct *Account, app string) (string, error) { |
| + stored, haPool, err := s.store.appPlacementRow(ctx, acct.ID, app) |
| if err != nil { |
| return "", err |
| } |
| @@ -838,13 +846,13 @@ const placeInstancesFailed = "could not update this app's instances — try agai |
| // A console with no deployment bucket configured (cfg.Releases == nil) |
| // refuses the whole request: it has no records to stamp. |
| func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target string) (status int, errMsg string) { |
| - if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + if ref := s.demoMutationRefusal(ctx, acct, app); ref != nil { |
| return ref.Status, ref.Msg |
| } |
| // A linked app is served from its home deployment: nothing here places |
| // it (LD-C11). The fleet page's Place form names its app in the form, |
| // where no route policy sees it. |
| - if ref := s.linkedRefusalFor(acct, app, linkedRefuse); ref != nil { |
| + if ref := s.linkedRefusalFor(ctx, acct, app, linkedRefuse); ref != nil { |
| return ref.Status, ref.Msg |
| } |
| // A born-HA app's region is its pool's, so it is never placed (G6 Task |
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go| index 4ddd2806b..5adc5ccab 100644 |
| --- a/internal/console/fleetsecretskey.go |
| +++ b/internal/console/fleetsecretskey.go |
| @@ -378,7 +378,8 @@ func (s *Server) fleetPlacedAppsIn(acct *Account, fleet string, includeTrash boo |
| listed := false |
| var out []string |
| for _, app := range apps { |
| - stored, haPool, err := s.store.appPlacementRow(acct.ID, app) |
| + // fleetPlacedAppsIn's callers carry no context yet. |
| + stored, haPool, err := s.store.appPlacementRow(context.Background(), acct.ID, app) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/console/gettingstarted.go b/internal/console/gettingstarted.go| index 4ea3aa3fb..b2d8ccf61 100644 |
| --- a/internal/console/gettingstarted.go |
| +++ b/internal/console/gettingstarted.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "log" |
| "reflect" |
| "strings" |
| @@ -142,15 +143,15 @@ func buildGettingStarted(marks map[gsMark]bool, connected, anyLive bool, role st |
| // not the filtered lists. Only console-database reads: no bucket call. A |
| // failed read never fails the page: unread tokens leave step 1 open, |
| // unread marks show no card and no Show link. |
| -func (s *Server) fillGettingStarted(p *page, acct *Account, addr, role string, live map[string]bool) { |
| +func (s *Server) fillGettingStarted(ctx context.Context, p *page, acct *Account, addr, role string, live map[string]bool) { |
| now := time.Now() |
| connected := false |
| - if tokens, err := s.store.CLITokens(addr); err != nil { |
| + if tokens, err := s.store.CLITokensContext(ctx, addr); err != nil { |
| log.Printf("console: getting started tokens %s: %v", acct.Sqid, err) |
| } else { |
| connected = personConnected(tokens, now) |
| } |
| - marks, err := s.store.GettingStartedMarks(acct.ID, addr) |
| + marks, err := s.store.GettingStartedMarks(ctx, acct.ID, addr) |
| if err != nil { |
| log.Printf("console: getting started marks %s: %v", acct.Sqid, err) |
| return |
| @@ -167,7 +168,7 @@ func (s *Server) fillGettingStarted(p *page, acct *Account, addr, role string, l |
| // Conditional on the manual steps' marks still being there: a Show |
| // pressed since the read above wins (CompleteGettingStarted). Either |
| // way this response offers Show; the next one reads the live state. |
| - if _, err := s.store.CompleteGettingStarted(acct.ID, addr, now); err != nil { |
| + if _, err := s.store.CompleteGettingStarted(ctx, acct.ID, addr, now); err != nil { |
| log.Printf("console: getting started completed %s: %v", acct.Sqid, err) |
| } |
| p.ShowGettingStarted = true |
diff --git a/internal/console/gettingstarted_handlers_test.go b/internal/console/gettingstarted_handlers_test.go| index 1ce07addf..fbe6146c8 100644 |
| --- a/internal/console/gettingstarted_handlers_test.go |
| +++ b/internal/console/gettingstarted_handlers_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "net/http" |
| "net/url" |
| "testing" |
| @@ -9,7 +10,7 @@ import ( |
| func gsMarksOf(t *testing.T, fx *consoleFixture, address string) map[gsMark]bool { |
| t.Helper() |
| - got, err := fx.st.GettingStartedMarks(OpsAccountID, address) |
| + got, err := fx.st.GettingStartedMarks(context.Background(), OpsAccountID, address) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/gettingstarted_page_test.go b/internal/console/gettingstarted_page_test.go| index ee7ffc4a8..a9a99791f 100644 |
| --- a/internal/console/gettingstarted_page_test.go |
| +++ b/internal/console/gettingstarted_page_test.go |
| @@ -369,7 +369,7 @@ func TestGettingStartedSecretsNoLinkWithoutLiveApp(t *testing.T) { |
| for _, live := range []map[string]bool{{}, {"elsewhere": true}} { |
| var p page |
| p.Apps = apps |
| - fx.srv.fillGettingStarted(&p, acct, "paul@keymail.dev", RoleOwner, live) |
| + fx.srv.fillGettingStarted(context.Background(), &p, acct, "paul@keymail.dev", RoleOwner, live) |
| v := p.GettingStarted |
| if v == nil { |
| t.Fatalf("live %v: no card", live) |
| @@ -380,7 +380,7 @@ func TestGettingStartedSecretsNoLinkWithoutLiveApp(t *testing.T) { |
| } |
| var p page |
| p.Apps = apps |
| - fx.srv.fillGettingStarted(&p, acct, "paul@keymail.dev", RoleOwner, map[string]bool{"idle": true}) |
| + fx.srv.fillGettingStarted(context.Background(), &p, acct, "paul@keymail.dev", RoleOwner, map[string]bool{"idle": true}) |
| if want := appSettingsURL(fx.sqid, "idle", "environments"); p.GettingStarted == nil || p.GettingStarted.SecretsURL != want { |
| t.Errorf("live idle: view %+v, want secrets URL %q", p.GettingStarted, want) |
| } |
diff --git a/internal/console/gettingstarted_store.go b/internal/console/gettingstarted_store.go| index f7278bfa7..f41f7f4f5 100644 |
| --- a/internal/console/gettingstarted_store.go |
| +++ b/internal/console/gettingstarted_store.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "time" |
| ) |
| @@ -38,8 +39,8 @@ func (s *Store) migrateGettingStarted() error { |
| } |
| // GettingStartedMarks is the set of marks address has set in the account. |
| -func (s *Store) GettingStartedMarks(accountID int64, address string) (map[gsMark]bool, error) { |
| - rows, err := s.db.Query(`SELECT mark FROM getting_started_marks WHERE account_id = ? AND address = ?`, accountID, address) |
| +func (s *Store) GettingStartedMarks(ctx context.Context, accountID int64, address string) (map[gsMark]bool, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT mark FROM getting_started_marks WHERE account_id = ? AND address = ?`, accountID, address) |
| if err != nil { |
| return nil, err |
| } |
| @@ -90,8 +91,8 @@ ON CONFLICT (account_id, address, mark) DO NOTHING`, accountID, address, string( |
| // then undo a Show pressed since: the reset deleted those marks, so the |
| // write finds nothing to stand on. ok reports whether completed is stored |
| // (already present counts). |
| -func (s *Store) CompleteGettingStarted(accountID int64, address string, now time.Time) (ok bool, err error) { |
| - if _, err := s.db.Exec(`INSERT INTO getting_started_marks (account_id, address, mark, marked_at) |
| +func (s *Store) CompleteGettingStarted(ctx context.Context, accountID int64, address string, now time.Time) (ok bool, err error) { |
| + if _, err := s.db.ExecContext(ctx, `INSERT INTO getting_started_marks (account_id, address, mark, marked_at) |
| SELECT ?, ?, ?, ? |
| WHERE EXISTS (SELECT 1 FROM getting_started_marks WHERE account_id = ? AND address = ? AND mark IN (?, ?)) |
| AND EXISTS (SELECT 1 FROM getting_started_marks WHERE account_id = ? AND address = ? AND mark IN (?, ?)) |
| @@ -102,7 +103,7 @@ ON CONFLICT (account_id, address, mark) DO NOTHING`, |
| return false, err |
| } |
| var n int |
| - if err := s.db.QueryRow(`SELECT COUNT(*) FROM getting_started_marks WHERE account_id = ? AND address = ? AND mark = ?`, |
| + if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM getting_started_marks WHERE account_id = ? AND address = ? AND mark = ?`, |
| accountID, address, string(gsCompleted)).Scan(&n); err != nil { |
| return false, err |
| } |
diff --git a/internal/console/gettingstarted_store_test.go b/internal/console/gettingstarted_store_test.go| index 1403fcf7e..ab3c52c60 100644 |
| --- a/internal/console/gettingstarted_store_test.go |
| +++ b/internal/console/gettingstarted_store_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "reflect" |
| "testing" |
| "time" |
| @@ -15,7 +16,7 @@ func TestGettingStartedMarksRoundTrip(t *testing.T) { |
| if err := st.SetGettingStartedMark(1, "a@example.com", gsHidden, now); err != nil { |
| t.Fatal(err) |
| } |
| - got, err := st.GettingStartedMarks(1, "a@example.com") |
| + got, err := st.GettingStartedMarks(context.Background(), 1, "a@example.com") |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -34,7 +35,7 @@ func TestGettingStartedDoneReplacesSkip(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - got, err := st.GettingStartedMarks(1, addr) |
| + got, err := st.GettingStartedMarks(context.Background(), 1, addr) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -52,7 +53,7 @@ func TestGettingStartedReset(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - if ok, err := st.CompleteGettingStarted(1, "a@example.com", now); err != nil || !ok { |
| + if ok, err := st.CompleteGettingStarted(context.Background(), 1, "a@example.com", now); err != nil || !ok { |
| t.Fatalf("complete: %v %v", ok, err) |
| } |
| if err := st.SetGettingStartedMark(1, "b@example.com", gsHidden, now); err != nil { |
| @@ -61,11 +62,11 @@ func TestGettingStartedReset(t *testing.T) { |
| if err := st.ResetGettingStarted(1, "a@example.com"); err != nil { |
| t.Fatal(err) |
| } |
| - got, err := st.GettingStartedMarks(1, "a@example.com") |
| + got, err := st.GettingStartedMarks(context.Background(), 1, "a@example.com") |
| if err != nil || len(got) != 0 { |
| t.Fatalf("after reset: %v %v", got, err) |
| } |
| - if other, _ := st.GettingStartedMarks(1, "b@example.com"); !other[gsHidden] { |
| + if other, _ := st.GettingStartedMarks(context.Background(), 1, "b@example.com"); !other[gsHidden] { |
| t.Fatal("reset touched another person") |
| } |
| } |
| @@ -75,10 +76,10 @@ func TestGettingStartedMarksPerAccount(t *testing.T) { |
| if err := st.SetGettingStartedMark(1, "a@example.com", gsHidden, time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| - if got, _ := st.GettingStartedMarks(2, "a@example.com"); len(got) != 0 { |
| + if got, _ := st.GettingStartedMarks(context.Background(), 2, "a@example.com"); len(got) != 0 { |
| t.Fatalf("leaked to account 2: %v", got) |
| } |
| - if got, _ := st.GettingStartedMarks(1, "b@example.com"); len(got) != 0 { |
| + if got, _ := st.GettingStartedMarks(context.Background(), 1, "b@example.com"); len(got) != 0 { |
| t.Fatalf("leaked to another address: %v", got) |
| } |
| } |
| @@ -96,7 +97,7 @@ func TestGettingStartedCleanup(t *testing.T) { |
| if err := st.RemoveMember(id, "member@example.com"); err != nil { |
| t.Fatal(err) |
| } |
| - if got, err := st.GettingStartedMarks(id, "member@example.com"); err != nil || len(got) != 0 { |
| + if got, err := st.GettingStartedMarks(context.Background(), id, "member@example.com"); err != nil || len(got) != 0 { |
| t.Fatalf("after RemoveMember: %v %v", got, err) |
| } |
| for _, reap := range []bool{false, true} { |
| @@ -114,7 +115,7 @@ func TestGettingStartedCleanup(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if got, err := st.GettingStartedMarks(id, "member@example.com"); err != nil || len(got) != 0 { |
| + if got, err := st.GettingStartedMarks(context.Background(), id, "member@example.com"); err != nil || len(got) != 0 { |
| t.Fatalf("reap=%v: %v %v", reap, got, err) |
| } |
| } |
| @@ -128,11 +129,11 @@ func TestGettingStartedCompleteConditional(t *testing.T) { |
| const addr = "a@example.com" |
| complete := func(want bool) { |
| t.Helper() |
| - ok, err := st.CompleteGettingStarted(1, addr, now) |
| + ok, err := st.CompleteGettingStarted(context.Background(), 1, addr, now) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - got, _ := st.GettingStartedMarks(1, addr) |
| + got, _ := st.GettingStartedMarks(context.Background(), 1, addr) |
| if ok != want || got[gsCompleted] != want { |
| t.Fatalf("complete = %v, stored %v, want %v (marks %v)", ok, got[gsCompleted], want, got) |
| } |
| @@ -162,7 +163,7 @@ func TestGettingStartedCompleteConditional(t *testing.T) { |
| if err := st.SetGettingStartedMark(1, addr, gsCompleted, now); err == nil { |
| t.Fatal("SetGettingStartedMark wrote completed unconditionally") |
| } |
| - if got, _ := st.GettingStartedMarks(1, addr); got[gsCompleted] { |
| + if got, _ := st.GettingStartedMarks(context.Background(), 1, addr); got[gsCompleted] { |
| t.Fatal("refused completed was stored") |
| } |
| } |
diff --git a/internal/console/invite_held_address_test.go b/internal/console/invite_held_address_test.go| index 861d50936..d446c14b5 100644 |
| --- a/internal/console/invite_held_address_test.go |
| +++ b/internal/console/invite_held_address_test.go |
| @@ -162,7 +162,7 @@ func TestInviteHeldAddressEndToEnd(t *testing.T) { |
| } |
| wantInviteRole(t, fx.st, accountID, "person@example.test", RoleMember) |
| wantInviteRole(t, fx.st, accountID, "alias@example.test", "") |
| - if id, err := fx.st.LastAccount("person@example.test"); err != nil || id != accountID { |
| + if id, err := fx.st.LastAccount(context.Background(), "person@example.test"); err != nil || id != accountID { |
| t.Fatalf("LastAccount = %d, %v; want %d", id, err, accountID) |
| } |
| if status, _, _ := get(t, c, fx.ts.URL+"/a/cdef/"); status != http.StatusOK { |
diff --git a/internal/console/lastseen.go b/internal/console/lastseen.go| index 6cd4f40a1..226da04d7 100644 |
| --- a/internal/console/lastseen.go |
| +++ b/internal/console/lastseen.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "log" |
| "time" |
| ) |
| @@ -51,13 +52,15 @@ func (s *Server) reserveSeen(addr string, now time.Time) bool { |
| } |
| // noteSeen records that addr was seen at now, when its hour is not already |
| -// reserved. Called only after a gate has passed for addr as a person. |
| -func (s *Server) noteSeen(addr string, now time.Time) { |
| +// reserved. Called only after a gate has passed for addr as a person. The |
| +// write runs under the request's ctx: a request that has gone away does not |
| +// queue it. |
| +func (s *Server) noteSeen(ctx context.Context, addr string, now time.Time) { |
| if !s.reserveSeen(addr, now) { |
| return |
| } |
| s.lastSeenWrites.Add(1) |
| - if err := s.store.TouchLastSeen(addr, now); err != nil { |
| + if err := s.store.TouchLastSeen(ctx, addr, now); err != nil { |
| log.Printf("console: last seen %s: %v", addr, err) |
| } |
| } |
diff --git a/internal/console/lastseen_test.go b/internal/console/lastseen_test.go| index 62ef83b90..f4291b76b 100644 |
| --- a/internal/console/lastseen_test.go |
| +++ b/internal/console/lastseen_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "database/sql" |
| "errors" |
| "net/http" |
| @@ -130,7 +131,7 @@ func TestLastSeenReservationIsAtomic(t *testing.T) { |
| go func() { |
| defer wg.Done() |
| <-start |
| - fx.srv.noteSeen(lastSeenPaul, now) |
| + fx.srv.noteSeen(context.Background(), lastSeenPaul, now) |
| }() |
| } |
| close(start) |
| @@ -248,7 +249,7 @@ func TestLastSeenWithNoUserRowIsHarmless(t *testing.T) { |
| t.Fatal(err) |
| } |
| expireSeen(t, fx, lastSeenPaul, false) |
| - fx.srv.noteSeen(lastSeenPaul, time.Now()) |
| + fx.srv.noteSeen(context.Background(), lastSeenPaul, time.Now()) |
| if got := fx.srv.lastSeenWrites.Load() - base; got != 2 { |
| t.Fatalf("lastSeenWrites after a direct noteSeen past the hour = +%d, want +2", got) |
| } |
| @@ -273,7 +274,7 @@ func TestLastSeenFailedWriteKeepsTheHour(t *testing.T) { |
| BEGIN SELECT RAISE(ABORT, 'test: last_seen refused'); END;`); err != nil { |
| t.Fatal(err) |
| } |
| - if err := fx.st.TouchLastSeen(lastSeenPaul, time.Now()); err == nil { |
| + if err := fx.st.TouchLastSeen(context.Background(), lastSeenPaul, time.Now()); err == nil { |
| t.Fatal("TouchLastSeen succeeded past the refusing trigger; the test would not exercise a failed write") |
| } |
| before, _ := lastSeenOf(t, fx, lastSeenPaul) |
diff --git a/internal/console/link_sim_test.go b/internal/console/link_sim_test.go| index 6b52c65fd..221e762cf 100644 |
| --- a/internal/console/link_sim_test.go |
| +++ b/internal/console/link_sim_test.go |
| @@ -530,7 +530,7 @@ func (s *consoleSim) check() { |
| s.t.Fatal(err) |
| } |
| for i, l := range s.links { |
| - row, err := s.fx.st.linkRow(l.id) |
| + row, err := s.fx.st.linkRow(context.Background(), l.id) |
| if err != nil || row == nil { |
| s.t.Fatalf("L%d: links row %v %v", i, row, err) |
| } |
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go| index 396b04b11..4cd6a71d3 100644 |
| --- a/internal/console/linkedpolicy.go |
| +++ b/internal/console/linkedpolicy.go |
| @@ -14,6 +14,7 @@ package console |
| // a pattern the table does not know is refused (fail closed). |
| import ( |
| + "context" |
| "log" |
| "net/http" |
| ) |
| @@ -320,7 +321,7 @@ func (s *Server) refuseLinkedPage(w http.ResponseWriter, r *http.Request, acct * |
| // method, reads included. The policy is read first, so an allowed door |
| // costs no lookup. A store error refuses (503): the guard fails closed. |
| func (s *Server) linkedAppRefusal(r *http.Request, acct *Account, app string) *doorRefusal { |
| - return s.linkedRefusalFor(acct, app, linkedAppPolicy(r.Pattern)) |
| + return s.linkedRefusalFor(r.Context(), acct, app, linkedAppPolicy(r.Pattern)) |
| } |
| // linkedRefusalFor is linkedAppRefusal under policy pol rather than the |
| @@ -329,11 +330,11 @@ func (s *Server) linkedAppRefusal(r *http.Request, acct *Account, app string) *d |
| // (TestLinkedPolicyCoversBodyAppDoors lists those doors): a domain |
| // purchase and its completion's attach (linkedRefuseDomains), and a |
| // placement (linkedRefuse). |
| -func (s *Server) linkedRefusalFor(acct *Account, app string, pol linkedPolicy) *doorRefusal { |
| +func (s *Server) linkedRefusalFor(ctx context.Context, acct *Account, app string, pol linkedPolicy) *doorRefusal { |
| if pol == linkedAllow { |
| return nil |
| } |
| - linkID, err := s.store.appLinkID(acct.ID, app) |
| + linkID, err := s.store.appLinkIDContext(ctx, acct.ID, app) |
| if err != nil { |
| log.Printf("console: linked check %s/%s: %v", acct.Sqid, app, err) |
| return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copyLinkedCheckFailed} |
| @@ -345,7 +346,7 @@ func (s *Server) linkedRefusalFor(acct *Account, app string, pol linkedPolicy) * |
| return &doorRefusal{Status: http.StatusConflict, Msg: copyLD12} |
| } |
| home := linkID |
| - if l, err := s.store.LinkByID(linkID); err != nil { |
| + if l, err := s.store.LinkByIDContext(ctx, linkID); err != nil { |
| log.Printf("console: linked check %s/%s: link %s: %v", acct.Sqid, app, linkID, err) |
| } else if l != nil && l.Name != "" { |
| home = l.Name |
diff --git a/internal/console/links_auth_test.go b/internal/console/links_auth_test.go| index f3d1bc4c1..9220aa441 100644 |
| --- a/internal/console/links_auth_test.go |
| +++ b/internal/console/links_auth_test.go |
| @@ -427,7 +427,7 @@ func TestSyncCannotResurrect(t *testing.T) { |
| if tokenB, err = fx.st.RotateLinkToken(linkID, time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| - if l, _ := fx.st.linkRow(linkID); l == nil || l.generation != 2 { |
| + if l, _ := fx.st.linkRow(context.Background(), linkID); l == nil || l.generation != 2 { |
| t.Fatalf("after rotate the row is %+v, want generation 2", l) |
| } |
| } |
| @@ -829,7 +829,7 @@ func TestLinkDoorsRefuseEveryOtherBearer(t *testing.T) { |
| } |
| } |
| // None of them changed anything a link door would. |
| - if apps, err := fx.st.AppLivesIn(acct.ID); err != nil { |
| + if apps, err := fx.st.AppLivesIn(context.Background(), acct.ID); err != nil { |
| t.Fatal(err) |
| } else { |
| for _, a := range apps { |
diff --git a/internal/console/links_store.go b/internal/console/links_store.go| index eb19770aa..eb121b6d2 100644 |
| --- a/internal/console/links_store.go |
| +++ b/internal/console/links_store.go |
| @@ -198,8 +198,8 @@ func scanLinkState(scan func(...any) error) (*linkState, error) { |
| } |
| // linkRow reads one link's whole row; nil, nil when there is none. |
| -func (s *Store) linkRow(id string) (*linkState, error) { |
| - l, err := scanLinkState(s.db.QueryRow(`SELECT `+linkStateCols+` |
| +func (s *Store) linkRow(ctx context.Context, id string) (*linkState, error) { |
| + l, err := scanLinkState(s.db.QueryRowContext(ctx, `SELECT `+linkStateCols+` |
| FROM links l LEFT JOIN accounts a ON a.id = l.account_id WHERE l.id = ?`, id).Scan) |
| if errors.Is(err, sql.ErrNoRows) { |
| return nil, nil |
| @@ -207,9 +207,15 @@ FROM links l LEFT JOIN accounts a ON a.id = l.account_id WHERE l.id = ?`, id).Sc |
| return l, err |
| } |
| -// LinkByID returns one link, revoked or not; nil, nil when there is none. |
| +// LinkByID returns one link, revoked or not; nil, nil when there is none. It |
| +// is LinkByIDContext for callers with no request to follow. |
| func (s *Store) LinkByID(id string) (*Link, error) { |
| - l, err := s.linkRow(id) |
| + return s.LinkByIDContext(context.Background(), id) |
| +} |
| + |
| +// LinkByIDContext is LinkByID under the caller's context. |
| +func (s *Store) LinkByIDContext(ctx context.Context, id string) (*Link, error) { |
| + l, err := s.linkRow(ctx, id) |
| if l == nil || err != nil { |
| return nil, err |
| } |
| @@ -354,10 +360,10 @@ func (s *Store) RevokeLink(id string, now time.Time) error { |
| // account and link ID) is the live credential of a live link: the links |
| // 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 { |
| +func (s *Store) linkPrincipalLive(ctx context.Context, hash string, accountID int64, linkID string) bool { |
| var acct, revoked int64 |
| var current string |
| - err := s.db.QueryRow(`SELECT l.account_id, l.revoked_at, l.token_hash |
| + err := s.db.QueryRowContext(ctx, `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 |
| @@ -385,10 +391,17 @@ func (s *Store) CreateLinkedApp(accountID int64, app, createdBy, linkID string, |
| } |
| // appLinkID reads the link app belongs to in accountID: "" for an ordinary |
| -// app and for no row at all. |
| +// app and for no row at all. It is appLinkIDContext for callers with no |
| +// request to follow. |
| func (s *Store) appLinkID(accountID int64, app string) (string, error) { |
| + return s.appLinkIDContext(context.Background(), accountID, app) |
| +} |
| + |
| +// appLinkIDContext is appLinkID under the caller's context: the linked-app |
| +// guard on every app door asks it. |
| +func (s *Store) appLinkIDContext(ctx context.Context, accountID int64, app string) (string, error) { |
| var id string |
| - err := s.db.QueryRow(`SELECT linked_link_id FROM apps WHERE account_id = ? AND app = ?`, accountID, app).Scan(&id) |
| + err := s.db.QueryRowContext(ctx, `SELECT linked_link_id FROM apps WHERE account_id = ? AND app = ?`, accountID, app).Scan(&id) |
| if errors.Is(err, sql.ErrNoRows) { |
| return "", nil |
| } |
| @@ -526,8 +539,8 @@ WHERE t.token_hash = ? AND t.kind = ? AND l.token_hash = t.token_hash AND l.acco |
| // linkedAppHomes maps each linked app of accountID to the name of the |
| // deployment it is served from: what the account's app list labels it |
| // with (LD-C31) and what the Fleet tab leaves out of its platform count. |
| -func (s *Store) linkedAppHomes(accountID int64) (map[string]string, error) { |
| - rows, err := s.db.Query(`SELECT p.app, l.name FROM apps p JOIN links l ON l.id = p.linked_link_id |
| +func (s *Store) linkedAppHomes(ctx context.Context, accountID int64) (map[string]string, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT p.app, l.name FROM apps p JOIN links l ON l.id = p.linked_link_id |
| WHERE p.account_id = ? AND p.linked_link_id != ''`, accountID) |
| if err != nil { |
| return nil, err |
diff --git a/internal/console/links_sync.go b/internal/console/links_sync.go| index 9cb339b1f..f84d9c541 100644 |
| --- a/internal/console/links_sync.go |
| +++ b/internal/console/links_sync.go |
| @@ -57,7 +57,7 @@ func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error { |
| if s.linkSyncHook != nil { |
| s.linkSyncHook(linkID, linkSyncBeforeRead) |
| } |
| - row, err := s.store.linkRow(linkID) |
| + row, err := s.store.linkRow(ctx, linkID) |
| if err != nil { |
| return fmt.Errorf("link %s: read: %w", linkID, err) |
| } |
diff --git a/internal/console/materialize_test.go b/internal/console/materialize_test.go| index 223290ddb..09dadf8e7 100644 |
| --- a/internal/console/materialize_test.go |
| +++ b/internal/console/materialize_test.go |
| @@ -2,6 +2,7 @@ package console |
| import ( |
| "bytes" |
| + "context" |
| "encoding/json" |
| "log" |
| "os" |
| @@ -410,7 +411,7 @@ func TestMaterializeReapsTombstonedAccounts(t *testing.T) { |
| if _, err := st.CreateAppIn(id, "blog", "paul@keymail.dev", now); err != nil { |
| t.Fatal(err) |
| } |
| - if err := st.SetLastAccount("paul@keymail.dev", id); err != nil { |
| + if err := st.SetLastAccount(context.Background(), "paul@keymail.dev", id); err != nil { |
| t.Fatal(err) |
| } |
| @@ -435,10 +436,10 @@ func TestMaterializeReapsTombstonedAccounts(t *testing.T) { |
| if apps, _ := st.AppsIn(id); len(apps) != 0 { |
| t.Errorf("AppsIn = %v, want none", apps) |
| } |
| - if trashed, _ := st.TrashedAppsIn(id); len(trashed) != 0 { |
| + if trashed, _ := st.TrashedAppsIn(context.Background(), id); len(trashed) != 0 { |
| t.Errorf("TrashedAppsIn = %+v, want none — the app rows are reaped with the account", trashed) |
| } |
| - if last, err := st.LastAccount("paul@keymail.dev"); err != nil || last != 0 { |
| + if last, err := st.LastAccount(context.Background(), "paul@keymail.dev"); err != nil || last != 0 { |
| t.Errorf("LastAccount = %d %v, want 0 — the MRU must not land anyone in a reaped account", last, err) |
| } |
| // Stable: a second pass finds a marked row and a tombstoned manifest agreeing. |
| @@ -606,7 +607,7 @@ func TestMaterializeAppsConverges(t *testing.T) { |
| // The cooloff clock comes from the MARKER, not from this pass: the bucket |
| // records when the app was trashed, and a console catching up days later |
| // must not restart the 30 days. |
| - trashedRows, err := st.TrashedAppsIn(id) |
| + trashedRows, err := st.TrashedAppsIn(context.Background(), id) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/mobilenav.go b/internal/console/mobilenav.go| index a8b0e877b..13425e74b 100644 |
| --- a/internal/console/mobilenav.go |
| +++ b/internal/console/mobilenav.go |
| @@ -235,7 +235,7 @@ func (s *Server) handleAppIndex(w http.ResponseWriter, r *http.Request) { |
| p := s.accountPage(w, r, addr, raw, acct, role) |
| p.Title = app |
| p.AppName = app |
| - p.LinkedApp = s.linkedAppPage(acct, app) |
| + p.LinkedApp = s.linkedAppPage(r.Context(), acct, app) |
| p.ActiveNav = "apps" |
| p.IndexOf = indexApp |
| s.render(w, http.StatusOK, "nav_index", p) |
diff --git a/internal/console/opbilling_store_test.go b/internal/console/opbilling_store_test.go| index 978d847e9..6bebd3393 100644 |
| --- a/internal/console/opbilling_store_test.go |
| +++ b/internal/console/opbilling_store_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "reflect" |
| "testing" |
| "time" |
| @@ -18,7 +19,7 @@ func TestBillingFunnel(t *testing.T) { |
| if _, err := st.EnsureUser("faa@example.com", old); err != nil { |
| t.Fatal(err) |
| } |
| - if err := st.TouchLastSeen("faa@example.com", recent); err != nil { |
| + if err := st.TouchLastSeen(context.Background(), "faa@example.com", recent); err != nil { |
| t.Fatal(err) |
| } |
| // fab: an app, its owner seen long ago, but signed in recently. |
| @@ -28,7 +29,7 @@ func TestBillingFunnel(t *testing.T) { |
| if _, err := st.EnsureUser("fab@example.com", old); err != nil { |
| t.Fatal(err) |
| } |
| - if err := st.TouchLastSeen("fab@example.com", old); err != nil { |
| + if err := st.TouchLastSeen(context.Background(), "fab@example.com", old); err != nil { |
| t.Fatal(err) |
| } |
| if _, err := st.CreateSession("fab@example.com", "", recent); err != nil { |
| @@ -62,7 +63,7 @@ func TestBillingFunnel(t *testing.T) { |
| if _, err := st.EnsureUser("m@example.com", old); err != nil { |
| t.Fatal(err) |
| } |
| - if err := st.TouchLastSeen("m@example.com", recent); err != nil { |
| + if err := st.TouchLastSeen(context.Background(), "m@example.com", recent); err != nil { |
| t.Fatal(err) |
| } |
| // faf: deleted, with an app and a recent visit; counts nowhere. |
| @@ -72,7 +73,7 @@ func TestBillingFunnel(t *testing.T) { |
| if _, err := st.EnsureUser("faf@example.com", old); err != nil { |
| t.Fatal(err) |
| } |
| - if err := st.TouchLastSeen("faf@example.com", recent); err != nil { |
| + if err := st.TouchLastSeen(context.Background(), "faf@example.com", recent); err != nil { |
| t.Fatal(err) |
| } |
| if err := st.ReapAccount(ids["faf"], now); err != nil { |
diff --git a/internal/console/opdashboard_test.go b/internal/console/opdashboard_test.go| index 5df16354f..4b9a5f38f 100644 |
| --- a/internal/console/opdashboard_test.go |
| +++ b/internal/console/opdashboard_test.go |
| @@ -91,7 +91,7 @@ func seedOperatorWorld(t *testing.T, fx *consoleFixture) operatorWorld { |
| t.Fatal(err) |
| } |
| if p.seen { |
| - if err := fx.st.TouchLastSeen(p.addr, now); err != nil { |
| + if err := fx.st.TouchLastSeen(context.Background(), p.addr, now); err != nil { |
| t.Fatal(err) |
| } |
| } |
diff --git a/internal/console/opstore.go b/internal/console/opstore.go| index 214b0a08e..381b33323 100644 |
| --- a/internal/console/opstore.go |
| +++ b/internal/console/opstore.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "database/sql" |
| "encoding/json" |
| "errors" |
| @@ -284,8 +285,8 @@ func (s *Store) OperatorPerson(address string) (*PersonDetail, error) { |
| // TouchLastSeen records that address was seen at now. It never moves |
| // last_seen backwards and never creates a users row. |
| -func (s *Store) TouchLastSeen(address string, now time.Time) error { |
| - _, err := s.db.Exec(opSQLTouchLastSeen, now.Unix(), address, now.Unix()) |
| +func (s *Store) TouchLastSeen(ctx context.Context, address string, now time.Time) error { |
| + _, err := s.db.ExecContext(ctx, opSQLTouchLastSeen, now.Unix(), address, now.Unix()) |
| return err |
| } |
diff --git a/internal/console/opstore_test.go b/internal/console/opstore_test.go| index 775606f5e..7ed843d2c 100644 |
| --- a/internal/console/opstore_test.go |
| +++ b/internal/console/opstore_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "database/sql" |
| "fmt" |
| "math" |
| @@ -367,14 +368,14 @@ func opHas(list []string, s string) bool { |
| func TestTouchLastSeenNeverMovesBack(t *testing.T) { |
| s := openOpStore(t) |
| opUser(t, s, "ann@example.com", opNow.Add(-24*time.Hour)) |
| - opMust(t, s.TouchLastSeen("ann@example.com", opNow)) |
| - opMust(t, s.TouchLastSeen("ann@example.com", opNow.Add(-time.Hour))) |
| + opMust(t, s.TouchLastSeen(context.Background(), "ann@example.com", opNow)) |
| + opMust(t, s.TouchLastSeen(context.Background(), "ann@example.com", opNow.Add(-time.Hour))) |
| var seen int64 |
| opMust(t, s.db.QueryRow(`SELECT last_seen FROM users WHERE address = 'ann@example.com'`).Scan(&seen)) |
| if seen != opNow.Unix() { |
| t.Fatalf("last_seen = %d, want %d", seen, opNow.Unix()) |
| } |
| - opMust(t, s.TouchLastSeen("nobody@example.com", opNow)) |
| + opMust(t, s.TouchLastSeen(context.Background(), "nobody@example.com", opNow)) |
| var n int |
| opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)) |
| if n != 1 { |
| @@ -411,8 +412,8 @@ func TestOperatorCountsWindows(t *testing.T) { |
| opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "rollback", "rolled back stable to v1", opNow.Add(-time.Hour))) |
| opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "promote", "promoted v0 to stable", opNow.Add(-24*time.Hour))) |
| opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "rename", "renamed", opNow.Add(-time.Hour))) |
| - opMust(t, s.TouchLastSeen("a@example.com", opNow.Add(-time.Hour))) |
| - opMust(t, s.TouchLastSeen("b@example.com", opNow.Add(-5*24*time.Hour))) |
| + opMust(t, s.TouchLastSeen(context.Background(), "a@example.com", opNow.Add(-time.Hour))) |
| + opMust(t, s.TouchLastSeen(context.Background(), "b@example.com", opNow.Add(-5*24*time.Hour))) |
| if _, err := s.CreateSessionMethod("c@example.com", "", MethodKeymail, opNow.Add(-3*24*time.Hour)); err != nil { |
| t.Fatal(err) |
| } |
| @@ -467,7 +468,7 @@ func TestNewestPeopleAndPeoplePage(t *testing.T) { |
| if _, err := s.CreateAppIn(acct, "shop", "ed@notes.test", opNow); err != nil { |
| t.Fatal(err) |
| } |
| - opMust(t, s.TouchLastSeen("ed@notes.test", opNow)) |
| + opMust(t, s.TouchLastSeen(context.Background(), "ed@notes.test", opNow)) |
| newest, err := s.NewestPeople(2) |
| opMust(t, err) |
| if len(newest) != 2 || newest[0].Address != "ed@notes.test" || newest[1].Address != "di@demo.invalid" { |
| @@ -714,7 +715,7 @@ func TestActivityFeedFiltersAndPages(t *testing.T) { |
| func TestGatedStoreOpensWithTheNewSchema(t *testing.T) { |
| cx := newClaimCase(t) |
| - if err := cx.st.TouchLastSeen(claimFxOwner, time.Now()); err != nil { |
| + if err := cx.st.TouchLastSeen(context.Background(), claimFxOwner, time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| } |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 09a060570..a2f9d46c1 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -237,7 +237,7 @@ func (s *Server) handleTrash(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - rows, err := s.store.TrashedAppsIn(acct.ID) |
| + rows, err := s.store.TrashedAppsIn(r.Context(), acct.ID) |
| if err != nil { |
| log.Printf("console: trash %s: %v", acct.Sqid, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", |
diff --git a/internal/console/pending.go b/internal/console/pending.go| index 1061842ba..9ea4c9bb5 100644 |
| --- a/internal/console/pending.go |
| +++ b/internal/console/pending.go |
| @@ -181,7 +181,8 @@ func (s *Store) ConfirmChange(id, address string, now time.Time) (*PendingChange |
| id, address, now.Unix()); err != nil { |
| return nil, false, err |
| } |
| - confirms, err := confirmsFor(tx, id) |
| + // ConfirmChange carries no context yet. |
| + confirms, err := confirmsFor(context.Background(), tx, id) |
| if err != nil { |
| return nil, false, err |
| } |
| @@ -193,13 +194,13 @@ func (s *Store) ConfirmChange(id, address string, now time.Time) (*PendingChange |
| } |
| // PendingChangesFor lists an account/app's unexpired, unexecuted changes. |
| -func (s *Store) claimRawPendingChangesFor(accountID int64, app string, now time.Time) ([]PendingChange, error) { |
| - tx, err := s.db.Begin() |
| +func (s *Store) claimRawPendingChangesFor(ctx context.Context, accountID int64, app string, now time.Time) ([]PendingChange, error) { |
| + tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return nil, err |
| } |
| defer tx.Rollback() |
| - rows, err := tx.Query(`SELECT id, account_id, app, kind, payload, quorum, proposer, created_at, expires_at |
| + rows, err := tx.QueryContext(ctx, `SELECT id, account_id, app, kind, payload, quorum, proposer, created_at, expires_at |
| FROM pending_changes |
| WHERE account_id = ? AND app = ? AND executed_at = 0 AND expires_at > ? |
| ORDER BY created_at, id`, accountID, app, now.Unix()) |
| @@ -226,7 +227,7 @@ ORDER BY created_at, id`, accountID, app, now.Unix()) |
| return nil, err |
| } |
| for i, id := range ids { |
| - confirms, err := confirmsFor(tx, id) |
| + confirms, err := confirmsFor(ctx, tx, id) |
| if err != nil { |
| return nil, err |
| } |
| @@ -260,7 +261,8 @@ func (s *Store) PendingChange(id string, now time.Time) (*PendingChange, error) |
| if !executedAtZero(tx, id) { |
| return nil, nil |
| } |
| - confirms, err := confirmsFor(tx, id) |
| + // PendingChange carries no context yet. |
| + confirms, err := confirmsFor(context.Background(), tx, id) |
| if err != nil { |
| return nil, err |
| } |
| @@ -285,8 +287,8 @@ func (s *Store) PendingChange(id string, now time.Time) (*PendingChange, error) |
| // keeps showing every row — the gap between the two numbers is the honest |
| // picture, and a card that quietly dropped a name would make a stuck change |
| // unexplainable. |
| -func (s *Store) MemberConfirms(accountID int64, id string) ([]string, error) { |
| - rows, err := s.db.Query(`SELECT c.address FROM pending_confirms c |
| +func (s *Store) MemberConfirms(ctx context.Context, accountID int64, id string) ([]string, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT c.address FROM pending_confirms c |
| JOIN memberships m ON m.address = c.address AND m.account_id = ? |
| WHERE c.change_id = ? ORDER BY c.confirmed_at, c.address`, accountID, id) |
| if err != nil { |
| @@ -367,8 +369,8 @@ func executedAtZero(tx *sql.Tx, id string) bool { |
| // confirmsFor returns a change's confirming addresses, sorted by when they |
| // confirmed. |
| -func confirmsFor(tx *sql.Tx, id string) ([]string, error) { |
| - rows, err := tx.Query(`SELECT address FROM pending_confirms WHERE change_id = ? ORDER BY confirmed_at, address`, id) |
| +func confirmsFor(ctx context.Context, tx *sql.Tx, id string) ([]string, error) { |
| + rows, err := tx.QueryContext(ctx, `SELECT address FROM pending_confirms WHERE change_id = ? ORDER BY confirmed_at, address`, id) |
| if err != nil { |
| return nil, err |
| } |
| @@ -392,7 +394,7 @@ func (s *Store) PendingChangesFor(accountID int64, app string, now time.Time) (c |
| // shows the pending card register with the gate and refuse under a foreign |
| // operation. The armed triggers still refuse any write it could ever grow. |
| func (s *Store) PendingChangesForContext(claimContext context.Context, accountID int64, app string, now time.Time) (claimResult0 []PendingChange, claimResult1 error) { |
| - return s.claimRawPendingChangesFor(accountID, app, now) |
| + return s.claimRawPendingChangesFor(claimContext, accountID, app, now) |
| } |
| func (s *Store) ProposeChange(accountID int64, app, kind string, payload []byte, quorum int, proposer string, proposerConfirmed bool, now time.Time) (claimResult0 *PendingChange, claimResult1 error) { |
| return s.ProposeChangeContext(context.Background(), accountID, app, kind, payload, quorum, proposer, proposerConfirmed, now) |
diff --git a/internal/console/pendinghandlers.go b/internal/console/pendinghandlers.go| index 012518167..3f5adda8d 100644 |
| --- a/internal/console/pendinghandlers.go |
| +++ b/internal/console/pendinghandlers.go |
| @@ -332,7 +332,7 @@ func (s *Server) executePending(ctx context.Context, acct *Account, app, actor s |
| if err != nil { |
| return "", err |
| } |
| - counted, err := s.store.MemberConfirms(pc.AccountID, pc.ID) |
| + counted, err := s.store.MemberConfirms(ctx, pc.AccountID, pc.ID) |
| if err != nil { |
| log.Printf("console: execute %s %s: member confirms: %v", pc.Kind, pc.ID, err) |
| return "", errors.New("could not check who has confirmed this change") |
| @@ -454,9 +454,9 @@ func requiredQuorum(pc *PendingChange, pipe *release.Pipeline) (int, error) { |
| // The gap between this and len(pc.Confirms) is deliberately not hidden: a |
| // change stuck because someone left the account shows fewer confirmations |
| // than it has rows, which is the honest explanation for why it is stuck. |
| -func (s *Server) pendingTally(pc PendingChange, pipe *release.Pipeline) (confirmed, needed int) { |
| +func (s *Server) pendingTally(ctx context.Context, pc PendingChange, pipe *release.Pipeline) (confirmed, needed int) { |
| confirmed, needed = len(pc.Confirms), pc.Quorum |
| - if counted, err := s.store.MemberConfirms(pc.AccountID, pc.ID); err != nil { |
| + if counted, err := s.store.MemberConfirms(ctx, pc.AccountID, pc.ID); err != nil { |
| log.Printf("console: pending tally %s: member confirms: %v", pc.ID, err) |
| } else { |
| confirmed = len(counted) |
| @@ -773,7 +773,7 @@ func (s *Server) handlePendingConfirm(w http.ResponseWriter, r *http.Request) { |
| // gets and the row the trail keeps say the same thing the gate does. |
| // Deciding on it also keeps the not-met path a plain progress message |
| // rather than an execution that refuses a beat later. |
| - confirmed, needed := s.pendingTally(*pc, s.pendingPipeline(ctx, acct, app)) |
| + confirmed, needed := s.pendingTally(ctx, *pc, s.pendingPipeline(ctx, acct, app)) |
| if confirmed < needed { |
| s.audit(acct, app, addr, "confirmed", fmt.Sprintf("%s (%d of %d confirmations)", |
| pendingSummary(*pc), confirmed, needed)) |
| @@ -877,7 +877,7 @@ func (s *Server) handleAPIPending(w http.ResponseWriter, r *http.Request) { |
| } |
| out := make([]map[string]any, 0, len(list)) |
| for _, pc := range list { |
| - confirmed, needed := s.pendingTally(pc, pipe) |
| + confirmed, needed := s.pendingTally(r.Context(), pc, pipe) |
| out = append(out, map[string]any{ |
| "id": pc.ID, |
| "kind": pc.Kind, |
diff --git a/internal/console/pipelinepage.go b/internal/console/pipelinepage.go| index f9f913bf2..cdda44d2f 100644 |
| --- a/internal/console/pipelinepage.go |
| +++ b/internal/console/pipelinepage.go |
| @@ -56,10 +56,10 @@ type PendingChangeView struct { |
| // pipe is the app's pipeline, read ONCE by the caller for the whole listing |
| // (nil is fine — a legacy app, or a read that failed: the tally then degrades |
| // to the stored quorum, which is exactly what it was before this existed). |
| -func (s *Server) pendingChangeViews(pcs []PendingChange, pipe *release.Pipeline) []PendingChangeView { |
| +func (s *Server) pendingChangeViews(ctx context.Context, pcs []PendingChange, pipe *release.Pipeline) []PendingChangeView { |
| out := make([]PendingChangeView, len(pcs)) |
| for i, pc := range pcs { |
| - confirmed, needed := s.pendingTally(pc, pipe) |
| + confirmed, needed := s.pendingTally(ctx, pc, pipe) |
| out[i] = PendingChangeView{ |
| ID: pc.ID, Kind: pc.Kind, Summary: pendingSummary(pc), |
| Confirmed: confirmed, Needed: needed, |
diff --git a/internal/console/placement_census_test.go b/internal/console/placement_census_test.go| index b32140eff..9e6f274c4 100644 |
| --- a/internal/console/placement_census_test.go |
| +++ b/internal/console/placement_census_test.go |
| @@ -55,7 +55,7 @@ func TestEffectivePlacementIsTheOnlyRouteFallback(t *testing.T) { |
| }, |
| "appPlacementRow": { |
| "store.go:AppPlacement": "hands both columns to effectivePlacement (no fold)", |
| - "fleets.go:appPlacement": "hands both columns to effectivePlacement", |
| + "fleets.go:appPlacementContext": "hands both columns to effectivePlacement (appPlacement is its wrapper)", |
| "fleetsecretskey.go:fleetPlacedAppsIn": "hands both columns to effectivePlacement", |
| "regionfacts.go:regionFactsFor": "hands both columns to effectivePlacement", |
| }, |
diff --git a/internal/console/planexempt_test.go b/internal/console/planexempt_test.go| index 38155ed9c..acb4bf1e2 100644 |
| --- a/internal/console/planexempt_test.go |
| +++ b/internal/console/planexempt_test.go |
| @@ -206,7 +206,7 @@ func TestPlanExemptHasNoGraceLapseOrWarnings(t *testing.T) { |
| if fx.st.lapseEligible(row) { |
| t.Fatal("ops's row is on the lapse path") |
| } |
| - if lines, seen := fx.srv.planBanner(ops, RoleOwner, planNow); len(lines) != 0 || len(seen) != 0 { |
| + if lines, seen := fx.srv.planBanner(context.Background(), ops, RoleOwner, planNow); len(lines) != 0 || len(seen) != 0 { |
| t.Fatalf("ops banner = %v", lines) |
| } |
| fx.srv.planGracePass(context.Background(), planNow) |
| @@ -303,8 +303,9 @@ func TestPlanExemptHasNoBilling(t *testing.T) { |
| // planExemptSites are the functions that decide plans or billing for one |
| // account and must ask planExempt themselves. |
| var planExemptSites = []string{ |
| - // Limits (req 1). |
| - "EnsureDefaultPlans", "publishAccountLimits", "EffectiveLimits", |
| + // Limits (req 1). EffectiveLimits is a wrapper over |
| + // EffectiveLimitsContext, which asks. |
| + "EnsureDefaultPlans", "publishAccountLimits", "EffectiveLimitsContext", |
| // Caps and lifecycle (req 2). |
| "checkMemberCap", "pdfPlanCheck", "lapseEligible", "planBanner", "writePlanWarnings", |
| "transitionAccountPlan", |
| @@ -383,7 +384,7 @@ func planExemptFindings(files map[string]*ast.File, sites []string) (findings, f |
| } |
| continue |
| } |
| - if (buildsPlanCap(fd) || callsAny(fd, "PutLimits")) && !asksPlanExempt(fd) && !callsAny(fd, "EffectiveLimits") { |
| + if (buildsPlanCap(fd) || callsAny(fd, "PutLimits")) && !asksPlanExempt(fd) && !callsAny(fd, "EffectiveLimits", "EffectiveLimitsContext") { |
| findings = append(findings, name+" applies a plan without asking planExempt or EffectiveLimits") |
| } |
| } |
| @@ -411,11 +412,12 @@ func TestPlanExemptConsulted(t *testing.T) { |
| func (s *Server) checkNewThing(acct *Account) error { return &planCapError{msg: "x"} } |
| func (s *Server) publishSideways(ctx int) { plans.PutLimits(nil, nil, nil, "") } |
| func (s *Server) checkCounted(acct *Account) error { s.EffectiveLimits(acct); return &planCapError{msg: "x"} } |
| -func (s *Server) EffectiveLimits(acct *Account) {} |
| +func (s *Server) checkCountedCtx(acct *Account) error { s.EffectiveLimitsContext(nil, acct); return &planCapError{msg: "x"} } |
| +func (s *Server) EffectiveLimitsContext(acct *Account) {} |
| `) |
| got, _ := planExemptFindings(planted, planExemptSites) |
| want := []string{ |
| - "EffectiveLimits does not ask planExempt", |
| + "EffectiveLimitsContext does not ask planExempt", |
| "checkNewThing applies a plan without asking planExempt or EffectiveLimits", |
| "publishSideways applies a plan without asking planExempt or EffectiveLimits", |
| } |
diff --git a/internal/console/plangrace_store.go b/internal/console/plangrace_store.go| index 017298806..bb0168000 100644 |
| --- a/internal/console/plangrace_store.go |
| +++ b/internal/console/plangrace_store.go |
| @@ -1,6 +1,9 @@ |
| package console |
| -import "time" |
| +import ( |
| + "context" |
| + "time" |
| +) |
| // Plans 4a's own table, kept here so the feature is one file to read. |
| func (s *Store) migratePlanGrace() error { |
| @@ -36,9 +39,16 @@ func timeOrZero(sec int64) time.Time { |
| return time.Unix(sec, 0).UTC() |
| } |
| -// CapStates is every cap row for the account, in capOrder. |
| +// CapStates is every cap row for the account, in capOrder. It is |
| +// CapStatesContext for callers with no request to follow. |
| func (s *Store) CapStates(accountID int64) ([]capState, error) { |
| - rows, err := s.db.Query(`SELECT cap, period, level, used, cap_limit, first_over, grace_ends, |
| + return s.CapStatesContext(context.Background(), accountID) |
| +} |
| + |
| +// CapStatesContext is CapStates under the caller's context: the plan banner |
| +// on every account page reads it. |
| +func (s *Store) CapStatesContext(ctx context.Context, accountID int64) ([]capState, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT cap, period, level, used, cap_limit, first_over, grace_ends, |
| warned_at, reminded_at, notice_at, updated_at FROM plan_cap_state WHERE account_id = ?`, accountID) |
| if err != nil { |
| return nil, err |
| @@ -106,12 +116,12 @@ const deleteCapStateSQL = `DELETE FROM plan_cap_state WHERE account_id = ? AND c |
| // for the episode shown (same period and first over, Astra plans-4a |
| // finding 2), only once the cap was over and not before it went over |
| // (spec §6), and the first such notice is kept. |
| -func (s *Store) RecordCapNotice(accountID int64, seen []capState, at time.Time) error { |
| +func (s *Store) RecordCapNotice(ctx context.Context, accountID int64, seen []capState, at time.Time) error { |
| for _, st := range seen { |
| if !st.Level.over() || st.FirstOver.IsZero() || at.Before(st.FirstOver) { |
| continue |
| } |
| - if _, err := s.db.Exec(`UPDATE plan_cap_state SET notice_at = ? WHERE account_id = ? AND cap = ? |
| + if _, err := s.db.ExecContext(ctx, `UPDATE plan_cap_state SET notice_at = ? WHERE account_id = ? AND cap = ? |
| AND period = ? AND first_over = ? AND level IN ('over', 'ceiling') AND notice_at = 0`, |
| at.Unix(), accountID, string(st.Cap), st.Period, st.FirstOver.Unix()); err != nil { |
| return err |
diff --git a/internal/console/plangrace_test.go b/internal/console/plangrace_test.go| index 2ff51566a..afce6997f 100644 |
| --- a/internal/console/plangrace_test.go |
| +++ b/internal/console/plangrace_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "testing" |
| "time" |
| ) |
| @@ -140,10 +141,10 @@ func TestRecordCapNoticeOnlyWhenOver(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - if err := fx.st.RecordCapNotice(acct.ID, []capState{warn, over}, planNow); err != nil { |
| + if err := fx.st.RecordCapNotice(context.Background(), acct.ID, []capState{warn, over}, planNow); err != nil { |
| t.Fatal(err) |
| } |
| - if err := fx.st.RecordCapNotice(acct.ID, []capState{over}, planNow.Add(time.Hour)); err != nil { |
| + if err := fx.st.RecordCapNotice(context.Background(), acct.ID, []capState{over}, planNow.Add(time.Hour)); err != nil { |
| t.Fatal(err) |
| } |
| got, _ := fx.st.CapStates(acct.ID) |
| @@ -172,7 +173,7 @@ func TestPutCapStateKeepsConcurrentNotice(t *testing.T) { |
| t.Fatal(err) |
| } |
| snapshot := st // the pass read this before the owner's page view |
| - if err := fx.st.RecordCapNotice(acct.ID, []capState{st}, planNow.Add(time.Minute)); err != nil { |
| + if err := fx.st.RecordCapNotice(context.Background(), acct.ID, []capState{st}, planNow.Add(time.Minute)); err != nil { |
| t.Fatal(err) |
| } |
| snapshot.Used, snapshot.UpdatedAt = 160, planNow.Add(2*time.Minute) |
| @@ -207,13 +208,13 @@ func TestRecordCapNoticeMatchesTheEpisodeShown(t *testing.T) { |
| if err := fx.st.PutCapState(today); err != nil { // the pass rolled the day after the page read yesterday's row |
| t.Fatal(err) |
| } |
| - if err := fx.st.RecordCapNotice(acct.ID, []capState{yesterday}, planNow); err != nil { |
| + if err := fx.st.RecordCapNotice(context.Background(), acct.ID, []capState{yesterday}, planNow); err != nil { |
| t.Fatal(err) |
| } |
| if got, _ := capRow(t, fx, acct, capEmail); !got.NoticeAt.IsZero() { |
| t.Fatalf("yesterday's warning counted as notice for today: %v", got.NoticeAt) |
| } |
| - if err := fx.st.RecordCapNotice(acct.ID, []capState{today}, planNow.Add(-time.Minute)); err != nil { |
| + if err := fx.st.RecordCapNotice(context.Background(), acct.ID, []capState{today}, planNow.Add(-time.Minute)); err != nil { |
| t.Fatal(err) |
| } |
| if got, _ := capRow(t, fx, acct, capEmail); !got.NoticeAt.IsZero() { |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index 29c5e97b1..0b272cda9 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -220,7 +220,7 @@ func noticeDue(st capState, now time.Time, stage string, lastOff time.Time) bool |
| // due. Marks are set, and notice recorded, only when at least one owner's |
| // delivery was accepted; otherwise the next pass tries again. |
| func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []capState, now time.Time) error { |
| - stage := s.planStage(acct, now) |
| + stage := s.planStage(ctx, acct, now) |
| lastOff := s.lapseLastOff(acct) |
| var due []capState |
| for _, st := range states { |
| @@ -269,7 +269,7 @@ func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []c |
| return err |
| } |
| } |
| - return s.store.RecordCapNotice(acct.ID, due, now) |
| + return s.store.RecordCapNotice(ctx, acct.ID, due, now) |
| } |
| func (s *Server) planNoticeEmail(acct *Account, due []capState, stage func(capState) string) (string, string) { |
| @@ -362,18 +362,18 @@ func humanGB(b int64) string { |
| // or over, and the rows behind them when the viewer is an owner. It records |
| // nothing: notice is the banner actually served, so render records it once |
| // the page is written (Astra plans-4a finding 3). A store error shows no |
| -// banner and never fails the page. |
| -func (s *Server) planBanner(acct *Account, role string, now time.Time) ([]string, []capState) { |
| +// banner and never fails the page. Its reads run under the request's ctx. |
| +func (s *Server) planBanner(ctx context.Context, acct *Account, role string, now time.Time) ([]string, []capState) { |
| if s.cfg.PlanCatalog == nil || s.store.planExempt(acct.ID) { |
| return nil, nil |
| } |
| - states, err := s.store.CapStates(acct.ID) |
| + states, err := s.store.CapStatesContext(ctx, acct.ID) |
| if err != nil { |
| log.Printf("console: plan banner %s: %v", acct.Sqid, err) |
| return nil, nil |
| } |
| var lines []string |
| - for _, n := range planNoticesOf(states, now, s.planStage(acct, now)) { |
| + for _, n := range planNoticesOf(states, now, s.planStage(ctx, acct, now)) { |
| lines = append(lines, planNoticeText(n, "banner")) |
| } |
| if role != RoleOwner || len(lines) == 0 { |
| @@ -393,14 +393,23 @@ func shownStates(states []capState, now time.Time) []capState { |
| return out |
| } |
| +// bannerNotice is a page's plan banner as an owner was shown it: the |
| +// account, the over rows behind it (planBanner's second answer) and the |
| +// request it was served on, whose context the notice write runs under. |
| +type bannerNotice struct { |
| + ctx context.Context |
| + accountID int64 |
| + seen []capState |
| +} |
| + |
| // recordBannerNotice records notice for a page whose banner was served to |
| -// an owner. |
| -func (s *Server) recordBannerNotice(accountID int64, seen []capState, now time.Time) { |
| - if len(seen) == 0 { |
| +// an owner, under that page's request context. |
| +func (s *Server) recordBannerNotice(n bannerNotice, now time.Time) { |
| + if len(n.seen) == 0 { |
| return |
| } |
| - if err := s.store.RecordCapNotice(accountID, seen, now); err != nil { |
| - log.Printf("console: plan banner %d: notice: %v", accountID, err) |
| + if err := s.store.RecordCapNotice(n.ctx, n.accountID, n.seen, now); err != nil { |
| + log.Printf("console: plan banner %d: notice: %v", n.accountID, err) |
| } |
| } |
| @@ -419,20 +428,20 @@ func (s *Server) writePlanWarnings(w http.ResponseWriter, r *http.Request, p Pri |
| if s.cfg.PlanCatalog == nil || s.store.planExempt(acct.ID) || r.Header.Get(planWarningsAccept) != "1" { |
| return |
| } |
| - states, err := s.store.CapStates(acct.ID) |
| + states, err := s.store.CapStatesContext(r.Context(), acct.ID) |
| if err != nil { |
| log.Printf("console: plan warnings %s: %v", acct.Sqid, err) |
| return |
| } |
| now := time.Now() |
| - for _, n := range planNoticesOf(states, now, s.planStage(acct, now)) { |
| + for _, n := range planNoticesOf(states, now, s.planStage(r.Context(), acct, now)) { |
| w.Header().Add(planWarningHeader, planNoticeText(n, "cli")) |
| } |
| seen := shownStates(states, now) |
| if len(seen) == 0 || p.Kind != PrincipalUser || !s.isOwner(acct, p.Address) { |
| return |
| } |
| - if err := s.store.RecordCapNotice(acct.ID, seen, now); err != nil { |
| + if err := s.store.RecordCapNotice(r.Context(), acct.ID, seen, now); err != nil { |
| log.Printf("console: plan warnings %s: notice: %v", acct.Sqid, err) |
| } |
| } |
| @@ -458,13 +467,13 @@ func (s *Server) isOwner(acct *Account, addr string) bool { |
| // "lapse_off" while something of its kind is turned off, otherwise |
| // "lapse_grace" while it is over. |
| // nil when the account's limits cannot be read. |
| -func (s *Server) planStage(acct *Account, now time.Time) func(capState) string { |
| - l, err := s.EffectiveLimits(acct) |
| +func (s *Server) planStage(ctx context.Context, acct *Account, now time.Time) func(capState) string { |
| + l, err := s.EffectiveLimitsContext(ctx, acct) |
| if err != nil || l == nil { |
| return nil |
| } |
| - pauseAt := planMailPauseAt(l, s.planCeilings(acct)) |
| - lapse := s.lapseStages(acct) |
| + pauseAt := planMailPauseAt(l, s.planCeilings(ctx, acct)) |
| + lapse := s.lapseStages(ctx, acct) |
| return func(st capState) string { |
| if stage := lapse(st); stage != "" { |
| return stage |
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go| index c95214d64..ead828131 100644 |
| --- a/internal/console/planlapse.go |
| +++ b/internal/console/planlapse.go |
| @@ -338,13 +338,13 @@ func lapseCapOf(kind string) capID { |
| // lapseStages answers planStage's lapse question for acct, reading the plan |
| // row and the lapse items once. A store error, or an account not on the |
| // lapse path, answers "" for every row. |
| -func (s *Server) lapseStages(acct *Account) func(capState) string { |
| +func (s *Server) lapseStages(ctx context.Context, acct *Account) func(capState) string { |
| none := func(capState) string { return "" } |
| - row, err := s.store.AccountPlan(acct.ID) |
| + row, err := s.store.AccountPlanContext(ctx, acct.ID) |
| if err != nil || !s.store.lapseEligible(row) { |
| return none |
| } |
| - items, err := s.store.LapseItems(acct.ID) |
| + items, err := s.store.LapseItemsContext(ctx, acct.ID) |
| if err != nil { |
| return none |
| } |
diff --git a/internal/console/planlapse_keep.go b/internal/console/planlapse_keep.go| index 64e280f70..0de6143ef 100644 |
| --- a/internal/console/planlapse_keep.go |
| +++ b/internal/console/planlapse_keep.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "fmt" |
| "log" |
| "net/http" |
| @@ -30,15 +31,15 @@ type planKeepRow struct { |
| // planKeepOffered is whether an account's owners get the keep page link: |
| // plans on, the account on the lapse path, and its running things or |
| // workers over. |
| -func (s *Server) planKeepOffered(acct *Account) bool { |
| +func (s *Server) planKeepOffered(ctx context.Context, acct *Account) bool { |
| if s.cfg.PlanCatalog == nil { |
| return false |
| } |
| - row, err := s.store.AccountPlan(acct.ID) |
| + row, err := s.store.AccountPlanContext(ctx, acct.ID) |
| if err != nil || !s.store.lapseEligible(row) { |
| return false |
| } |
| - states, err := s.store.CapStates(acct.ID) |
| + states, err := s.store.CapStatesContext(ctx, acct.ID) |
| if err != nil { |
| return false |
| } |
diff --git a/internal/console/planlapse_store.go b/internal/console/planlapse_store.go| index 743d9ec7a..fb1f3c070 100644 |
| --- a/internal/console/planlapse_store.go |
| +++ b/internal/console/planlapse_store.go |
| @@ -36,9 +36,15 @@ type lapseItem struct { |
| UpdatedAt time.Time |
| } |
| -// LapseItems is every lapse item row for the account. |
| +// LapseItems is every lapse item row for the account. It is |
| +// LapseItemsContext for callers with no request to follow. |
| func (s *Store) LapseItems(accountID int64) ([]lapseItem, error) { |
| - rows, err := s.db.Query(`SELECT app, kind, ref, thing_created, keep, disabled_at, updated_at |
| + return s.LapseItemsContext(context.Background(), accountID) |
| +} |
| + |
| +// LapseItemsContext is LapseItems under the caller's context. |
| +func (s *Store) LapseItemsContext(ctx context.Context, accountID int64) ([]lapseItem, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT app, kind, ref, thing_created, keep, disabled_at, updated_at |
| FROM plan_lapse_items WHERE account_id = ? ORDER BY kind, ref`, accountID) |
| if err != nil { |
| return nil, err |
diff --git a/internal/console/planlapse_test.go b/internal/console/planlapse_test.go| index de7f52833..2369672d1 100644 |
| --- a/internal/console/planlapse_test.go |
| +++ b/internal/console/planlapse_test.go |
| @@ -303,7 +303,7 @@ func TestLapseWaitsForNotice(t *testing.T) { |
| if !ok || !st.NoticeAt.IsZero() { |
| t.Fatalf("running_things row %+v (present %v), want no notice yet", st, ok) |
| } |
| - if err := fx.st.RecordCapNotice(acct.ID, []capState{st}, planNow.Add(week-71*time.Hour)); err != nil { |
| + if err := fx.st.RecordCapNotice(context.Background(), acct.ID, []capState{st}, planNow.Add(week-71*time.Hour)); err != nil { |
| t.Fatal(err) |
| } |
| fx.srv.planGracePass(context.Background(), planNow.Add(week)) |
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go| index bf43ad597..702e8662c 100644 |
| --- a/internal/console/planlimits.go |
| +++ b/internal/console/planlimits.go |
| @@ -129,15 +129,21 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n |
| return errors.New("lost two write races; the next pass retries") |
| } |
| -// EffectiveLimits is acct's limits under the configured catalog, or nil |
| -// when plans are off or the account is exempt (planExempt). An account |
| -// with no row is on the default plan. |
| +// EffectiveLimits is EffectiveLimitsContext for callers with no request to |
| +// follow. |
| func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) { |
| + return s.EffectiveLimitsContext(context.Background(), acct) |
| +} |
| + |
| +// EffectiveLimitsContext is acct's limits under the configured catalog, or |
| +// nil when plans are off or the account is exempt (planExempt). An account |
| +// with no row is on the default plan. Its read runs under ctx. |
| +func (s *Server) EffectiveLimitsContext(ctx context.Context, acct *Account) (*plans.Limits, error) { |
| cat := s.cfg.PlanCatalog |
| if cat == nil || s.store.planExempt(acct.ID) { |
| return nil, nil |
| } |
| - row, err := s.store.AccountPlan(acct.ID) |
| + row, err := s.store.AccountPlanContext(ctx, acct.ID) |
| if err != nil { |
| return nil, err |
| } |
| @@ -156,10 +162,10 @@ func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) { |
| // planCeilings is the ceilings of acct's plan (Catalog.CeilingsFor): the |
| // catalog's, unless the plan sets its own. Plans must be on. |
| -func (s *Server) planCeilings(acct *Account) plans.Limits { |
| +func (s *Server) planCeilings(ctx context.Context, acct *Account) plans.Limits { |
| cat := s.cfg.PlanCatalog |
| plan := cat.DefaultPlan |
| - if row, err := s.store.AccountPlan(acct.ID); err == nil && row != nil { |
| + if row, err := s.store.AccountPlanContext(ctx, acct.ID); err == nil && row != nil { |
| plan = row.Plan |
| } |
| return cat.CeilingsFor(plan) |
diff --git a/internal/console/planmail.go b/internal/console/planmail.go| index fbe938b42..356d9af5a 100644 |
| --- a/internal/console/planmail.go |
| +++ b/internal/console/planmail.go |
| @@ -40,14 +40,14 @@ func (s *Server) enforceAccountMail(ctx context.Context, acct string, now time.T |
| if err != nil || a == nil { |
| return false, err |
| } |
| - l, err := s.EffectiveLimits(a) |
| + l, err := s.EffectiveLimitsContext(ctx, a) |
| if err != nil || l == nil { |
| return false, err |
| } |
| // The day's pause first: it holds until the day rolls, so it is the |
| // one to take when both are due. |
| kind, audit := "", "" |
| - if at := planMailPauseAt(l, s.planCeilings(a)); at > 0 { |
| + if at := planMailPauseAt(l, s.planCeilings(ctx, a)); at > 0 { |
| sent, err := s.store.AccountSends(ctx, acct, usage.DayOf(now)) |
| if err != nil { |
| return false, err |
| @@ -135,11 +135,11 @@ func (s *Server) planMailSpent(ctx context.Context, acct string, now time.Time) |
| if err != nil || a == nil { |
| return false, err |
| } |
| - l, err := s.EffectiveLimits(a) |
| + l, err := s.EffectiveLimitsContext(ctx, a) |
| if err != nil || l == nil { |
| return false, err |
| } |
| - if at := planMailPauseAt(l, s.planCeilings(a)); at > 0 { |
| + if at := planMailPauseAt(l, s.planCeilings(ctx, a)); at > 0 { |
| sent, err := s.store.AccountSends(ctx, acct, usage.DayOf(now)) |
| if err != nil || sent >= at { |
| return err == nil, err |
diff --git a/internal/console/planpdf_test.go b/internal/console/planpdf_test.go| index 4c40d9010..836ef9d3a 100644 |
| --- a/internal/console/planpdf_test.go |
| +++ b/internal/console/planpdf_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "fmt" |
| "math" |
| @@ -145,7 +146,7 @@ func TestPDFCapBanner(t *testing.T) { |
| if err := fx.st.PutCapState(st); err != nil { |
| t.Fatal(err) |
| } |
| - lines, _ := fx.srv.planBanner(acct, RoleOwner, now) |
| + lines, _ := fx.srv.planBanner(context.Background(), acct, RoleOwner, now) |
| if len(lines) != 1 || lines[0] != pdfCeilingBanner { |
| t.Fatalf("banner = %q", lines) |
| } |
| @@ -153,11 +154,11 @@ func TestPDFCapBanner(t *testing.T) { |
| t.Fatalf("usage = %q", got) |
| } |
| next := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC) |
| - if lines, _ := fx.srv.planBanner(acct, RoleOwner, next); len(lines) != 0 { |
| + if lines, _ := fx.srv.planBanner(context.Background(), acct, RoleOwner, next); len(lines) != 0 { |
| t.Fatalf("stale banner = %q", lines) |
| } |
| fx.srv.cfg.PlanCatalog = pdfPlanCatalog(t, 200) |
| - lines, _ = fx.srv.planBanner(acct, RoleOwner, now) |
| + lines, _ = fx.srv.planBanner(context.Background(), acct, RoleOwner, now) |
| if strings.Contains(strings.Join(lines, " "), pdfCeilingBanner) { |
| t.Fatalf("larger plan still refuses: %q", lines) |
| } |
| @@ -208,7 +209,7 @@ func TestPDFCapNotices(t *testing.T) { |
| date := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC).Format("2 January 2006") |
| banner, cli = fmt.Sprintf(banner, date), fmt.Sprintf(cli, date) |
| } |
| - lines, _ := fx.srv.planBanner(acct, RoleOwner, now) |
| + lines, _ := fx.srv.planBanner(context.Background(), acct, RoleOwner, now) |
| if len(lines) != 1 || lines[0] != banner { |
| t.Errorf("banner = %q, want %q", lines, banner) |
| } |
diff --git a/internal/console/regioncandidates.go b/internal/console/regioncandidates.go| index 2952abd72..039a9bd8c 100644 |
| --- a/internal/console/regioncandidates.go |
| +++ b/internal/console/regioncandidates.go |
| @@ -301,7 +301,7 @@ func (s *Server) appPolicy(ctx context.Context, acct *Account, app string) regio |
| log.Printf("console: region policy %s/%s: open registry: %v", acct.Sqid, app, err) |
| return regionPolicy{State: policyUnreadable} |
| } |
| - placed, err := s.appPlacement(reg, acct, app) |
| + placed, err := s.appPlacementContext(ctx, reg, acct, app) |
| if err != nil { |
| log.Printf("console: region policy %s/%s: placement: %v", acct.Sqid, app, err) |
| return regionPolicy{State: policyUnreadable} |
diff --git a/internal/console/regionconfig.go b/internal/console/regionconfig.go| index 015260c6c..eff83a944 100644 |
| --- a/internal/console/regionconfig.go |
| +++ b/internal/console/regionconfig.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "log" |
| "github.com/carlosframework/platform/internal/appconfig" |
| @@ -28,13 +29,13 @@ func (s *Server) expectedSecretsFP() string { |
| return fp |
| } |
| -// appRegion reads the app's stored region through the test seam when one |
| -// is set. |
| -func (s *Server) appRegion(accountID int64, app string) (string, string, error) { |
| +// appRegion reads the app's stored region, under ctx, through the test seam |
| +// when one is set. |
| +func (s *Server) appRegion(ctx context.Context, accountID int64, app string) (string, string, error) { |
| if s.appRegionOf != nil { |
| return s.appRegionOf(accountID, app) |
| } |
| - return s.store.AppRegion(accountID, app) |
| + return s.store.AppRegionContext(ctx, accountID, app) |
| } |
| // logRegionConfig names, once at startup, each configuration that leaves |
diff --git a/internal/console/regionconfig_test.go b/internal/console/regionconfig_test.go| index 39ce9ab84..98bc1898b 100644 |
| --- a/internal/console/regionconfig_test.go |
| +++ b/internal/console/regionconfig_test.go |
| @@ -2,6 +2,7 @@ package console |
| import ( |
| "bytes" |
| + "context" |
| "crypto/ecdh" |
| "encoding/base64" |
| "log" |
| @@ -56,13 +57,13 @@ func TestExpectedSecretsFP(t *testing.T) { |
| func TestAppRegionUsesTheSeamWhenSet(t *testing.T) { |
| fx := newConsoleFixture(t) |
| - if r, src, err := fx.srv.appRegion(OpsAccountID, "nobody"); err != nil || r != "" || src != "" { |
| + if r, src, err := fx.srv.appRegion(context.Background(), OpsAccountID, "nobody"); err != nil || r != "" || src != "" { |
| t.Fatalf("store read of a missing app = %q %q %v, want empty", r, src, err) |
| } |
| fx.srv.appRegionOf = func(id int64, app string) (string, string, error) { |
| return "uk", "timezone", nil |
| } |
| - if r, src, err := fx.srv.appRegion(OpsAccountID, "nobody"); err != nil || r != "uk" || src != "timezone" { |
| + if r, src, err := fx.srv.appRegion(context.Background(), OpsAccountID, "nobody"); err != nil || r != "uk" || src != "timezone" { |
| t.Fatalf("seam read = %q %q %v, want uk timezone", r, src, err) |
| } |
| } |
diff --git a/internal/console/regiondefault.go b/internal/console/regiondefault.go| index 83ceae823..c221cd3bb 100644 |
| --- a/internal/console/regiondefault.go |
| +++ b/internal/console/regiondefault.go |
| @@ -34,7 +34,7 @@ type appDefaultView struct { |
| func boolp(b bool) *bool { return &b } |
| func (s *Server) appDefault(ctx context.Context, acct *Account, app string) appDefaultView { |
| - stored, source, rerr := s.appRegion(acct.ID, app) |
| + stored, source, rerr := s.appRegion(ctx, acct.ID, app) |
| snap, ferr := s.liveEdges(ctx) |
| cands := homeOnlyCandidates() |
| if ferr == nil { |
diff --git a/internal/console/regionfacts.go b/internal/console/regionfacts.go| index fa937cc31..ad0f0627d 100644 |
| --- a/internal/console/regionfacts.go |
| +++ b/internal/console/regionfacts.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "fmt" |
| "log" |
| @@ -180,8 +181,8 @@ func (s *Server) registryRoutes() ([]registry.Route, bool) { |
| // store's columns and a route fleet the caller already folded from rows it |
| // listed (routeFleet, with routesOK false when that listing failed). An |
| // unread fact is unknown: never the home by default. |
| -func (s *Server) regionFactsFor(acct *Account, app, routeFleet string, routesOK bool) appRegionFacts { |
| - stored, haPool, err := s.store.appPlacementRow(acct.ID, app) |
| +func (s *Server) regionFactsFor(ctx context.Context, acct *Account, app, routeFleet string, routesOK bool) appRegionFacts { |
| + stored, haPool, err := s.store.appPlacementRow(ctx, acct.ID, app) |
| if err != nil { |
| log.Printf("console: region labels %s/%s: placement: %v", acct.Sqid, app, err) |
| return appRegionFacts{} |
| @@ -198,7 +199,7 @@ func (s *Server) regionFactsFor(acct *Account, app, routeFleet string, routesOK |
| if name, ok := registry.FleetPlacement(placed); ok { |
| return appRegionFacts{Known: true, Fleet: name, Label: regionlabel.ForCode(placed, s.regionHome(), s.regionNames())} |
| } |
| - region, source, err := s.appRegion(acct.ID, app) |
| + region, source, err := s.appRegion(ctx, acct.ID, app) |
| if err != nil { |
| log.Printf("console: region labels %s/%s: region: %v", acct.Sqid, app, err) |
| return appRegionFacts{} |
diff --git a/internal/console/regionfacts_test.go b/internal/console/regionfacts_test.go| index d6fd70db7..d9d91f22c 100644 |
| --- a/internal/console/regionfacts_test.go |
| +++ b/internal/console/regionfacts_test.go |
| @@ -52,7 +52,7 @@ func TestRegionFactsByCase(t *testing.T) { |
| {"legacy", nil, false, "", "", ""}, |
| {"cart", nil, false, "fleet private", "This app runs on your fleet private.", ""}, // the store's placement needs no registry |
| } { |
| - f := fx.srv.regionFactsFor(acct, c.app, fleetFromRoutes(c.routes, fx.sqid, c.app), c.routesOK) |
| + f := fx.srv.regionFactsFor(context.Background(), acct, c.app, fleetFromRoutes(c.routes, fx.sqid, c.app), c.routesOK) |
| if f.Text() != c.text || f.Sentence() != c.sentence || f.SourceSentence() != c.source { |
| t.Errorf("%s (registry read %v): %q / %q / %q, want %q / %q / %q", c.app, c.routesOK, |
| f.Text(), f.Sentence(), f.SourceSentence(), c.text, c.sentence, c.source) |
diff --git a/internal/console/requestctx_test.go b/internal/console/requestctx_test.go| new file mode 100644 |
| index 000000000..912c93ede |
| --- /dev/null |
| +++ b/internal/console/requestctx_test.go |
| @@ -0,0 +1,316 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http" |
| + "net/http/httptest" |
| + "runtime" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +// TestCancelledRequestLeavesTheConnectionQueue: the console store has one |
| +// SQLite connection, so a query with no context waits for it however long |
| +// the client that asked has been gone. Each signed-in door below is sent |
| +// while something else holds that connection; once the request is queued |
| +// for it, the client goes away. The request must give up its place and |
| +// return while the connection is still held, without the page's queries |
| +// running. |
| +// |
| +// A case with pauseAt is held up further in: the connection is taken only |
| +// once the request reaches that query (pauseDB), so the request is past |
| +// its bearer lookup and queued at the later one when the client goes. |
| +// |
| +// The wait is on the pool's own counter (the request is queued once |
| +// WaitCount moves), on pauseDB's signal and on the handler returning; the |
| +// timer only bounds a failure. |
| +func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + const person = "paul@keymail.dev" |
| + session, err := fx.st.CreateSession(person, "", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token := mintHostClaimToken(t, fx.st, person) |
| + service := serviceToken(t, fx.st, OpsAccountID, "ci", "kass", svcrole.Publish) |
| + cookie := func(r *http.Request) { r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session}) } |
| + bearer := func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) } |
| + serviceBearer := func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+service) } |
| + for _, c := range []struct { |
| + name, path string |
| + auth func(*http.Request) |
| + pauseAt string |
| + }{ |
| + {"app list", fx.path("/"), cookie, ""}, |
| + {"app page", fx.path("/apps/kass"), cookie, ""}, |
| + {"instances", fx.path("/apps/kass/instances"), cookie, ""}, |
| + {"cli door", "/api/cli/apps", bearer, ""}, |
| + {"cli door, service credential", "/api/cli/apps", serviceBearer, ""}, |
| + // serviceBinding's account read, after the bearer resolved. |
| + {"cli door, service binding", "/api/cli/apps", serviceBearer, "FROM accounts WHERE id = ?"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + // The door answers this caller when nothing is in its way. |
| + req := httptest.NewRequest(http.MethodGet, c.path, nil) |
| + c.auth(req) |
| + rec := httptest.NewRecorder() |
| + fx.srv.ServeHTTP(rec, req) |
| + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "kass") { |
| + t.Fatalf("GET %s = %d with the connection free, want 200 naming kass:\n%s", c.path, rec.Code, rec.Body) |
| + } |
| + |
| + var held *sql.Conn |
| + released := false |
| + release := func() { |
| + if held != nil && !released { |
| + released = true |
| + held.Close() |
| + } |
| + } |
| + defer release() |
| + hold := func() { |
| + var err error |
| + if held, err = fx.st.rawPool.Conn(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var pause *pauseDB |
| + if c.pauseAt != "" { |
| + pause = &pauseDB{sqlHandle: fx.st.db, at: c.pauseAt, reached: make(chan struct{}), proceed: make(chan struct{})} |
| + fx.st.db = pause |
| + defer func() { fx.st.db = pause.sqlHandle }() |
| + } else { |
| + hold() |
| + } |
| + |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + req = httptest.NewRequest(http.MethodGet, c.path, nil).WithContext(ctx) |
| + c.auth(req) |
| + rec = httptest.NewRecorder() |
| + waits := fx.st.rawPool.Stats().WaitCount |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + fx.srv.ServeHTTP(rec, req) |
| + }() |
| + bound := time.After(10 * time.Second) |
| + if pause != nil { |
| + select { |
| + case <-pause.reached: |
| + case <-done: |
| + t.Fatalf("GET %s returned %d before it reached %q", c.path, rec.Code, c.pauseAt) |
| + case <-bound: |
| + t.Fatalf("GET %s never reached %q", c.path, c.pauseAt) |
| + } |
| + hold() |
| + waits = fx.st.rawPool.Stats().WaitCount |
| + close(pause.proceed) |
| + } |
| + for fx.st.rawPool.Stats().WaitCount == waits { |
| + select { |
| + case <-done: |
| + t.Fatalf("GET %s returned %d before it queued for the connection", c.path, rec.Code) |
| + case <-bound: |
| + t.Fatalf("GET %s never queued for the connection", c.path) |
| + default: |
| + runtime.Gosched() |
| + } |
| + } |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-bound: |
| + release() |
| + <-done |
| + t.Fatalf("GET %s kept its place behind the held connection after the client went away", c.path) |
| + } |
| + if released { |
| + t.Fatal("the held connection was let go before the request returned") |
| + } |
| + // It gave up at the query it was queued at: the session or |
| + // bearer lookup reads as signed out, the service binding as no |
| + // binding, and nothing of the page was served. |
| + if rec.Code == http.StatusOK && strings.Contains(rec.Body.String(), "kass") { |
| + t.Fatalf("GET %s served the page after the client went away:\n%s", c.path, rec.Body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestSignedInPagesQueryUnderTheRequestContext runs the doors above with |
| +// the store's handle wrapped, and fails any query a door makes with no |
| +// context, or under one that is not the request's (context.Background() |
| +// where the request's was in reach). Plans are on and the fixture account |
| +// is not exempt, so the plan banner's reads run too. |
| +func TestSignedInPagesQueryUnderTheRequestContext(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + fx.st.planExemptID = 0 |
| + const person = "paul@keymail.dev" |
| + session, err := fx.st.CreateSession(person, "", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token := mintHostClaimToken(t, fx.st, person) |
| + service := serviceToken(t, fx.st, OpsAccountID, "ci", "kass", svcrole.Publish) |
| + check := &requestCtxDB{sqlHandle: fx.st.db} |
| + fx.st.db = check |
| + t.Cleanup(func() { fx.st.db = check.sqlHandle }) |
| + for _, c := range []struct { |
| + name, path, auth string |
| + }{ |
| + {"landing", "/", session}, |
| + {"app list", fx.path("/"), session}, |
| + {"app page", fx.path("/apps/kass"), session}, |
| + {"instances", fx.path("/apps/kass/instances"), session}, |
| + {"cli door", "/api/cli/apps", "Bearer " + token}, |
| + {"cli door, service credential", "/api/cli/apps", "Bearer " + service}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + ctx := context.WithValue(context.Background(), requestCtxMark{}, c.path) |
| + req := httptest.NewRequest(http.MethodGet, c.path, nil).WithContext(ctx) |
| + if strings.HasPrefix(c.auth, "Bearer ") { |
| + req.Header.Set("Authorization", c.auth) |
| + } else { |
| + req.AddCookie(&http.Cookie{Name: sessionCookie, Value: c.auth}) |
| + } |
| + check.reset() |
| + rec := httptest.NewRecorder() |
| + fx.srv.ServeHTTP(rec, req) |
| + if rec.Code != http.StatusOK && rec.Code != http.StatusFound { |
| + t.Fatalf("GET %s = %d:\n%s", c.path, rec.Code, rec.Body) |
| + } |
| + queries, bad := check.result() |
| + if queries == 0 { |
| + t.Fatalf("GET %s made no queries through the store; the check saw nothing", c.path) |
| + } |
| + for _, b := range bad { |
| + t.Errorf("GET %s: %s", c.path, b) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// requestCtxMark marks a test request's context. |
| +type requestCtxMark struct{} |
| + |
| +// requestCtxDB is the store's handle with every call checked: a method |
| +// with no context, or a context without requestCtxMark, is recorded. |
| +type requestCtxDB struct { |
| + sqlHandle |
| + mu sync.Mutex |
| + queries int |
| + bad []string |
| +} |
| + |
| +func (d *requestCtxDB) reset() { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.queries, d.bad = 0, nil |
| +} |
| + |
| +func (d *requestCtxDB) result() (int, []string) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + return d.queries, append([]string(nil), d.bad...) |
| +} |
| + |
| +func (d *requestCtxDB) note(ctx context.Context, method, query string) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.queries++ |
| + q := strings.Join(strings.Fields(query), " ") |
| + if len(q) > 90 { |
| + q = q[:90] + "..." |
| + } |
| + switch { |
| + case ctx == nil: |
| + d.bad = append(d.bad, method+" with no context: "+q) |
| + case ctx.Value(requestCtxMark{}) == nil: |
| + d.bad = append(d.bad, method+" under a context that is not the request's: "+q) |
| + } |
| +} |
| + |
| +func (d *requestCtxDB) Exec(query string, args ...any) (sql.Result, error) { |
| + d.note(nil, "Exec", query) |
| + return d.sqlHandle.Exec(query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { |
| + d.note(ctx, "ExecContext", query) |
| + return d.sqlHandle.ExecContext(ctx, query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) Query(query string, args ...any) (*sql.Rows, error) { |
| + d.note(nil, "Query", query) |
| + return d.sqlHandle.Query(query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { |
| + d.note(ctx, "QueryContext", query) |
| + return d.sqlHandle.QueryContext(ctx, query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) QueryRow(query string, args ...any) *sql.Row { |
| + d.note(nil, "QueryRow", query) |
| + return d.sqlHandle.QueryRow(query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { |
| + d.note(ctx, "QueryRowContext", query) |
| + return d.sqlHandle.QueryRowContext(ctx, query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) Begin() (*sql.Tx, error) { |
| + d.note(nil, "Begin", "") |
| + return d.sqlHandle.Begin() |
| +} |
| + |
| +func (d *requestCtxDB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) { |
| + d.note(ctx, "BeginTx", "") |
| + return d.sqlHandle.BeginTx(ctx, opts) |
| +} |
| + |
| +func (d *requestCtxDB) Prepare(query string) (*sql.Stmt, error) { |
| + d.note(nil, "Prepare", query) |
| + return d.sqlHandle.Prepare(query) |
| +} |
| + |
| +func (d *requestCtxDB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { |
| + d.note(ctx, "PrepareContext", query) |
| + return d.sqlHandle.PrepareContext(ctx, query) |
| +} |
| + |
| +// pauseDB holds up the first query containing at: it says so on reached |
| +// and goes on to the store only once proceed is closed. |
| +type pauseDB struct { |
| + sqlHandle |
| + at string |
| + once sync.Once |
| + reached, proceed chan struct{} |
| +} |
| + |
| +func (d *pauseDB) wait(query string) { |
| + if strings.Contains(query, d.at) { |
| + d.once.Do(func() { |
| + close(d.reached) |
| + <-d.proceed |
| + }) |
| + } |
| +} |
| + |
| +func (d *pauseDB) QueryRow(query string, args ...any) *sql.Row { |
| + d.wait(query) |
| + return d.sqlHandle.QueryRow(query, args...) |
| +} |
| + |
| +func (d *pauseDB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { |
| + d.wait(query) |
| + return d.sqlHandle.QueryRowContext(ctx, query, args...) |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 48624b1e1..9311c0548 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -2446,10 +2446,9 @@ type page struct { |
| BillingPickQuery string |
| // BillingNav shows the account nav's billing link: billing is on. |
| BillingNav bool |
| - // planSeen are the over rows behind PlanNotices when the viewer owns |
| + // planNotice is the over rows behind PlanNotices when the viewer owns |
| // the account; render records them as notice once the page is written. |
| - planSeen []capState |
| - planAcctID int64 |
| + planNotice bannerNotice |
| FlashErr string // one-shot error notice |
| Apps []appRow // account home |
| @@ -2904,7 +2903,7 @@ func (s *Server) render(w http.ResponseWriter, status int, name string, p page) |
| if s.writeTemplate(w, status, name, p) != nil { |
| return |
| } |
| - s.recordBannerNotice(p.planAcctID, p.planSeen, time.Now()) // plans 4a: the banner was served |
| + s.recordBannerNotice(p.planNotice, time.Now()) // plans 4a: the banner was served |
| } |
| // templateBufs holds the buffers writeTemplate renders into. One grown past |
| @@ -2975,12 +2974,12 @@ func (s *Server) session(r *http.Request) (address, rawToken string, ok bool) { |
| } |
| end := perf.Span(r, "db") |
| now := time.Now() |
| - addr, ok := s.store.SessionAddress(c.Value, now) |
| + addr, ok := s.store.SessionAddress(r.Context(), c.Value, now) |
| end() |
| if !ok { |
| return "", "", false |
| } |
| - s.noteSeen(addr, now) |
| + s.noteSeen(r.Context(), addr, now) |
| return addr, c.Value, true |
| } |
| @@ -3060,7 +3059,7 @@ func (s *Server) redirectToCurrentAccount(w http.ResponseWriter, r *http.Request |
| return |
| } |
| seg := sqid |
| - if accts, err := s.store.AccountsFor(addr); err == nil { |
| + if accts, err := s.store.AccountsForContext(r.Context(), addr); err == nil { |
| for i := range accts { |
| if accts[i].Sqid == sqid { |
| seg = preferredSeg(accts, &accts[i]) |
| @@ -3080,8 +3079,11 @@ func (s *Server) redirectToCurrentAccount(w http.ResponseWriter, r *http.Request |
| // minting) give one personal account, not two. It runs detached from the |
| // request's cancellation, bounded by landingMintTimeout: a browser that gives |
| // up mid-mint must not leave a manifest in the bucket with no console row. |
| +// The membership reads that decide whether to mint are detached too: |
| +// a landing whose request is already gone still finds or mints the account, |
| +// so the next sign-in lands on it rather than on a half-made one. |
| func (s *Server) currentAccount(ctx context.Context, addr string) (string, error) { |
| - a, err := s.memberAccount(addr) |
| + a, err := s.memberAccount(context.WithoutCancel(ctx), addr) |
| if err != nil { |
| return "", err |
| } |
| @@ -3091,7 +3093,7 @@ func (s *Server) currentAccount(ctx context.Context, addr string) (string, error |
| mu := s.landingLock(addr) |
| mu.Lock() |
| defer mu.Unlock() |
| - if a, err := s.memberAccount(addr); err != nil { |
| + if a, err := s.memberAccount(context.WithoutCancel(ctx), addr); err != nil { |
| return "", err |
| } else if a != nil { |
| return a.Sqid, nil |
| @@ -3114,14 +3116,14 @@ const landingMintTimeout = 30 * time.Second |
| // by creation order, else nil. Split out because pages that merely want the |
| // header's account context — /accounts/new — must not create an account as a |
| // side effect of being looked at. Only landing mints. |
| -func (s *Server) memberAccount(addr string) (*Account, error) { |
| - if id, err := s.store.LastAccount(addr); err != nil { |
| +func (s *Server) memberAccount(ctx context.Context, addr string) (*Account, error) { |
| + if id, err := s.store.LastAccount(ctx, addr); err != nil { |
| return nil, err |
| } else if id != 0 { |
| - if role, err := s.store.Role(id, addr); err != nil { |
| + if role, err := s.store.RoleContext(ctx, id, addr); err != nil { |
| return nil, err |
| } else if role != "" { |
| - a, err := s.store.AccountByID(id) |
| + a, err := s.store.AccountByIDContext(ctx, id) |
| if err != nil { |
| return nil, err |
| } |
| @@ -3131,7 +3133,7 @@ func (s *Server) memberAccount(addr string) (*Account, error) { |
| } |
| } |
| } |
| - accts, err := s.store.AccountsFor(addr) |
| + accts, err := s.store.AccountsForContext(ctx, addr) |
| if err != nil { |
| return nil, err |
| } |
| @@ -3180,7 +3182,7 @@ func (s *Server) mintAccount(ctx context.Context, name, ownerAddr string) (*Acco |
| "locally: %v — accounts/%s/account.json is stranded with no owner", sqid, id, name, err, sqid) |
| return nil, err |
| } |
| - if err := s.store.SetLastAccount(ownerAddr, id); err != nil { |
| + if err := s.store.SetLastAccount(ctx, ownerAddr, id); err != nil { |
| log.Printf("console: set last account for %s: %v", ownerAddr, err) |
| } |
| acct := &Account{ID: id, Sqid: sqid, Name: name, Role: RoleOwner, CreatedAt: now} |
| @@ -3208,7 +3210,7 @@ func (s *Server) account(w http.ResponseWriter, r *http.Request) (addr, raw stri |
| return "", "", nil, "", false |
| } |
| end := perf.Span(r, "db") |
| - accts, err := s.store.AccountsFor(addr) |
| + accts, err := s.store.AccountsForContext(r.Context(), addr) |
| end() |
| if err != nil { |
| log.Printf("console: account lookup: %v", err) |
| @@ -3294,7 +3296,7 @@ func (s *Server) handleNewAccountForm(w http.ResponseWriter, r *http.Request) { |
| } |
| p := page{Title: "New account", Address: addr, CSRF: csrfToken(raw), MobileParent: &navLink{Label: "Accounts", Href: "/accounts#nav-new"}} |
| p.Flash, p.FlashErr = s.takeFlash(w, r) |
| - if accts, err := s.store.AccountsFor(addr); err != nil { |
| + if accts, err := s.store.AccountsForContext(r.Context(), addr); err != nil { |
| log.Printf("console: switcher: %v", err) |
| } else { |
| p.Accounts = accts |
| @@ -3305,7 +3307,7 @@ func (s *Server) handleNewAccountForm(w http.ResponseWriter, r *http.Request) { |
| // The header chrome wants an account to name in the switcher's trigger. |
| // memberAccount, not currentAccount: looking at this page must never mint. |
| // A user with no memberships at all simply gets the wordmark header. |
| - if a, err := s.memberAccount(addr); err != nil { |
| + if a, err := s.memberAccount(r.Context(), addr); err != nil { |
| log.Printf("console: new-account chrome: %v", err) |
| } else if a != nil { |
| p.Account = a |
| @@ -3665,7 +3667,7 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| accountID := a.ID |
| - if err := s.store.SetLastAccount(addr, accountID); err != nil { |
| + if err := s.store.SetLastAccount(r.Context(), addr, accountID); err != nil { |
| log.Printf("console: set last account: %v", err) |
| } |
| s.auditInviteAccepted(a, addr) |
| @@ -4102,7 +4104,7 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) { |
| p.Welcome = true |
| s.clearCookie(w, welcomeCookie) |
| } |
| - apps, err := s.store.AppsIn(acct.ID) |
| + apps, err := s.store.AppsInContext(r.Context(), acct.ID) |
| if err != nil { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.") |
| return |
| @@ -4118,14 +4120,14 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) { |
| } |
| // Linked apps are labelled by their home. Best-effort: a failed read |
| // costs the label, never the page. |
| - homes, err := s.store.linkedAppHomes(acct.ID) |
| + homes, err := s.store.linkedAppHomes(r.Context(), acct.ID) |
| if err != nil { |
| log.Printf("console: app list %s: linked apps: %v", acct.Sqid, err) |
| } |
| for _, v := range views { |
| row := summarize(v, acct.Sqid) |
| // Assemble listed the registry: its rows give the legacy fleet. |
| - row.Region = s.regionFactsFor(acct, v.App, v.routeFleet, true) |
| + row.Region = s.regionFactsFor(r.Context(), acct, v.App, v.routeFleet, true) |
| row.Elsewhere = elsewhereCounts(v.Routes, acct.Sqid, row.Region) |
| if home, ok := homes[v.App]; ok { |
| row.ServedFrom = linkCopy(copyLD31, "home", home) |
| @@ -4137,7 +4139,7 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) { |
| } |
| } |
| // The viewer's stars, the expiries and the q filter (applist.go). |
| - if err := s.fillAppLists(&p, acct, addr, r.URL.Query().Get("q")); err != nil { |
| + if err := s.fillAppLists(r.Context(), &p, acct, addr, r.URL.Query().Get("q")); err != nil { |
| log.Printf("console: app list %s: %v", acct.Sqid, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.") |
| return |
| @@ -4145,12 +4147,12 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) { |
| } |
| // The Trash link, and only when there is something in it. Best-effort: a |
| // failed count costs a link, never the page. |
| - if trashed, err := s.store.TrashedAppsIn(acct.ID); err != nil { |
| + if trashed, err := s.store.TrashedAppsIn(r.Context(), acct.ID); err != nil { |
| log.Printf("console: trashed apps: %v", err) |
| } else { |
| p.TrashN = len(trashed) |
| } |
| - s.fillGettingStarted(&p, acct, addr, role, live) |
| + s.fillGettingStarted(r.Context(), &p, acct, addr, role, live) |
| s.render(w, http.StatusOK, "apps", p) |
| } |
| @@ -4231,7 +4233,7 @@ func (s *Server) handleAccountSettings(w http.ResponseWriter, r *http.Request) { |
| // the MRU, so signing in lands you back on the account you were last in. |
| func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, role string) page { |
| end := perf.Span(r, "db") |
| - if err := s.store.SetLastAccount(addr, acct.ID); err != nil { |
| + if err := s.store.SetLastAccount(r.Context(), addr, acct.ID); err != nil { |
| log.Printf("console: set last account: %v", err) |
| } |
| end() |
| @@ -4243,7 +4245,7 @@ func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, addr, raw s |
| } |
| p.Flash, p.FlashErr = s.takeFlash(w, r) |
| end = perf.Span(r, "db") |
| - accts, err := s.store.AccountsFor(addr) |
| + accts, err := s.store.AccountsForContext(r.Context(), addr) |
| end() |
| if err != nil { |
| log.Printf("console: switcher: %v", err) |
| @@ -4261,9 +4263,9 @@ func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, addr, raw s |
| p.Accounts[i].Seg = preferredSeg(p.Accounts, &p.Accounts[i]) |
| } |
| p.Nav = "/a/" + url.PathEscape(preferredSeg(p.Accounts, acct)) |
| - p.PlanNotices, p.planSeen = s.planBanner(acct, role, time.Now()) |
| - p.planAcctID = acct.ID |
| - if role == RoleOwner && s.planKeepOffered(acct) { |
| + p.PlanNotices, p.planNotice.seen = s.planBanner(r.Context(), acct, role, time.Now()) |
| + p.planNotice.ctx, p.planNotice.accountID = r.Context(), acct.ID |
| + if role == RoleOwner && s.planKeepOffered(r.Context(), acct) { |
| p.PlanKeepURL = "/a/" + url.PathEscape(acct.Sqid) + "/plan/keep" |
| p.PlanKeepLink = planKeepCopy["keep.link"] |
| } |
| @@ -4281,7 +4283,7 @@ func (s *Server) accountApp(w http.ResponseWriter, r *http.Request) (addr, raw s |
| } |
| app = r.PathValue("app") |
| end := perf.Span(r, "db") |
| - has, err := s.store.HasAppIn(acct.ID, app) |
| + has, err := s.store.HasAppInContext(r.Context(), acct.ID, app) |
| end() |
| if err != nil { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.") |
| @@ -4298,7 +4300,7 @@ func (s *Server) accountApp(w http.ResponseWriter, r *http.Request) (addr, raw s |
| return "", "", nil, "", "", false |
| } |
| if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| - if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + if ref := s.demoMutationRefusal(r.Context(), acct, app); ref != nil { |
| s.renderMessage(w, r, ref.Status, "Demo", ref.Msg) |
| return "", "", nil, "", "", false |
| } |
| @@ -4345,24 +4347,24 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa |
| p := s.accountPage(w, r, addr, raw, acct, role) |
| p.Title = app |
| p.AppName = app |
| - p.LinkedApp = s.linkedAppPage(acct, app) |
| + p.LinkedApp = s.linkedAppPage(r.Context(), acct, app) |
| if role == RoleOwner || role == RoleMember { |
| - p.HasClaimedSource, _ = s.store.hasClaimedSource(acct.ID, app) |
| + p.HasClaimedSource, _ = s.store.hasClaimedSource(r.Context(), acct.ID, app) |
| } |
| p.ActiveTab = tab |
| p.ActiveNav = "apps" |
| p.Detail = &views[0] |
| - p.StoredRegion = s.regionFactsFor(acct, app, views[0].routeFleet, true) |
| + p.StoredRegion = s.regionFactsFor(r.Context(), acct, app, views[0].routeFleet, true) |
| p.StoredElsewhere = elsewhereCounts(views[0].Routes, acct.Sqid, p.StoredRegion) |
| end := perf.Span(r, "db") |
| - life, err := s.store.AppLife(acct.ID, app) |
| + life, err := s.store.AppLifeContext(r.Context(), acct.ID, app) |
| end() |
| if err != nil { |
| log.Printf("console: app lifecycle %s/%s: %v", acct.Sqid, app, err) |
| } else if life != nil && life.Temporary() { |
| p.ExpiresAt = time.Unix(life.ExpiresAt, 0).UTC() |
| } |
| - if review, all, err := s.appAccountReview(addr, acct, app); err != nil { |
| + if review, all, err := s.appAccountReview(r.Context(), addr, acct, app); err != nil { |
| log.Printf("console: account review %s/%s: %v", acct.Sqid, app, err) |
| } else { |
| // The review itself reads the console box's registry: it is about |
| @@ -4573,7 +4575,7 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) { |
| } |
| p.Flow = assembleFlow(p.Detail, p.InstanceRows, latest, latestAt, p.Nav+"/apps/"+p.AppName+"/instances") |
| end := perf.Span(r, "db") |
| - events, err := s.store.Events(acct.ID, app, overviewActivityCap) |
| + events, err := s.store.EventsContext(r.Context(), acct.ID, app, overviewActivityCap) |
| end() |
| if err != nil { |
| log.Printf("console: events %s: %v", app, err) |
| @@ -4588,7 +4590,7 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) { |
| } else if len(pcs) > 0 { |
| // The frame's pipeline for the whole card: the rows show the quorum |
| // EXECUTION will require, not the one they were proposed under. |
| - p.Pending = s.pendingChangeViews(pcs, p.Detail.Pipeline) |
| + p.Pending = s.pendingChangeViews(r.Context(), pcs, p.Detail.Pipeline) |
| } |
| end = perf.Span(r, "s3") |
| wait := time.NewTimer(trafficWait(start, time.Now())) |
| @@ -4642,7 +4644,7 @@ func (s *Server) handleAppReleases(w http.ResponseWriter, r *http.Request) { |
| if err != nil { |
| log.Printf("console: pending changes %s/%s: %v", acct.Sqid, p.AppName, err) |
| } else if len(pcs) > 0 { |
| - p.Pending = s.pendingChangeViews(pcs, p.Detail.Pipeline) |
| + p.Pending = s.pendingChangeViews(r.Context(), pcs, p.Detail.Pipeline) |
| } |
| p.ReleaseSummary = assembleReleaseSummary(p.Detail.Channels, p.Detail.Routes, acct.Sqid) |
| p.PromoteChannels = promoteChannelOptions(p.Detail.Channels, p.Detail.Pipeline) |
diff --git a/internal/console/signinmethods_store_test.go b/internal/console/signinmethods_store_test.go| index 613031f41..a8580a229 100644 |
| --- a/internal/console/signinmethods_store_test.go |
| +++ b/internal/console/signinmethods_store_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "database/sql" |
| "errors" |
| "sync" |
| @@ -89,14 +90,14 @@ func TestResolveSignInCreatesPerson(t *testing.T) { |
| func TestResolveSignInExistingUserNoMethod(t *testing.T) { |
| s := openTestStore(t) |
| - if err := s.SetLastAccount("op@x.test", 7); err != nil { |
| + if err := s.SetLastAccount(context.Background(), "op@x.test", 7); err != nil { |
| t.Fatal(err) |
| } |
| m, created, err := s.ResolveSignIn("keymail", "op@x.test", time.Unix(1700000000, 0)) |
| if err != nil || created || m.Address != "op@x.test" { |
| t.Fatalf("ResolveSignIn = %+v, %v, %v", m, created, err) |
| } |
| - if id, err := s.LastAccount("op@x.test"); err != nil || id != 7 { |
| + if id, err := s.LastAccount(context.Background(), "op@x.test"); err != nil || id != 7 { |
| t.Fatalf("LastAccount = %d, %v", id, err) |
| } |
| assertSignInCounts(t, s, 1, 1) |
| @@ -210,7 +211,7 @@ func TestSignInMethodsReadOnly(t *testing.T) { |
| t.Fatalf("new person = %v, %v", got, err) |
| } |
| assertSignInCounts(t, s, 0, 0) |
| - if err := s.SetLastAccount("person@x.test", 7); err != nil { |
| + if err := s.SetLastAccount(context.Background(), "person@x.test", 7); err != nil { |
| t.Fatal(err) |
| } |
| if _, err := s.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, label, added_at) VALUES |
diff --git a/internal/console/signinmethods_test.go b/internal/console/signinmethods_test.go| index 9c9bd8dd9..929799ae0 100644 |
| --- a/internal/console/signinmethods_test.go |
| +++ b/internal/console/signinmethods_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "net/http" |
| "net/url" |
| "testing" |
| @@ -125,7 +126,7 @@ func TestSigninExistingUserNoMethodNotWelcomed(t *testing.T) { |
| if err := fx.st.CreateAccount(acctID, "cdef", "Demo", addr, time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| - if err := fx.st.SetLastAccount(addr, acctID); err != nil { |
| + if err := fx.st.SetLastAccount(context.Background(), addr, acctID); err != nil { |
| t.Fatal(err) |
| } |
| if methods, err := fx.st.SignInMethodsFor(addr); err != nil || len(methods) != 0 { |
| @@ -144,7 +145,7 @@ func TestSigninExistingUserNoMethodNotWelcomed(t *testing.T) { |
| if methods, err := fx.st.SignInMethodsFor(addr); err != nil || len(methods) != 1 { |
| t.Fatalf("methods after sign-in = %v, %v; want one", methods, err) |
| } |
| - if id, err := fx.st.LastAccount(addr); err != nil || id != acctID { |
| + if id, err := fx.st.LastAccount(context.Background(), addr); err != nil || id != acctID { |
| t.Fatalf("last account = %d, %v; want %d", id, err, acctID) |
| } |
| } |
diff --git a/internal/console/store.go b/internal/console/store.go| index 5a0f91b72..40a2bb177 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -1392,10 +1392,17 @@ func (s *Store) AccountBySqid(sqid string) (*Account, error) { |
| } |
| // AccountByID is AccountBySqid keyed the other way, for the MRU landing. |
| +// It is AccountByIDContext for callers with no request to follow. |
| func (s *Store) AccountByID(id int64) (*Account, error) { |
| + return s.AccountByIDContext(context.Background(), id) |
| +} |
| + |
| +// AccountByIDContext is AccountByID under the caller's context, so a |
| +// request that goes away stops waiting for the one connection. |
| +func (s *Store) AccountByIDContext(ctx context.Context, id int64) (*Account, error) { |
| var a Account |
| var created int64 |
| - err := s.db.QueryRow(`SELECT id, sqid, name, created_at FROM accounts WHERE id = ? AND deleted_at = 0`, id). |
| + err := s.db.QueryRowContext(ctx, `SELECT id, sqid, name, created_at FROM accounts WHERE id = ? AND deleted_at = 0`, id). |
| Scan(&a.ID, &a.Sqid, &a.Name, &created) |
| if err == sql.ErrNoRows { |
| return nil, nil |
| @@ -1436,9 +1443,16 @@ func (s *Store) AccountAnyBySqid(sqid string) (*Account, bool, error) { |
| // AccountsFor returns the accounts address is a member of, in creation order |
| // — the switcher's list, and the "your first membership" fallback when there |
| // is no MRU history. Ordered by created_at then id so two accounts created in |
| -// the same second still order deterministically. |
| +// the same second still order deterministically. It is AccountsForContext |
| +// for callers with no request to follow. |
| func (s *Store) AccountsFor(address string) ([]Account, error) { |
| - rows, err := s.db.Query(`SELECT a.id, a.sqid, a.name, a.created_at, m.role |
| + return s.AccountsForContext(context.Background(), address) |
| +} |
| + |
| +// AccountsForContext is AccountsFor under the caller's context: the gate on |
| +// every account page asks it. |
| +func (s *Store) AccountsForContext(ctx context.Context, address string) ([]Account, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT a.id, a.sqid, a.name, a.created_at, m.role |
| FROM accounts a JOIN memberships m ON m.account_id = a.id |
| WHERE m.address = ? AND a.deleted_at = 0 ORDER BY a.created_at, a.id`, address) |
| if err != nil { |
| @@ -1533,10 +1547,16 @@ func (s *Store) AccountTiers() (map[string]string, error) { |
| } |
| // Role is address's role in the account, "" when they are not a member. It is |
| -// the one permission check every account-scoped route makes. |
| +// the one permission check every account-scoped route makes. It is |
| +// RoleContext for callers with no request to follow. |
| func (s *Store) Role(accountID int64, address string) (string, error) { |
| + return s.RoleContext(context.Background(), accountID, address) |
| +} |
| + |
| +// RoleContext is Role under the caller's context. |
| +func (s *Store) RoleContext(ctx context.Context, accountID int64, address string) (string, error) { |
| var role string |
| - err := s.db.QueryRow(`SELECT role FROM memberships WHERE account_id = ? AND address = ?`, |
| + err := s.db.QueryRowContext(ctx, `SELECT role FROM memberships WHERE account_id = ? AND address = ?`, |
| accountID, address).Scan(&role) |
| if err == sql.ErrNoRows { |
| return "", nil |
| @@ -1672,8 +1692,8 @@ func lastOwnerGuard(tx *sql.Tx, accountID int64, address string) error { |
| // SetLastAccount records where a user was last, so signing in lands them |
| // back there. Upserts the users row: an invited address that has never |
| // signed in still gets a landing spot. |
| -func (s *Store) SetLastAccount(address string, accountID int64) error { |
| - _, err := s.db.Exec(`INSERT INTO users (address, created_at, last_account) VALUES (?, ?, ?) |
| +func (s *Store) SetLastAccount(ctx context.Context, address string, accountID int64) error { |
| + _, err := s.db.ExecContext(ctx, `INSERT INTO users (address, created_at, last_account) VALUES (?, ?, ?) |
| ON CONFLICT(address) DO UPDATE SET last_account = excluded.last_account`, |
| address, time.Now().Unix(), accountID) |
| return err |
| @@ -1681,9 +1701,9 @@ ON CONFLICT(address) DO UPDATE SET last_account = excluded.last_account`, |
| // LastAccount is the account id a user was last in, 0 when there is no |
| // history (a fresh user, or one whose only account was deleted). |
| -func (s *Store) LastAccount(address string) (int64, error) { |
| +func (s *Store) LastAccount(ctx context.Context, address string) (int64, error) { |
| var id int64 |
| - err := s.db.QueryRow(`SELECT last_account FROM users WHERE address = ?`, address).Scan(&id) |
| + err := s.db.QueryRowContext(ctx, `SELECT last_account FROM users WHERE address = ?`, address).Scan(&id) |
| if err == sql.ErrNoRows { |
| return 0, nil |
| } |
| @@ -1944,9 +1964,15 @@ func (s *Store) CreateAppInRegion(accountID int64, app, createdBy, region, sourc |
| } |
| // AppRegion reads an app's region and its source label. A missing row |
| -// reads as the home with no source. |
| +// reads as the home with no source. It is AppRegionContext for callers with |
| +// no request to follow. |
| func (s *Store) AppRegion(accountID int64, app string) (region, source string, err error) { |
| - err = s.db.QueryRow(`SELECT region, region_source FROM apps WHERE account_id = ? AND app = ?`, accountID, app). |
| + return s.AppRegionContext(context.Background(), accountID, app) |
| +} |
| + |
| +// AppRegionContext is AppRegion under the caller's context. |
| +func (s *Store) AppRegionContext(ctx context.Context, accountID int64, app string) (region, source string, err error) { |
| + err = s.db.QueryRowContext(ctx, `SELECT region, region_source FROM apps WHERE account_id = ? AND app = ?`, accountID, app). |
| Scan(®ion, &source) |
| if errors.Is(err, sql.ErrNoRows) { |
| return "", "", nil |
| @@ -2022,9 +2048,16 @@ WHERE p.region != '' AND p.deleted_at = 0 ORDER BY a.sqid, p.app`) |
| // filtered out — every door this feeds (API resolution, ship claim, account |
| // page listings) is a door a trashed app must vanish from automatically, |
| // without each caller having to remember to ask. TrashedAppsIn is the |
| -// dedicated listing for the Trash page itself. |
| +// dedicated listing for the Trash page itself. It is AppsInContext for |
| +// callers with no request to follow. |
| func (s *Store) AppsIn(accountID int64) ([]string, error) { |
| - rows, err := s.db.Query(`SELECT app FROM apps WHERE account_id = ? AND deleted_at = 0 ORDER BY app`, accountID) |
| + return s.AppsInContext(context.Background(), accountID) |
| +} |
| + |
| +// AppsInContext is AppsIn under the caller's context: the account home's |
| +// app list reads it. |
| +func (s *Store) AppsInContext(ctx context.Context, accountID int64) ([]string, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT app FROM apps WHERE account_id = ? AND deleted_at = 0 ORDER BY app`, accountID) |
| if err != nil { |
| return nil, err |
| } |
| @@ -2062,10 +2095,17 @@ func (s *Store) AppsIncludingTrashIn(accountID int64) ([]string, error) { |
| // HasAppIn reports whether an account already claims a LIVE app name. |
| // Filtered the same way as AppsIn: a trashed name still occupies the row (see |
| // CreateAppIn / the name-reservation rule) but must read as absent to a caller |
| -// asking "is this name in use right now". |
| +// asking "is this name in use right now". It is HasAppInContext for callers |
| +// with no request to follow. |
| func (s *Store) HasAppIn(accountID int64, app string) (bool, error) { |
| + return s.HasAppInContext(context.Background(), accountID, app) |
| +} |
| + |
| +// HasAppInContext is HasAppIn under the caller's context: the gate on every |
| +// app page asks it. |
| +func (s *Store) HasAppInContext(ctx context.Context, accountID int64, app string) (bool, error) { |
| var n int |
| - err := s.db.QueryRow(`SELECT COUNT(*) FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`, |
| + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`, |
| accountID, app).Scan(&n) |
| return n > 0, err |
| } |
| @@ -2157,7 +2197,8 @@ func (s *Store) claimRawSetAppBuildProbe(accountID int64, app, path string) erro |
| // A born-HA row reads "" whatever its column says (effectivePlacement, the |
| // one placement rule). |
| func (s *Store) AppPlacement(accountID int64, app string) (string, error) { |
| - placement, haPool, err := s.appPlacementRow(accountID, app) |
| + // AppPlacement's callers carry no context yet. |
| + placement, haPool, err := s.appPlacementRow(context.Background(), accountID, app) |
| if err != nil { |
| return "", err |
| } |
| @@ -2165,9 +2206,9 @@ func (s *Store) AppPlacement(accountID int64, app string) (string, error) { |
| } |
| // appPlacementRow is the row's raw placement column and HA pool, for |
| -// effectivePlacement; a missing row reads "", "". |
| -func (s *Store) appPlacementRow(accountID int64, app string) (placement, haPool string, err error) { |
| - err = s.db.QueryRow(`SELECT placement, ha_pool FROM apps WHERE account_id = ? AND app = ?`, accountID, app). |
| +// effectivePlacement; a missing row reads "", "". It runs under ctx. |
| +func (s *Store) appPlacementRow(ctx context.Context, accountID int64, app string) (placement, haPool string, err error) { |
| + err = s.db.QueryRowContext(ctx, `SELECT placement, ha_pool FROM apps WHERE account_id = ? AND app = ?`, accountID, app). |
| Scan(&placement, &haPool) |
| if errors.Is(err, sql.ErrNoRows) { |
| return "", "", nil |
| @@ -2299,8 +2340,8 @@ type TrashedApp struct { |
| // TrashedAppsIn lists an account's trashed apps, sorted by name — the Trash |
| // page's listing, and the mirror image of AppsIn's "live only" filter. |
| -func (s *Store) TrashedAppsIn(accountID int64) ([]TrashedApp, error) { |
| - rows, err := s.db.Query(`SELECT app, deleted_at, purge_after FROM apps WHERE account_id = ? AND deleted_at != 0 ORDER BY app`, |
| +func (s *Store) TrashedAppsIn(ctx context.Context, accountID int64) ([]TrashedApp, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT app, deleted_at, purge_after FROM apps WHERE account_id = ? AND deleted_at != 0 ORDER BY app`, |
| accountID) |
| if err != nil { |
| return nil, err |
| @@ -2336,10 +2377,16 @@ func (s *Store) AppNameState(accountID int64, app string) (live, trashed bool, e |
| // HasTrashedAppIn reports whether an account holds a TRASHED row for app — |
| // the check the claim-once door uses to explain a refusal ("that name is in |
| -// the trash") rather than just saying no. |
| +// the trash") rather than just saying no. It is HasTrashedAppInContext for |
| +// callers with no request to follow. |
| func (s *Store) HasTrashedAppIn(accountID int64, app string) (bool, error) { |
| + return s.HasTrashedAppInContext(context.Background(), accountID, app) |
| +} |
| + |
| +// HasTrashedAppInContext is HasTrashedAppIn under the caller's context. |
| +func (s *Store) HasTrashedAppInContext(ctx context.Context, accountID int64, app string) (bool, error) { |
| var n int |
| - err := s.db.QueryRow(`SELECT COUNT(*) FROM apps WHERE account_id = ? AND app = ? AND deleted_at != 0`, |
| + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM apps WHERE account_id = ? AND app = ? AND deleted_at != 0`, |
| accountID, app).Scan(&n) |
| return n > 0, err |
| } |
| @@ -3036,10 +3083,10 @@ VALUES (?, ?, ?, ?, ?, ?, ?)`, |
| // SessionAddress resolves a raw session token to its address; ok is false |
| // for unknown or expired tokens. |
| -func (s *Store) SessionAddress(rawToken string, now time.Time) (string, bool) { |
| +func (s *Store) SessionAddress(ctx context.Context, rawToken string, now time.Time) (string, bool) { |
| var addr string |
| var exp int64 |
| - err := s.db.QueryRow(`SELECT address, expires_at FROM sessions WHERE token_hash = ?`, |
| + err := s.db.QueryRowContext(ctx, `SELECT address, expires_at FROM sessions WHERE token_hash = ?`, |
| hashToken(rawToken)).Scan(&addr, &exp) |
| if err != nil || now.Unix() > exp { |
| return "", false |
| @@ -3183,9 +3230,15 @@ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, accountID, app, address, activity.Action, |
| } |
| // Events returns one account's audit rows for an app, newest first, capped at |
| -// limit. |
| +// limit. It is EventsContext for callers with no request to follow. |
| func (s *Store) Events(accountID int64, app string, limit int) ([]Event, error) { |
| - rows, err := s.db.Query(`SELECT app, address, action, target_type, target, message, detail, created_at |
| + return s.EventsContext(context.Background(), accountID, app, limit) |
| +} |
| + |
| +// EventsContext is Events under the caller's context: the app overview's |
| +// activity strip reads it. |
| +func (s *Store) EventsContext(ctx context.Context, accountID int64, app string, limit int) ([]Event, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT app, address, action, target_type, target, message, detail, created_at |
| FROM audit WHERE account_id = ? AND app = ? ORDER BY id DESC LIMIT ?`, accountID, app, limit) |
| if err != nil { |
| return nil, err |
diff --git a/internal/console/store_test.go b/internal/console/store_test.go| index 38d36bd80..3e7e03770 100644 |
| --- a/internal/console/store_test.go |
| +++ b/internal/console/store_test.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "fmt" |
| "path/filepath" |
| @@ -83,19 +84,19 @@ func TestSessions(t *testing.T) { |
| if raw == "" { |
| t.Fatal("empty raw session token") |
| } |
| - if addr, ok := s.SessionAddress(raw, now.Add(time.Hour)); !ok || addr != "paul@keymail.dev" { |
| + if addr, ok := s.SessionAddress(context.Background(), raw, now.Add(time.Hour)); !ok || addr != "paul@keymail.dev" { |
| t.Fatalf("SessionAddress = %q %v, want paul@keymail.dev true", addr, ok) |
| } |
| - if _, ok := s.SessionAddress("not-a-token", now); ok { |
| + if _, ok := s.SessionAddress(context.Background(), "not-a-token", now); ok { |
| t.Fatal("bogus token resolved") |
| } |
| - if _, ok := s.SessionAddress(raw, now.Add(SessionTTL+time.Minute)); ok { |
| + if _, ok := s.SessionAddress(context.Background(), raw, now.Add(SessionTTL+time.Minute)); ok { |
| t.Fatal("expired session resolved") |
| } |
| if err := s.DeleteSession(raw); err != nil { |
| t.Fatal(err) |
| } |
| - if _, ok := s.SessionAddress(raw, now); ok { |
| + if _, ok := s.SessionAddress(context.Background(), raw, now); ok { |
| t.Fatal("deleted session resolved") |
| } |
| } |
| @@ -114,7 +115,7 @@ func TestPurgeExpired(t *testing.T) { |
| if err := s.PurgeExpired(now.Add(SessionTTL + time.Hour)); err != nil { |
| t.Fatal(err) |
| } |
| - if _, ok := s.SessionAddress(raw, now); ok { |
| + if _, ok := s.SessionAddress(context.Background(), raw, now); ok { |
| t.Fatal("purged session still resolves at an in-window time") |
| } |
| if _, ok := s.TakeConfirmation(conf, now); ok { |
| @@ -458,7 +459,7 @@ func TestTrashAppRowRoundTrip(t *testing.T) { |
| if has, err := s.HasTrashedAppIn(acct, "zephyr"); err != nil || !has { |
| t.Fatalf("HasTrashedAppIn after trash = %v %v, want true", has, err) |
| } |
| - trashed, err := s.TrashedAppsIn(acct) |
| + trashed, err := s.TrashedAppsIn(context.Background(), acct) |
| if err != nil || len(trashed) != 1 || trashed[0].App != "zephyr" { |
| t.Fatalf("TrashedAppsIn = %+v %v, want one zephyr row", trashed, err) |
| } |
| @@ -475,7 +476,7 @@ func TestTrashAppRowRoundTrip(t *testing.T) { |
| if err := s.TrashAppRow(acct, "zephyr", later); err != nil { |
| t.Fatal(err) |
| } |
| - trashed, err = s.TrashedAppsIn(acct) |
| + trashed, err = s.TrashedAppsIn(context.Background(), acct) |
| if err != nil || len(trashed) != 1 || !trashed[0].DeletedAt.Equal(time.Unix(now.Unix(), 0).UTC()) { |
| t.Fatalf("second TrashAppRow moved the timestamp: %+v %v", trashed, err) |
| } |
| @@ -689,7 +690,7 @@ func TestReapAccountClearsAndMarks(t *testing.T) { |
| if _, err := s.CreateInvite(id, "carol@keymail.dev", "paul@keymail.dev", now); err != nil { |
| t.Fatal(err) |
| } |
| - if err := s.SetLastAccount("bob@keymail.dev", id); err != nil { |
| + if err := s.SetLastAccount(context.Background(), "bob@keymail.dev", id); err != nil { |
| t.Fatal(err) |
| } |
| @@ -706,13 +707,13 @@ func TestReapAccountClearsAndMarks(t *testing.T) { |
| if apps, err := s.AppsIn(id); err != nil || len(apps) != 0 { |
| t.Fatalf("AppsIn after reap = %v %v, want empty", apps, err) |
| } |
| - if trashed, err := s.TrashedAppsIn(id); err != nil || len(trashed) != 0 { |
| + if trashed, err := s.TrashedAppsIn(context.Background(), id); err != nil || len(trashed) != 0 { |
| t.Fatalf("TrashedAppsIn after reap = %v %v, want empty — reap deletes app rows, it does not trash them", trashed, err) |
| } |
| if invites, err := s.PendingInvites(id); err != nil || len(invites) != 0 { |
| t.Fatalf("PendingInvites after reap = %v %v, want empty", invites, err) |
| } |
| - if last, err := s.LastAccount("bob@keymail.dev"); err != nil || last != 0 { |
| + if last, err := s.LastAccount(context.Background(), "bob@keymail.dev"); err != nil || last != 0 { |
| t.Fatalf("LastAccount after reap = %d %v, want 0", last, err) |
| } |
| if a, err := s.AccountBySqid(sqid); err != nil || a != nil { |
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go| index caa411545..ba73000c8 100644 |
| --- a/internal/console/svcprincipal.go |
| +++ b/internal/console/svcprincipal.go |
| @@ -102,14 +102,21 @@ var ErrNoServicePrincipal = errors.New("console: no such credential") |
| // row — for a role name this binary does not recognise: a caller that reads |
| // "unparseable" as "no authority" would still be wrong if this returned a |
| // role-less service principal instead of refusing outright, so it refuses. |
| +// It is CLIPrincipalContext for callers with no request to follow. |
| func (s *Store) CLIPrincipal(rawToken string, now time.Time) (Principal, bool) { |
| + return s.CLIPrincipalContext(context.Background(), rawToken, now) |
| +} |
| + |
| +// CLIPrincipalContext is CLIPrincipal under the caller's context: every CLI |
| +// door's gate resolves its bearer with it. |
| +func (s *Store) CLIPrincipalContext(ctx context.Context, rawToken string, now time.Time) (Principal, bool) { |
| if rawToken == "" { |
| return Principal{}, false |
| } |
| hash := hashToken(rawToken) |
| var storedHash, addr, kind, app, role, name, rungs, credID, commands, teamScope string |
| var accountID, expires, revoked int64 |
| - err := s.db.QueryRow(`SELECT token_hash, address, kind, account_id, app, role, name, expires_at, revoked_at, rungs, |
| + err := s.db.QueryRowContext(ctx, `SELECT token_hash, address, kind, account_id, app, role, name, expires_at, revoked_at, rungs, |
| credential_id, commands, scope |
| FROM cli_tokens WHERE token_hash = ?`, hash). |
| Scan(&storedHash, &addr, &kind, &accountID, &app, &role, &name, &expires, &revoked, &rungs, &credID, &commands, &teamScope) |
| @@ -210,7 +217,7 @@ FROM cli_tokens WHERE token_hash = ?`, hash). |
| // A row carrying an app, a role or any scope column is not one |
| // this console wrote. No Address: it speaks for no person. |
| if accountID == 0 || app != "" || role != "" || rungs != "" || commands != "" || teamScope != "" || |
| - !s.linkPrincipalLive(hash, accountID, name) { |
| + !s.linkPrincipalLive(ctx, hash, accountID, name) { |
| return Principal{}, false |
| } |
| p = Principal{Kind: PrincipalLink, AccountID: accountID, LinkID: name} |
| @@ -219,7 +226,7 @@ FROM cli_tokens WHERE token_hash = ?`, hash). |
| } |
| // Best-effort: "last used" is for the owner's benefit on the tokens page, |
| // and a failed write must not fail the request it is annotating. |
| - s.db.Exec(`UPDATE cli_tokens SET last_used = ? WHERE token_hash = ?`, now.Unix(), hash) |
| + s.db.ExecContext(ctx, `UPDATE cli_tokens SET last_used = ? WHERE token_hash = ?`, now.Unix(), hash) |
| return p, true |
| } |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 51836b3d9..3493b034f 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -1525,7 +1525,7 @@ func TestAuthCLIFamilyResolvesOnlyPersons(t *testing.T) { |
| } |
| assertNoLinkResolver(t, src, d.pattern, fd.Body, map[string]bool{}) |
| } |
| - if lr := src.funcs["linkRoute"]; lr == nil || !callsSelector(lr.Body, "CLIPrincipal") { |
| + if lr := src.funcs["linkRoute"]; lr == nil || !callsSelector(lr.Body, "CLIPrincipal") && !callsSelector(lr.Body, "CLIPrincipalContext") { |
| t.Error("linkRoute does not resolve the bearer through CLIPrincipal") |
| } |
| @@ -1557,7 +1557,8 @@ func assertResolvesOnlyPersons(t *testing.T, src *cliSource, what string, fd *as |
| // assertBodyResolvesOnlyPersons fails if a handler outside /api/cli/ resolves |
| // a bearer by any route other than cliUser. CLIPrincipal answers for a |
| -// SERVICE credential and CLITokenAddress is the raw resolver cliUser wraps; |
| +// SERVICE credential and CLITokenAddress is the raw resolver cliUser wraps |
| +// (each with its ...Context form, which is the same resolver); |
| // a handler over here calling either one has stopped being person-only, and |
| // that is precisely the drift this catches. It matches identifiers, not |
| // only selectors: principalFrom is a package function, so a call of it is |
| @@ -1573,7 +1574,7 @@ func assertBodyResolvesOnlyPersons(t *testing.T, src *cliSource, what string, bo |
| return true |
| } |
| switch id.Name { |
| - case "CLIPrincipal", "CLITokenAddress", "principalFrom": |
| + case "CLIPrincipal", "CLIPrincipalContext", "CLITokenAddress", "CLITokenAddressContext", "principalFrom": |
| t.Errorf("%s: resolves a bearer through %s at %s — the /auth/cli/ family must go through cliUser, which answers only for a person", |
| what, id.Name, src.fset.Position(id.Pos())) |
| } |
| @@ -1583,7 +1584,8 @@ func assertBodyResolvesOnlyPersons(t *testing.T, src *cliSource, what string, bo |
| // assertNoLinkResolver fails if body, or a (*Server) method or package |
| // function it calls (transitively, within the package), resolves a bearer: |
| -// CLIPrincipal, CLITokenAddress, cliUser or bearer, or reads the CLI gate's |
| +// CLIPrincipal, CLITokenAddress (or either's ...Context form), cliUser or |
| +// bearer, or reads the CLI gate's |
| // principal (principalFrom). seen stops the descent at a function already |
| // read. |
| func assertNoLinkResolver(t *testing.T, src *cliSource, what string, body *ast.BlockStmt, seen map[string]bool) { |
| @@ -1602,7 +1604,7 @@ func assertNoLinkResolver(t *testing.T, src *cliSource, what string, body *ast.B |
| return true |
| } |
| switch name { |
| - case "CLIPrincipal", "CLITokenAddress", "cliUser", "bearer", "principalFrom": |
| + case "CLIPrincipal", "CLIPrincipalContext", "CLITokenAddress", "CLITokenAddressContext", "cliUser", "bearer", "principalFrom": |
| t.Errorf("%s: resolves a bearer through %s at %s; a link door reads linkRoute's principal (linkPrincipalFrom)", |
| what, name, src.fset.Position(n.Pos())) |
| case "linkRoute": |
diff --git a/internal/console/teamdoors.go b/internal/console/teamdoors.go| index 45983a6ab..b991fe8c6 100644 |
| --- a/internal/console/teamdoors.go |
| +++ b/internal/console/teamdoors.go |
| @@ -288,7 +288,7 @@ func (tv *teamView) claimInScope(ctx context.Context, s *Server, c *domains.Clai |
| // as either in or out of scope; a console with no bucket answers the |
| // instance family's 503 before any read. |
| func (s *Server) teamInScope(w http.ResponseWriter, r *http.Request, p Principal, target scopeTarget) (*teamView, bool) { |
| - acct, ok := s.serviceBinding(p) |
| + acct, ok := s.serviceBinding(r.Context(), p) |
| if !ok || r.PathValue("account") != acct.Sqid || p.App == "" || p.App != r.PathValue("app") { |
| http.NotFound(w, r) |
| return nil, false |
diff --git a/internal/console/tempstore.go b/internal/console/tempstore.go| index edcb52557..a22260aff 100644 |
| --- a/internal/console/tempstore.go |
| +++ b/internal/console/tempstore.go |
| @@ -50,9 +50,15 @@ func scanAppLife(sc interface{ Scan(...any) error }) (AppLife, error) { |
| return l, err |
| } |
| -// AppLife reads one row's lifecycle. (nil, nil) when there is no row. |
| +// AppLife reads one row's lifecycle. (nil, nil) when there is no row. It is |
| +// AppLifeContext for callers with no request to follow. |
| func (s *Store) AppLife(accountID int64, app string) (*AppLife, error) { |
| - l, err := scanAppLife(s.db.QueryRow(`SELECT `+appLifeCols+` FROM apps WHERE account_id = ? AND app = ?`, accountID, app)) |
| + return s.AppLifeContext(context.Background(), accountID, app) |
| +} |
| + |
| +// AppLifeContext is AppLife under the caller's context. |
| +func (s *Store) AppLifeContext(ctx context.Context, accountID int64, app string) (*AppLife, error) { |
| + l, err := scanAppLife(s.db.QueryRowContext(ctx, `SELECT `+appLifeCols+` FROM apps WHERE account_id = ? AND app = ?`, accountID, app)) |
| if errors.Is(err, sql.ErrNoRows) { |
| return nil, nil |
| } |
| @@ -62,8 +68,8 @@ func (s *Store) AppLife(accountID int64, app string) (*AppLife, error) { |
| return &l, nil |
| } |
| -func (s *Store) appLives(query string, args ...any) ([]AppLife, error) { |
| - rows, err := s.db.Query(query, args...) |
| +func (s *Store) appLives(ctx context.Context, query string, args ...any) ([]AppLife, error) { |
| + rows, err := s.db.QueryContext(ctx, query, args...) |
| if err != nil { |
| return nil, err |
| } |
| @@ -81,8 +87,8 @@ func (s *Store) appLives(query string, args ...any) ([]AppLife, error) { |
| // AppLivesIn is every row in the account, trashed included, by name: the |
| // input to GET /api/cli/apps/{account}/list (spec §7). |
| -func (s *Store) AppLivesIn(accountID int64) ([]AppLife, error) { |
| - return s.appLives(`SELECT `+appLifeCols+` FROM apps WHERE account_id = ? ORDER BY app`, accountID) |
| +func (s *Store) AppLivesIn(ctx context.Context, accountID int64) ([]AppLife, error) { |
| + return s.appLives(ctx, `SELECT `+appLifeCols+` FROM apps WHERE account_id = ? ORDER BY app`, accountID) |
| } |
| // liveTemporaryWhere is the cap's definition of a live temporary app (spec |
| @@ -92,7 +98,8 @@ const liveTemporaryWhere = `expires_at > 0 AND (deleted_at = 0 OR restoring = 1) |
| // LiveTemporaryApps lists the rows the cap counts, soonest expiry first, so |
| // the refusal can say what each one is and when it goes. |
| func (s *Store) LiveTemporaryApps(accountID int64) ([]AppLife, error) { |
| - return s.appLives(`SELECT `+appLifeCols+` FROM apps WHERE account_id = ? AND `+liveTemporaryWhere+` ORDER BY expires_at, app`, accountID) |
| + // Its one caller, temporaryCapCheck, carries no context yet. |
| + return s.appLives(context.Background(), `SELECT `+appLifeCols+` FROM apps WHERE account_id = ? AND `+liveTemporaryWhere+` ORDER BY expires_at, app`, accountID) |
| } |
| // CreateTemporaryAppIn is CreateTemporaryAppInRegion at the home, the way |
diff --git a/internal/provision/console_request_ctx_census_test.go b/internal/provision/console_request_ctx_census_test.go| new file mode 100644 |
| index 000000000..b2a4561d8 |
| --- /dev/null |
| +++ b/internal/provision/console_request_ctx_census_test.go |
| @@ -0,0 +1,40 @@ |
| +package provision |
| + |
| +// Record-write census re-pins for console request contexts (code-health |
| +// batch 3, branch console-request-ctx), layered on |
| +// configReceiptsWriteCensusInventory. No record write is added, moved or |
| +// reclassified, and no unit writes anything new. Two units changed only in |
| +// the guard calls ahead of their writes, which now take the caller's |
| +// context: |
| +// - Server.attachDomainAs (console): linkedRefusalFor(ctx, ...), so the |
| +// linked-app guard's store reads run under the attach's own context. |
| +// The CreateRecord write after it is unchanged. Kinds unchanged: |
| +// record-writer, key:CreateRecord. |
| +// - Server.placeAppTarget (console): demoMutationRefusal(ctx, ...) and |
| +// linkedRefusalFor(ctx, ...), the same two guards under the same |
| +// context; the demo guard used to build context.Background() itself. |
| +// The record listing and SetRecordRegion writes after them are |
| +// unchanged. Kinds unchanged: record-writer, |
| +// key:RecordsPrefix,key:SetRecordRegion. |
| +func consoleRequestCtxWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), configReceiptsWriteCensusInventory()...) |
| + repins := []censusEntry{ |
| + {"internal/console/domainattach.go", "Server.attachDomainAs", "record-writer", "key:CreateRecord", "73e9cac53c477550b622238e1da7b9f3907202fc22f12a07de728199b2db552d"}, |
| + {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "2315a4338ed343f7fedb9eea9ef8f6de6c56bdc3d2b4c6ddeb109eafde2d0a36"}, |
| + } |
| + for _, r := range repins { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("console-request-ctx re-pin changes the class or kinds of " + r.File + ":" + r.Unit) |
| + } |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("console-request-ctx re-pin of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 1be2b7055..8cf02f418 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := configReceiptsWriteCensusInventory() |
| + inventory := consoleRequestCtxWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |