carlos / platform Public

console: request context through the sign-in and membership gates

The console store runs every query on one SQLite connection, and the
gates every signed-in request passes called it with no context, so a
client that went away kept its queries queued ahead of live requests.
These gates now pass the request's context down to the database:

- the session cookie lookup and the hourly last-seen write
  (SessionAddress, TouchLastSeen, noteSeen);
- the CLI bearer gates (CLIPrincipalContext in cliRoute, linkRoute and
  sourceAdmission; CLITokenAddressContext in cliUser and moveOperator);
- account resolution and membership: account, memberAccount and the
  landing redirect (AccountsForContext, LastAccount, RoleContext,
  AccountByIDContext);
- the account page chrome: the MRU write, the switcher, the plan banner
  and keep link (planBanner, planStage, planCeilings, lapseStages,
  planKeepOffered over AccountPlanContext, CapStatesContext,
  LapseItemsContext, EffectiveLimitsContext), and the banner's notice
  write after render, under the page's planCtx;
- the app gate: HasAppInContext, the linked-app guard (linkedRefusalFor
  over appLinkIDContext and LinkByIDContext) and the demo mutation guard,
  which used context.Background() although its callers had a context.

A method with few callers takes ctx directly; one with many keeps its
old form as a thin wrapper over the new ...Context form, for callers
outside these paths. Two source guards learn the new names: the
plan-exempt census now lists EffectiveLimitsContext (EffectiveLimits is
its wrapper), and the bearer-resolver scans in svcroutes_test treat
CLIPrincipalContext and CLITokenAddressContext as the resolvers they
are, so a person-only or link door calling them still fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 39fc8896fcf7f56b50ea4d3643fb9d563fa779da parent 7e50962
52 files changed, +298 −186
  • internal/console/account_test.go +5 −5
  • internal/console/accountplans.go +10 −2
  • internal/console/apicli.go +1 −1
  • internal/console/apiinstancemove.go +1 −1
  • internal/console/apiinteractive.go +1 −1
  • internal/console/apilinks.go +2 −2
  • internal/console/app_source.go +1 −1
  • internal/console/appcopies.go +1 −1
  • internal/console/appregionset.go +1 −1
  • internal/console/authcli.go +4 −4
  • internal/console/authstore.go +8 −2
  • internal/console/claim_invariant_probes_nonapp_test.go +1 −1
  • internal/console/claim_invariant_probes_world_test.go +1 −1
  • internal/console/demo_claim_target_test.go +2 −2
  • internal/console/demo_domains.go +3 −3
  • internal/console/domainattach.go +1 −1
  • internal/console/domainbuy.go +1 −1
  • internal/console/emailsignin.go +1 −1
  • internal/console/emailsignin_test.go +2 −1
  • internal/console/fleets.go +2 −2
  • internal/console/invite_held_address_test.go +1 −1
  • internal/console/lastseen.go +6 −3
  • internal/console/lastseen_test.go +4 −3
  • internal/console/link_sim_test.go +1 −1
  • internal/console/linkedpolicy.go +5 −4
  • internal/console/links_auth_test.go +1 −1
  • internal/console/links_store.go +21 −8
  • internal/console/links_sync.go +1 −1
  • internal/console/materialize_test.go +3 −2
  • internal/console/opbilling_store_test.go +5 −4
  • internal/console/opdashboard_test.go +1 −1
  • internal/console/opstore.go +3 −2
  • internal/console/opstore_test.go +8 −7
  • internal/console/planexempt_test.go +8 −6
  • internal/console/plangrace_store.go +15 −5
  • internal/console/plangrace_test.go +6 −5
  • internal/console/plangracepass.go +16 −16
  • internal/console/planlapse.go +3 −3
  • internal/console/planlapse_keep.go +4 −3
  • internal/console/planlapse_store.go +8 −2
  • internal/console/planlapse_test.go +1 −1
  • internal/console/planlimits.go +12 −6
  • internal/console/planmail.go +4 −4
  • internal/console/planpdf_test.go +5 −4
  • internal/console/server.go +27 −24
  • internal/console/signinmethods_store_test.go +4 −3
  • internal/console/signinmethods_test.go +3 −2
  • internal/console/store.go +40 −13
  • internal/console/store_test.go +8 −7
  • internal/console/svcprincipal.go +10 −3
  • internal/console/svcroutes_test.go +7 −5
  • internal/console/tempstore.go +8 −2

