console: a mint cannot land after its minter's removal (H4-M1 r1)
Review round 1 (Astra P1-1): the instance-token and door-key doors read membership before the request body, so a mint paused on its body could commit after the removal and escape the revocation. The insert now re-reads the minter's membership in the same statement (instance token) or transaction (door key), serialised with the removal by SQLite; a refused mint answers the family's 404. TestMintInFlightDuringRemovalLandsNothing removes the member from inside the body read; it fails without the re-read. Fifteen store tests that mint as a non-member now make the minter a member first (mustMember).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+126
−3
internal/console/apidoorkeys.go+4 −0internal/console/apiinstances.go+4 −0internal/console/authstore.go+18 −3internal/console/authstore_test.go+5 −0internal/console/doorkeys_store.go+13 −0internal/console/memberrevoke_test.go+72 −0internal/console/svcprincipal_run_test.go+1 −0internal/console/svcprincipal_test.go+5 −0internal/console/svcscope_test.go+4 −0
diff --git a/internal/console/apidoorkeys.go b/internal/console/apidoorkeys.go| index 93965158e..fcf003638 100644 |
| --- a/internal/console/apidoorkeys.go |
| +++ b/internal/console/apidoorkeys.go |
| @@ -229,6 +229,10 @@ func (s *Server) handleAPIDoorKeyMint(w http.ResponseWriter, r *http.Request) { |
| } |
| entry.Label = cleanLabel(req.Label) |
| if _, err := s.store.DoorKeyInsertContext(r.Context(), acct.ID, app, entry, addr); err != nil { |
| + if errors.Is(err, errMinterNotMember) { |
| + http.NotFound(w, r) // removed while the request was in flight: the family's 404 |
| + return |
| + } |
| if errors.Is(err, errDoorKeysFull) { |
| jsonError(w, http.StatusConflict, fmt.Sprintf( |
| "this app already has %d door keys. revoke one before you mint another", doorkey.MaxKeys)) |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 6c6edd4e4..1dd35a1a4 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -3590,6 +3590,10 @@ func (s *Server) handleAPIInstanceToken(w http.ResponseWriter, r *http.Request) |
| label = app + " instance token" |
| } |
| raw, err := s.store.NewAppTokenContext(r.Context(), acct.ID, app, addr, label, time.Now()) |
| + if errors.Is(err, errMinterNotMember) { |
| + http.NotFound(w, r) // removed while the request was in flight: the family's 404 |
| + return |
| + } |
| if err != nil { |
| log.Printf("console: api instance token %s/%s: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusInternalServerError, "could not mint the token — try again") |
diff --git a/internal/console/authstore.go b/internal/console/authstore.go| index ed98e3ce3..78f5615de 100644 |
| --- a/internal/console/authstore.go |
| +++ b/internal/console/authstore.go |
| @@ -750,15 +750,30 @@ func (s *Store) claimRawNewAppToken(accountID int64, app, mintedBy, label string |
| if err != nil { |
| return "", err |
| } |
| - if _, err := s.db.Exec(`INSERT INTO cli_tokens |
| + // The minter's membership is re-read in the same statement as the |
| + // insert (security hunt H4-M1): a mint whose request began before the |
| + // minter's removal cannot land after it, because the removal's |
| + // transaction and this statement are serialised by SQLite. |
| + res, err := s.db.Exec(`INSERT INTO cli_tokens |
| (token_hash, address, label, remote_addr, created_at, expires_at, kind, account_id, app, credential_id) |
| -VALUES (?, ?, ?, '', ?, 0, ?, ?, ?, ?)`, |
| - hashToken(raw), mintedBy, label, now.Unix(), cliKindApp, accountID, app, credID); err != nil { |
| +SELECT ?, ?, ?, '', ?, 0, ?, ?, ?, ? |
| +WHERE EXISTS (SELECT 1 FROM memberships WHERE account_id = ? AND address = ?)`, |
| + hashToken(raw), mintedBy, label, now.Unix(), cliKindApp, accountID, app, credID, accountID, mintedBy) |
| + if err != nil { |
| + return "", err |
| + } |
| + if n, err := res.RowsAffected(); err != nil { |
| return "", err |
| + } else if n == 0 { |
| + return "", errMinterNotMember |
| } |
| return raw, nil |
| } |
| +// errMinterNotMember is a credential mint refused because the minter is no |
| +// longer a member of the account by the time the row would be written. |
| +var errMinterNotMember = errors.New("console: the minter is not a member of the account") |
| + |
| // CLITokenAddress resolves a bearer token to the address that approved it; ok |
| // is false for unknown, revoked and expired tokens. This is the whole |
| // authorization decision for every CLI-facing endpoint. |
diff --git a/internal/console/authstore_test.go b/internal/console/authstore_test.go| index 68b083351..b491087cc 100644 |
| --- a/internal/console/authstore_test.go |
| +++ b/internal/console/authstore_test.go |
| @@ -243,6 +243,7 @@ func TestAppTokenContainment(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| + mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1) |
| app, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now) |
| if err != nil { |
| t.Fatal(err) |
| @@ -307,6 +308,7 @@ VALUES (?, 'paul@keymail.dev', 'dated', '', ?, ?, 'app', 9, 'tito')`, |
| func TestAppTokenNeverExpires(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| + mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1) |
| app, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now) |
| if err != nil { |
| t.Fatal(err) |
| @@ -336,6 +338,7 @@ func TestAppTokenNeverExpires(t *testing.T) { |
| func TestAppTokenRevocation(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| + mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1) |
| app, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now) |
| if err != nil { |
| t.Fatal(err) |
| @@ -373,6 +376,7 @@ func TestCLITokenMigrationReopens(t *testing.T) { |
| t.Fatal(err) |
| } |
| user := mintUserToken(t, first, "paul@keymail.dev", now) |
| + mustMember(t, first, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1) |
| app, err := first.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now) |
| if err != nil { |
| t.Fatal(err) |
| @@ -406,6 +410,7 @@ func TestCLITokensReportsKind(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| mintUserToken(t, s, "paul@keymail.dev", now) |
| + mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1) |
| if _, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/doorkeys_store.go b/internal/console/doorkeys_store.go| index cf799a942..82a433a3c 100644 |
| --- a/internal/console/doorkeys_store.go |
| +++ b/internal/console/doorkeys_store.go |
| @@ -91,6 +91,19 @@ func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Ent |
| return 0, err |
| } |
| defer tx.Rollback() |
| + // The minter's membership, re-read inside the insert's transaction |
| + // (security hunt H4-M1), so a mint cannot land after its minter's |
| + // removal. "" is a key with no recorded minter (tests and older rows). |
| + if createdBy != "" { |
| + var one int |
| + err := tx.QueryRow(`SELECT 1 FROM memberships WHERE account_id = ? AND address = ?`, accountID, createdBy).Scan(&one) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return 0, errMinterNotMember |
| + } |
| + if err != nil { |
| + return 0, err |
| + } |
| + } |
| var live int |
| if err := tx.QueryRow(`SELECT COUNT(*) FROM door_keys WHERE account_id = ? AND app = ? AND revoked_at = 0`, |
| accountID, app).Scan(&live); err != nil { |
diff --git a/internal/console/memberrevoke_test.go b/internal/console/memberrevoke_test.go| index daa316ee0..6521b78f2 100644 |
| --- a/internal/console/memberrevoke_test.go |
| +++ b/internal/console/memberrevoke_test.go |
| @@ -1,6 +1,8 @@ |
| package console |
| import ( |
| + "net/http" |
| + "net/http/httptest" |
| "strings" |
| "testing" |
| "time" |
| @@ -147,3 +149,73 @@ func TestDoorKeyMinterBackfilledFromAudit(t *testing.T) { |
| t.Fatalf("live keys after removing their minter = %+v, %v; want none", keys, err) |
| } |
| } |
| + |
| +// pausedBody is a request body whose first Read runs pause before any |
| +// byte is returned: the handler has passed its membership gate and is |
| +// waiting on the body when pause runs. |
| +type pausedBody struct { |
| + pause func() |
| + body *strings.Reader |
| + once bool |
| +} |
| + |
| +func (p *pausedBody) Read(b []byte) (int, error) { |
| + if !p.once { |
| + p.once = true |
| + p.pause() |
| + } |
| + return p.body.Read(b) |
| +} |
| + |
| +// TestMintInFlightDuringRemovalLandsNothing (security hunt H4-M1, review |
| +// round 1): a member's instance-token and door-key mints that passed the |
| +// membership gate, then waited on their body while the member was |
| +// removed, write no credential. The insert re-reads membership itself. |
| +func TestMintInFlightDuringRemovalLandsNothing(t *testing.T) { |
| + for _, door := range []string{"instance-token", "door-keys"} { |
| + t.Run(door, func(t *testing.T) { |
| + fx, member := instanceFixture(t, "code-mint-race-"+door) |
| + removed := false |
| + body := &pausedBody{body: strings.NewReader(`{"label":"race"}`), pause: func() { |
| + if err := fx.st.RemoveMember(OpsAccountID, "alice@keymail.dev"); err != nil { |
| + t.Error(err) |
| + } |
| + removed = true |
| + }} |
| + req := httptest.NewRequest(http.MethodPost, "/api/cli/apps/bab/titogo/"+door, body) |
| + req.Header.Set("Authorization", "Bearer "+member) |
| + req.Header.Set("Content-Type", "application/json") |
| + rec := httptest.NewRecorder() |
| + fx.srv.ServeHTTP(rec, req) |
| + if !removed { |
| + t.Fatalf("the handler answered %d %s before reading the body; the race was not staged", rec.Code, rec.Body) |
| + } |
| + if rec.Code == http.StatusCreated { |
| + t.Fatalf("mint after removal = %d %s, want refusal", rec.Code, rec.Body) |
| + } |
| + var n int |
| + q := `SELECT COUNT(*) FROM cli_tokens WHERE kind = 'app' AND address = ? AND revoked_at = 0` |
| + if door == "door-keys" { |
| + q = `SELECT COUNT(*) FROM door_keys WHERE created_by = ? AND revoked_at = 0` |
| + } |
| + if err := fx.st.db.QueryRow(q, "alice@keymail.dev").Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("live credentials minted by the removed member = %d (%v), want 0", n, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// mustMember makes address a member of accountID unless it already holds a |
| +// role there: credential mints re-read the minter's membership (H4-M1), so |
| +// a store-level test that mints as an address must make it a member. |
| +func mustMember(t *testing.T, s *Store, accountID int64, address string) { |
| + t.Helper() |
| + if role, err := s.Role(accountID, address); err != nil { |
| + t.Fatal(err) |
| + } else if role != "" { |
| + return |
| + } |
| + if err := s.AddMember(accountID, address, RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/console/svcprincipal_run_test.go b/internal/console/svcprincipal_run_test.go| index 09486f4b4..327175bac 100644 |
| --- a/internal/console/svcprincipal_run_test.go |
| +++ b/internal/console/svcprincipal_run_test.go |
| @@ -248,6 +248,7 @@ func TestCredentialIDBackfillIsIdempotent(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| + mustMember(t, st, 1, "paul@example.test") // a mint re-reads the minter's membership (H4-M1) |
| app, err := st.NewAppToken(1, "hello", "paul@example.test", "router", now) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/console/svcprincipal_test.go b/internal/console/svcprincipal_test.go| index 2ab0ebc13..a418ca038 100644 |
| --- a/internal/console/svcprincipal_test.go |
| +++ b/internal/console/svcprincipal_test.go |
| @@ -26,6 +26,7 @@ func TestCLIPrincipalLegacyAppTokenIsInstanceRole(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| acct := mustAccount(t, s, "legacy") |
| + mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1) |
| raw, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now) |
| if err != nil { |
| t.Fatalf("NewAppToken: %v", err) |
| @@ -206,6 +207,7 @@ func TestServicePrincipalsListsBothKinds(t *testing.T) { |
| if _, err := s.NewServicePrincipal(acct.ID, "hub", "", svcrole.Publish, "paul@example.test", now); err != nil { |
| t.Fatalf("NewServicePrincipal: %v", err) |
| } |
| + mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1) |
| if _, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now); err != nil { |
| t.Fatalf("NewAppToken: %v", err) |
| } |
| @@ -244,6 +246,7 @@ func TestRotateAndRevokeIgnoreLegacyNamelessRows(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| acct := mustAccount(t, s, "amadan") |
| + mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1) |
| app, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now) |
| if err != nil { |
| t.Fatalf("NewAppToken: %v", err) |
| @@ -268,6 +271,7 @@ func TestRevokeAccountTokenScopesByAccountNotAddress(t *testing.T) { |
| now := time.Now() |
| acct := mustAccount(t, s, "amadan") |
| other := mustAccount(t, s, "other") |
| + mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1) |
| app, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now) |
| if err != nil { |
| t.Fatalf("NewAppToken: %v", err) |
| @@ -616,6 +620,7 @@ func TestRevokeAccountTokenSoftRevokesNotDeletes(t *testing.T) { |
| s := openTestStore(t) |
| now := time.Now() |
| acct := mustAccount(t, s, "amadan") |
| + mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1) |
| app, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now) |
| if err != nil { |
| t.Fatalf("NewAppToken: %v", err) |
diff --git a/internal/console/svcscope_test.go b/internal/console/svcscope_test.go| index 03c9493d7..b6e576ef0 100644 |
| --- a/internal/console/svcscope_test.go |
| +++ b/internal/console/svcscope_test.go |
| @@ -194,6 +194,7 @@ func TestAppsListForAServiceIsItsOwnScope(t *testing.T) { |
| } |
| // A legacy kind='app' credential is a service principal too, and reads |
| // the same way here — its scope is its one app. |
| + mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1) |
| legacy, err := fx.st.NewAppToken(OpsAccountID, "two", serviceMinter, "router", now) |
| if err != nil { |
| t.Fatal(err) |
| @@ -270,6 +271,7 @@ func TestServiceAuditActorIsNotABareAddress(t *testing.T) { |
| // move — it is the exact failure mode the collapse could have introduced. |
| func TestLegacyBindingWithNoAppIsNotAWildcard(t *testing.T) { |
| fx := newConsoleFixture(t) |
| + mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1) |
| raw, err := fx.st.NewAppToken(OpsAccountID, "", serviceMinter, "bound to nothing", time.Now()) |
| if err != nil { |
| t.Fatal(err) |
| @@ -313,6 +315,7 @@ func TestEnableStaysAHumanAct(t *testing.T) { |
| fx, _ := instanceFixture(t, "code-scope-enable-human") |
| fx.srv.cfg.AppsDomain = "oncarlos.test" |
| named := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Instance) |
| + mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1) |
| legacy, err := fx.st.NewAppToken(OpsAccountID, "titogo", serviceMinter, "router", time.Now()) |
| if err != nil { |
| t.Fatal(err) |
| @@ -450,6 +453,7 @@ func TestAppScopedServiceCannotClaimANewApp(t *testing.T) { |
| // walls are not confused for one — if the role table ever put `instance` |
| // on this door, THIS is the assertion that would move, and the guard |
| // above is what would then be doing the work. |
| + mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1) |
| legacy, err := fx.st.NewAppToken(OpsAccountID, "one", serviceMinter, "router", time.Now()) |
| if err != nil { |
| t.Fatal(err) |