CI failed — run details

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/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/apicli.go b/internal/console/apicli.go
index aa367b4a3..9e730a0a5 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
}
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/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/app_source.go b/internal/console/app_source.go
index 994cb319a..96c264284 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
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/appregionset.go b/internal/console/appregionset.go
index 829a8a52e..81375bd7b 100644
--- a/internal/console/appregionset.go
+++ b/internal/console/appregionset.go
@@ -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/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..e1b6e4a11 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
}
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 60e2e4fba..e9318a893 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 ""
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/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/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..0362897f0 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -838,13 +838,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/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..a49b06bb3 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)
}
}
diff --git a/internal/console/links_store.go b/internal/console/links_store.go
index eb19770aa..fb3c42746 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, &current)
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
}
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..2a68399f5 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)
}
@@ -438,7 +439,7 @@ func TestMaterializeReapsTombstonedAccounts(t *testing.T) {
if trashed, _ := st.TrashedAppsIn(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.
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/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..01497eebf 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 {
@@ -394,12 +394,12 @@ func shownStates(states []capState, now time.Time) []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) {
+// an owner, under that page's request context.
+func (s *Server) recordBannerNotice(ctx context.Context, accountID int64, seen []capState, now time.Time) {
if len(seen) == 0 {
return
}
- if err := s.store.RecordCapNotice(accountID, seen, now); err != nil {
+ if err := s.store.RecordCapNotice(ctx, accountID, seen, now); err != nil {
log.Printf("console: plan banner %d: notice: %v", accountID, err)
}
}
@@ -419,20 +419,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 +458,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/server.go b/internal/console/server.go
index 48624b1e1..2d8e9b856 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2447,9 +2447,12 @@ type page struct {
// BillingNav shows the account nav's billing link: billing is on.
BillingNav bool
// planSeen are the over rows behind PlanNotices when the viewer owns
- // the account; render records them as notice once the page is written.
+ // the account; render records them as notice once the page is written,
+ // under planCtx, the request's context, which accountPage sets with
+ // them.
planSeen []capState
planAcctID int64
+ planCtx context.Context
FlashErr string // one-shot error notice
Apps []appRow // account home
@@ -2904,7 +2907,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.planCtx, p.planAcctID, p.planSeen, time.Now()) // plans 4a: the banner was served
}
// templateBufs holds the buffers writeTemplate renders into. One grown past
@@ -2975,12 +2978,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 +3063,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])
@@ -3081,7 +3084,7 @@ func (s *Server) redirectToCurrentAccount(w http.ResponseWriter, r *http.Request
// 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.
func (s *Server) currentAccount(ctx context.Context, addr string) (string, error) {
- a, err := s.memberAccount(addr)
+ a, err := s.memberAccount(ctx, addr)
if err != nil {
return "", err
}
@@ -3091,7 +3094,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(ctx, addr); err != nil {
return "", err
} else if a != nil {
return a.Sqid, nil
@@ -3114,14 +3117,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 +3134,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 +3183,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 +3211,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 +3297,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 +3308,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 +3668,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)
@@ -4231,7 +4234,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 +4246,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 +4264,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.planSeen = s.planBanner(r.Context(), acct, role, time.Now())
+ p.planAcctID, p.planCtx = acct.ID, r.Context()
+ if role == RoleOwner && s.planKeepOffered(r.Context(), acct) {
p.PlanKeepURL = "/a/" + url.PathEscape(acct.Sqid) + "/plan/keep"
p.PlanKeepLink = planKeepCopy["keep.link"]
}
@@ -4281,7 +4284,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 +4301,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
}
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..3ba6c6b2d 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
}
@@ -2062,10 +2082,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
}
@@ -3036,10 +3063,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
diff --git a/internal/console/store_test.go b/internal/console/store_test.go
index 38d36bd80..28dd79e77 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 {
@@ -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)
}
@@ -712,7 +713,7 @@ func TestReapAccountClearsAndMarks(t *testing.T) {
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/tempstore.go b/internal/console/tempstore.go
index edcb52557..5d940fbf2 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
}