console: removing a member revokes what they minted (H4-M1)
Instance tokens, door keys and the other credentials a member mints for an account never expire and never re-read membership, so they outlived the member's removal. revokeMemberCredentialsTx now runs inside the removal's own transaction (removeMemberTx, so the browser door and the box-side member tool both get it) and revokes, by minter: - cli_tokens kind app (instance tokens), service (every role) and link - links rows the member approved - door keys (new door_keys.created_by column, backfilled from the mint's audit row; the revision is bumped so the record is re-signed) - pending invites the member sent CLIPrincipal and linkPrincipalLive read the rows on every request, so the refusal is immediate. The browser removal then publishes the door-key records and link channels, as their own revoke doors do; the re-sign pass and linkSyncLoop catch a failed publish. No instance binding (#155). Carries the hunt test TestHunt_H4_M1_RemovalRevokesDerivedCredentials, plus TestRemoveMemberRevokesEveryKindTheyMinted and TestDoorKeyMinterBackfilledFromAudit. A /settings revoke test now ends the membership without the revocation, the case it still guards.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+512
−14
internal/console/apidoorkeys.go+1 −1internal/console/apidoorkeys_test.go+1 −1internal/console/deletion_test.go+1 −1internal/console/doorkeys_store.go+23 −8internal/console/hunt_H4-M1_test.go+180 −0internal/console/memberrevoke.go+128 −0internal/console/memberrevoke_test.go+149 −0internal/console/ownership.go+5 −1internal/console/store.go+19 −1internal/console/svcpage_test.go+5 −1
diff --git a/internal/console/apidoorkeys.go b/internal/console/apidoorkeys.go| index 22d186bab..93965158e 100644 |
| --- a/internal/console/apidoorkeys.go |
| +++ b/internal/console/apidoorkeys.go |
| @@ -228,7 +228,7 @@ func (s *Server) handleAPIDoorKeyMint(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| entry.Label = cleanLabel(req.Label) |
| - if _, err := s.store.DoorKeyInsertContext(r.Context(), acct.ID, app, entry); err != nil { |
| + if _, err := s.store.DoorKeyInsertContext(r.Context(), acct.ID, app, entry, addr); err != nil { |
| 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/apidoorkeys_test.go b/internal/console/apidoorkeys_test.go| index 0e224b2fd..b11f799c0 100644 |
| --- a/internal/console/apidoorkeys_test.go |
| +++ b/internal/console/apidoorkeys_test.go |
| @@ -439,7 +439,7 @@ func TestDoorKeyResignPassCoversEveryApp(t *testing.T) { |
| // mintTestDoorKey stores one live door key for (account, app) directly. |
| func mintTestDoorKey(t *testing.T, s *Store, accountID int64, app, id string) { |
| t.Helper() |
| - if _, err := s.DoorKeyInsert(accountID, app, doorkey.Entry{ID: id, SHA256: strings.Repeat("a", 64)}); err != nil { |
| + if _, err := s.DoorKeyInsert(accountID, app, doorkey.Entry{ID: id, SHA256: strings.Repeat("a", 64)}, ""); err != nil { |
| t.Fatalf("DoorKeyInsert(%d, %s): %v", accountID, app, err) |
| } |
| } |
diff --git a/internal/console/deletion_test.go b/internal/console/deletion_test.go| index 3f4c043e3..858b44c24 100644 |
| --- a/internal/console/deletion_test.go |
| +++ b/internal/console/deletion_test.go |
| @@ -421,7 +421,7 @@ func TestDeleteNowDestroysEverythingAndFreesTheName(t *testing.T) { |
| // 12-hourly re-sign. |
| func TestDeleteNowSweepsLedgersAndDoorKeys(t *testing.T) { |
| fx, c, csrf := trashPageFixture(t) |
| - if _, err := fx.st.DoorKeyInsert(OpsAccountID, "kass", doorkey.Entry{ID: "0123456789abcdef", SHA256: strings.Repeat("a", 64)}); err != nil { |
| + if _, err := fx.st.DoorKeyInsert(OpsAccountID, "kass", doorkey.Entry{ID: "0123456789abcdef", SHA256: strings.Repeat("a", 64)}, ""); err != nil { |
| t.Fatal(err) |
| } |
| ledgerKey := release.LedgerAppPrefix(fx.sqid, "kass") + "ledgers.json" |
diff --git a/internal/console/doorkeys_store.go b/internal/console/doorkeys_store.go| index 9d74cd35b..cf799a942 100644 |
| --- a/internal/console/doorkeys_store.go |
| +++ b/internal/console/doorkeys_store.go |
| @@ -17,6 +17,7 @@ import ( |
| "errors" |
| "fmt" |
| "os" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/doorkey" |
| @@ -51,7 +52,21 @@ func (s *Store) migrateDoorKeys() error { |
| return err |
| } |
| } |
| - return nil |
| + // created_by is the address that minted the key, so removing that |
| + // person from the account revokes it (security hunt H4-M1, |
| + // revokeMemberCredentialsTx). '' is a key whose minter is unknown. |
| + if _, err := s.db.Exec(`ALTER TABLE door_keys ADD COLUMN created_by TEXT NOT NULL DEFAULT ''`); err != nil && |
| + !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + // A key minted before the column existed takes its minter from the |
| + // mint's audit row (handleAPIDoorKeyMint's detail, the only mint |
| + // door). Idempotent: a key with no such row stays ''. |
| + _, err := s.db.Exec(`UPDATE door_keys SET created_by = COALESCE((SELECT a.address FROM audit a |
| +WHERE a.account_id = door_keys.account_id AND a.app = door_keys.app AND a.action = 'door-key' |
| +AND a.detail = 'minted door key ' || door_keys.id || ' for ' || door_keys.app || ' (cli)' |
| +ORDER BY a.id LIMIT 1), '') WHERE created_by = ''`) |
| + return err |
| } |
| // bumpDoorKeyRevision adds one to the app's counter inside tx, creating the |
| @@ -70,7 +85,7 @@ ON CONFLICT (account_id, app) DO UPDATE SET revision = revision + 1`, accountID, |
| // DoorKeyInsert stores a newly minted key's digest and bumps the app's |
| // revision in the same transaction. It refuses with errDoorKeysFull when the |
| // app already has doorkey.MaxKeys live keys. |
| -func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Entry) (uint64, error) { |
| +func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Entry, createdBy string) (uint64, error) { |
| tx, err := s.db.Begin() |
| if err != nil { |
| return 0, err |
| @@ -88,8 +103,8 @@ func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Ent |
| if created.IsZero() { |
| created = time.Now() |
| } |
| - if _, err := tx.Exec(`INSERT INTO door_keys (account_id, app, id, sha256, label, created_at) |
| -VALUES (?, ?, ?, ?, ?, ?)`, accountID, app, e.ID, e.SHA256, e.Label, created.UnixNano()); err != nil { |
| + if _, err := tx.Exec(`INSERT INTO door_keys (account_id, app, id, sha256, label, created_at, created_by) |
| +VALUES (?, ?, ?, ?, ?, ?, ?)`, accountID, app, e.ID, e.SHA256, e.Label, created.UnixNano(), createdBy); err != nil { |
| return 0, err |
| } |
| rev, err := bumpDoorKeyRevision(tx, accountID, app) |
| @@ -242,12 +257,12 @@ func (s *Store) DoorKeyAdvanceRevisionContext(claimContext context.Context, acco |
| }) |
| return |
| } |
| -func (s *Store) DoorKeyInsert(accountID int64, app string, e doorkey.Entry) (claimResult0 uint64, claimResult1 error) { |
| - return s.DoorKeyInsertContext(context.Background(), accountID, app, e) |
| +func (s *Store) DoorKeyInsert(accountID int64, app string, e doorkey.Entry, createdBy string) (claimResult0 uint64, claimResult1 error) { |
| + return s.DoorKeyInsertContext(context.Background(), accountID, app, e, createdBy) |
| } |
| -func (s *Store) DoorKeyInsertContext(claimContext context.Context, accountID int64, app string, e doorkey.Entry) (claimResult0 uint64, claimResult1 error) { |
| +func (s *Store) DoorKeyInsertContext(claimContext context.Context, accountID int64, app string, e doorkey.Entry, createdBy string) (claimResult0 uint64, claimResult1 error) { |
| claimResult1 = s.withAutoAppSQL(claimContext, accountID, app, "sql.DoorKeyInsert", func(claimView *Store) error { |
| - claimResult0, claimResult1 = claimView.claimRawDoorKeyInsert(accountID, app, e) |
| + claimResult0, claimResult1 = claimView.claimRawDoorKeyInsert(accountID, app, e, createdBy) |
| return claimResult1 |
| }) |
| return |
diff --git a/internal/console/hunt_H4-M1_test.go b/internal/console/hunt_H4-M1_test.go| new file mode 100644 |
| index 000000000..98a60a86a |
| --- /dev/null |
| +++ b/internal/console/hunt_H4-M1_test.go |
| @@ -0,0 +1,180 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdh" |
| + "crypto/rand" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +func TestHunt_H4_M1_RemovalRevokesDerivedCredentials(t *testing.T) { |
| + fx, member := huntInstanceFixture(t, "hunt-m1") |
| + enableInstances(t, fx, "titogo", titoManifest()) |
| + token := mintInstanceToken(t, fx, member, "titogo") |
| + door := mintDoorKey(t, fx, member) |
| + status, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "titogo"), token, `{"host":"hunt.go.tito.io","region":"ie"}`) |
| + if status != http.StatusCreated { |
| + t.Fatalf("setup instance: %d %s", status, out) |
| + } |
| + status, _, out = rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/hunt.go.tito.io", member, `{"gate":"hunt original password"}`) |
| + if status != http.StatusOK { |
| + t.Fatalf("setup password gate: %d %s", status, out) |
| + } |
| + beforeRecord, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "titogo", "hunt.go.tito.io") |
| + if err != nil || beforeRecord.Gate == "" { |
| + t.Fatalf("setup gate: %v", err) |
| + } |
| + fx.setUser("paul@keymail.dev") |
| + owner := signInPaul(t, fx) |
| + status, _, _ = postGated(t, fx, owner, fx.u("/members/remove"), url.Values{"csrf": {sessionToken(t, fx, owner)}, "address": {"alice@keymail.dev"}}) |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("remove member: %d", status) |
| + } |
| + if role, err := fx.st.Role(OpsAccountID, "alice@keymail.dev"); err != nil || role != "" { |
| + t.Fatalf("member still present: %q %v", role, err) |
| + } |
| + status, _, out = rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/hunt.go.tito.io", member, `{"gate":""}`) |
| + if status != http.StatusNotFound { |
| + t.Fatalf("removed personal credential must fail: %d %s", status, out) |
| + } |
| + status, _, out = rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/hunt.go.tito.io", token, `{"gate":""}`) |
| + if status != http.StatusUnauthorized && status != http.StatusNotFound && status != http.StatusForbidden { |
| + afterRecord, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "titogo", "hunt.go.tito.io") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Errorf("removed member's instance token still mutates instance: status=%d gate_cleared=%v; want 401/403/404 and unchanged gate", status, afterRecord.Gate == "") |
| + } |
| + before := readDoorRecord(t, fx) |
| + time.Sleep(2 * time.Millisecond) |
| + fx.srv.resignDoorKeys(context.Background()) |
| + after := readDoorRecord(t, fx) |
| + if after.Admits(door) { |
| + t.Errorf("removed member's door key remains admitted after production re-sign; expiry extended=%v", after.ExpiresAt.After(before.ExpiresAt)) |
| + } |
| + future := time.Now().Add(CLITokenTTL + time.Hour) |
| + if _, ok := fx.st.CLIPrincipal(member, future); ok { |
| + t.Fatal("personal token did not expire at day 91") |
| + } |
| + if _, ok := fx.st.CLIPrincipal(token, future); ok { |
| + t.Errorf("derived instance token still authenticates after its minter's 90-day bearer expires") |
| + } |
| +} |
| + |
| +// The sandbox disallows sockets. Reuse the fixture's real SQLite/DirStore |
| +// setup and OAuth handlers, replacing only the HTTP transport with direct |
| +// ServeHTTP calls. Every console request still traverses NewServer's mux, |
| +// cliRoute, session/CSRF checks, and the production handler. Other outbound |
| +// destinations are refused; none of these tests can access the network. |
| +// Tests using this fixture must not call t.Parallel (DefaultTransport is |
| +// scoped to the test and restored by Cleanup). |
| +type huntTransport func(*http.Request) (*http.Response, error) |
| + |
| +func (f huntTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +func huntConsoleFixture(t *testing.T) *consoleFixture { |
| + t.Helper() |
| + regPath, rel, priv, pub := buildFixtures(t) |
| + st, err := Open(filepath.Join(t.TempDir(), "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { st.Close() }) |
| + key, err := ecdh.P256().GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fk := &fakeKeymail{t: t, address: "paul@keymail.dev", boxPriv: key, reauth: true, powBits: 8, |
| + noMailbox: map[string]bool{}, blocked: map[string]bool{}, lookupStatus: map[string]int{}, |
| + lookupStall: map[string]time.Duration{}, senders: map[string]string{}} |
| + km := http.NewServeMux() |
| + km.HandleFunc("GET /.well-known/keymail", fk.handleWellKnown) |
| + km.HandleFunc("POST /api/oauth/token", fk.handleToken) |
| + km.HandleFunc("POST /api/oauth/revoke", fk.handleRevoke) |
| + km.HandleFunc("GET /api/federation/lookup", fk.handleLookup) |
| + km.HandleFunc("POST /api/app/send", fk.handleSend) |
| + km.HandleFunc("POST /api/federation/challenge", fk.handleChallenge) |
| + km.HandleFunc("POST /api/federation/register", fk.handleRegister) |
| + km.HandleFunc("POST /api/federation/deliver", fk.handleDeliver) |
| + fk.srv = &httptest.Server{URL: "http://keymail.hunt.invalid"} |
| + ts := &httptest.Server{URL: "http://console.hunt.invalid"} |
| + var srv *Server |
| + old := http.DefaultTransport |
| + http.DefaultTransport = huntTransport(func(req *http.Request) (*http.Response, error) { |
| + r := req.Clone(req.Context()) |
| + r.RequestURI = r.URL.RequestURI() |
| + if r.RemoteAddr == "" { |
| + r.RemoteAddr = "192.0.2.1:54321" |
| + } |
| + w := httptest.NewRecorder() |
| + switch r.URL.Host { |
| + case "console.hunt.invalid": |
| + srv.ServeHTTP(w, r) |
| + case "keymail.hunt.invalid": |
| + km.ServeHTTP(w, r) |
| + default: |
| + return nil, fmt.Errorf("hunt forbids outbound request to %s", r.URL.Host) |
| + } |
| + res := w.Result() |
| + res.Request = req |
| + return res, nil |
| + }) |
| + t.Cleanup(func() { http.DefaultTransport = old }) |
| + srv, err = NewServer(Config{Origin: ts.URL, Keymail: fk.srv.URL, Registry: regPath, Releases: rel, ReleasePub: pub, Key: priv, AppScheme: "http"}, st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv.km.httpc.Transport = http.DefaultTransport |
| + srv.cliNotified = make(chan struct{}, 16) |
| + if err := st.AddMember(OpsAccountID, "paul@keymail.dev", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.CreateAppIn(OpsAccountID, "kass", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + return &consoleFixture{ts: ts, srv: srv, st: st, fk: fk, rel: rel, regPath: regPath, priv: priv, pub: pub, sqid: "bab"} |
| +} |
| + |
| +func huntInstanceFixture(t *testing.T, code string) (*consoleFixture, string) { |
| + t.Helper() |
| + fx := huntConsoleFixture(t) |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + return fx, huntCLIToken(t, fx, "alice@keymail.dev", code) |
| +} |
| +func huntFleetFixture(t *testing.T, code string) (*consoleFixture, string) { |
| + t.Helper() |
| + fx := huntConsoleFixture(t) |
| + return fx, huntCLIToken(t, fx, "paul@keymail.dev", code) |
| +} |
| +func huntEmailFixture(t *testing.T) (*consoleFixture, *fakeConsoleMail) { |
| + t.Helper() |
| + fx := huntConsoleFixture(t) |
| + m := &fakeConsoleMail{ready: true} |
| + fx.srv.consoleMail = m |
| + fx.srv.challengeSent = make(chan struct{}, 16) |
| + return fx, m |
| +} |
| + |
| +func huntCLIToken(t *testing.T, fx *consoleFixture, address, code string) string { |
| + t.Helper() |
| + token := cliToken(t, fx, address, code) |
| + select { |
| + case <-fx.srv.cliNotified: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("CLI issuance notification did not finish") |
| + } |
| + return token |
| +} |
diff --git a/internal/console/memberrevoke.go b/internal/console/memberrevoke.go| new file mode 100644 |
| index 000000000..a335c0a5d |
| --- /dev/null |
| +++ b/internal/console/memberrevoke.go |
| @@ -0,0 +1,128 @@ |
| +package console |
| + |
| +// Removing a member ends what they minted for the account (security hunt |
| +// H4-M1). A person's own authority over an account is their membership, |
| +// read on every request, so it ends with the row. The credentials they |
| +// minted for the account do not read it: an instance token, a service |
| +// credential, a link credential and a door key each name the account |
| +// themselves and never expire. Left alone, every one of them outlives the |
| +// removal, so a removed member keeps whatever they minted on the way out. |
| +// |
| +// revokeMemberCredentialsTx is the one place that ends them, inside the |
| +// removal's own transaction, so there is no moment with the member gone |
| +// and their credentials live. Every kind the store can mint for an |
| +// account and record a minter on: |
| +// |
| +// cli_tokens kind 'app' instance tokens (NewAppToken; any member) |
| +// cli_tokens kind 'service' service credentials of every role, team and |
| +// deploy and run among them (owner-minted) |
| +// cli_tokens kind 'link' link credentials, with their links rows |
| +// (approved by any member who creates apps) |
| +// door_keys door keys (any member), by created_by |
| +// invites pending invitations the member sent (owner) |
| +// |
| +// Each is refused at its check the moment the transaction commits: |
| +// CLIPrincipal reads revoked_at on every request (no cache), and |
| +// linkPrincipalLive reads the links row. Door keys and link channels also |
| +// live outside this database; the caller publishes them after the commit |
| +// (afterMemberRemoved), the same way their own revoke doors do, and the |
| +// re-sign pass (12 hours) and linkSyncLoop (10 seconds) catch anything |
| +// that publish misses. |
| +// |
| +// A person's own CLI token (kind '') is not touched: it names no account, |
| +// and its reach into this one already ended with the membership. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "log" |
| + "net/http" |
| + "time" |
| +) |
| + |
| +// memberRevocation is what one removal revoked outside cli_tokens, for the |
| +// publish after the commit: the apps whose door-key record changed and the |
| +// links whose channel must be revoked. |
| +type memberRevocation struct { |
| + doorKeyApps []string |
| + links []string |
| +} |
| + |
| +// revokeMemberCredentialsTx revokes, inside tx, every credential address |
| +// minted for accountID (the list above). It never commits. |
| +func revokeMemberCredentialsTx(tx *sql.Tx, accountID int64, address string, now time.Time) (memberRevocation, error) { |
| + var out memberRevocation |
| + if _, err := tx.Exec(`UPDATE cli_tokens SET revoked_at = ? |
| +WHERE account_id = ? AND address = ? AND kind IN (?, ?, ?) AND revoked_at = 0`, |
| + now.Unix(), accountID, address, cliKindApp, cliKindService, cliKindLink); err != nil { |
| + return out, err |
| + } |
| + links, err := tx.Query(`SELECT id FROM links WHERE account_id = ? AND created_by = ? AND revoked_at = 0 ORDER BY id`, |
| + accountID, address) |
| + if err != nil { |
| + return out, err |
| + } |
| + out.links, err = scanStrings(links) |
| + if err != nil { |
| + return out, err |
| + } |
| + if _, err := tx.Exec(`UPDATE links SET revoked_at = ? WHERE account_id = ? AND created_by = ? AND revoked_at = 0`, |
| + now.Unix(), accountID, address); err != nil { |
| + return out, err |
| + } |
| + // A link's credential row names its approver as address, rotation |
| + // included (RotateLinkToken), so the cli_tokens update above has |
| + // already revoked it. |
| + apps, err := tx.Query(`SELECT DISTINCT app FROM door_keys |
| +WHERE account_id = ? AND created_by = ? AND revoked_at = 0 ORDER BY app`, accountID, address) |
| + if err != nil { |
| + return out, err |
| + } |
| + out.doorKeyApps, err = scanStrings(apps) |
| + if err != nil { |
| + return out, err |
| + } |
| + for _, app := range out.doorKeyApps { |
| + if _, err := tx.Exec(`UPDATE door_keys SET revoked_at = ? |
| +WHERE account_id = ? AND app = ? AND created_by = ? AND revoked_at = 0`, now.UnixNano(), accountID, app, address); err != nil { |
| + return out, err |
| + } |
| + if _, err := bumpDoorKeyRevision(tx, accountID, app); err != nil { |
| + return out, err |
| + } |
| + } |
| + _, err = tx.Exec(`DELETE FROM invites WHERE account_id = ? AND invited_by = ? AND accepted_at = 0`, accountID, address) |
| + return out, err |
| +} |
| + |
| +// scanStrings reads one string column to the end and closes rows. |
| +func scanStrings(rows *sql.Rows) ([]string, error) { |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var v string |
| + if err := rows.Scan(&v); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, v) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// afterMemberRemoved publishes what a committed removal revoked outside the |
| +// database: each changed door-key record (publishDoorKeys, as the revoke |
| +// door does) and each link's channel (syncLinkChannel, as unlink does). |
| +// Best-effort: the database is already the truth, and the re-sign pass and |
| +// linkSyncLoop retry anything that fails here. |
| +func (s *Server) afterMemberRemoved(r *http.Request, acct *Account, rev memberRevocation) { |
| + for _, app := range rev.doorKeyApps { |
| + s.republishDoorKeys(r, acct, app) |
| + } |
| + for _, id := range rev.links { |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), linkFirstSyncTimeout) |
| + if err := s.syncLinkChannel(ctx, id); err != nil { |
| + log.Printf("console: link %s: revoke after member removal: %v (linkSyncLoop retries)", id, err) |
| + } |
| + cancel() |
| + } |
| +} |
diff --git a/internal/console/memberrevoke_test.go b/internal/console/memberrevoke_test.go| new file mode 100644 |
| index 000000000..daa316ee0 |
| --- /dev/null |
| +++ b/internal/console/memberrevoke_test.go |
| @@ -0,0 +1,149 @@ |
| +package console |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/doorkey" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +// TestRemoveMemberRevokesEveryKindTheyMinted (security hunt H4-M1): every |
| +// credential kind revokeMemberCredentialsTx lists, minted by the removed |
| +// member, is refused once the removal commits; the same kinds minted by |
| +// the owner, and the member's credentials in another account, are not. |
| +func TestRemoveMemberRevokesEveryKindTheyMinted(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + st := fx.st |
| + now := time.Now() |
| + const alice, paul = "alice@keymail.dev", "paul@keymail.dev" |
| + if _, err := st.CreateAppIn(OpsAccountID, "titogo", paul, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.AddMember(OpsAccountID, alice, RoleOwner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.CreateAccount(42, "bbw", "other", alice, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.CreateAppIn(42, "elsewhere", alice, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + type minted struct{ instance, service, link, linkID, door, invite string } |
| + mint := func(who, tag string, accountID int64, app string) minted { |
| + t.Helper() |
| + var m minted |
| + var err error |
| + if m.instance, err = st.NewAppToken(accountID, app, who, "inst-"+tag, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.service, err = st.NewServicePrincipal(accountID, "svc-"+tag, app, svcrole.Publish, who, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + tx, err := st.db.Begin() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.link, err = randomToken(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.linkID, err = mintLinkTx(tx, st.linkIDSource(), accountID, "home-"+tag, who, "", m.link, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tx.Commit(); err != nil { |
| + t.Fatal(err) |
| + } |
| + m.door = tag + strings.Repeat("0", 16-len(tag)) |
| + if _, err := st.DoorKeyInsert(accountID, app, doorkey.Entry{ID: m.door, SHA256: strings.Repeat("a", 64)}, who); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.invite, err = st.CreateInvite(accountID, tag+"-invitee@example.com", who, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| + } |
| + gone := mint(alice, "a", OpsAccountID, "titogo") |
| + kept := mint(paul, "b", OpsAccountID, "titogo") |
| + elsewhere := mint(alice, "c", 42, "elsewhere") |
| + _, revBefore, err := st.DoorKeysLive(OpsAccountID, "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + if err := st.RemoveMember(OpsAccountID, alice); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + check := func(label string, m minted, accountID int64, app string, wantLive bool) { |
| + t.Helper() |
| + for kind, tok := range map[string]string{"instance token": m.instance, "service credential": m.service, "link credential": m.link} { |
| + if _, ok := st.CLIPrincipal(tok, now); ok != wantLive { |
| + t.Errorf("%s: %s resolves = %v, want %v", label, kind, ok, wantLive) |
| + } |
| + } |
| + l, err := st.LinkByID(m.linkID) |
| + if err != nil || l == nil { |
| + t.Fatalf("%s: link %s: %+v %v", label, m.linkID, l, err) |
| + } |
| + if l.RevokedAt.IsZero() != wantLive { |
| + t.Errorf("%s: link revoked at %v, want live %v", label, l.RevokedAt, wantLive) |
| + } |
| + keys, _, err := st.DoorKeysLive(accountID, app) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + live := false |
| + for _, k := range keys { |
| + live = live || k.ID == m.door |
| + } |
| + if live != wantLive { |
| + t.Errorf("%s: door key %s live = %v, want %v", label, m.door, live, wantLive) |
| + } |
| + if _, ok := st.PendingInviteAddress(m.invite, now); ok != wantLive { |
| + t.Errorf("%s: invite pending = %v, want %v", label, ok, wantLive) |
| + } |
| + } |
| + check("removed member", gone, OpsAccountID, "titogo", false) |
| + check("owner", kept, OpsAccountID, "titogo", true) |
| + check("removed member's other account", elsewhere, 42, "elsewhere", true) |
| + if _, revAfter, err := st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || revAfter <= revBefore { |
| + t.Errorf("door-key revision %d -> %d (%v); a revoke must bump it so the record is re-signed", revBefore, revAfter, err) |
| + } |
| +} |
| + |
| +// TestDoorKeyMinterBackfilledFromAudit: a key minted before created_by |
| +// existed takes its minter from the mint's audit row, so removing that |
| +// member revokes it too. |
| +func TestDoorKeyMinterBackfilledFromAudit(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + st := fx.st |
| + now := time.Now() |
| + if _, err := st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + const id = "0123456789abcdef" |
| + if _, err := st.DoorKeyInsert(OpsAccountID, "titogo", doorkey.Entry{ID: id, SHA256: strings.Repeat("a", 64)}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.RecordEvent(OpsAccountID, "titogo", "alice@keymail.dev", "door-key", "minted door key "+id+" for titogo (cli)", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.migrateDoorKeys(); err != nil { |
| + t.Fatal(err) |
| + } |
| + var by string |
| + if err := st.db.QueryRow(`SELECT created_by FROM door_keys WHERE id = ?`, id).Scan(&by); err != nil || by != "alice@keymail.dev" { |
| + t.Fatalf("created_by = %q, %v; want the audit row's minter", by, err) |
| + } |
| + if err := st.RemoveMember(OpsAccountID, "alice@keymail.dev"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if keys, _, err := st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || len(keys) != 0 { |
| + t.Fatalf("live keys after removing their minter = %+v, %v; want none", keys, err) |
| + } |
| +} |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 92a866402..9ae09865e 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -50,14 +50,18 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) { |
| // Under the member lock (plans 6b), so it and an accept or an invite |
| // are one after the other. |
| unlock := s.lockMembers(acct.Sqid) |
| + var rev memberRevocation |
| err := s.membershipTransition(r.Context(), acct, time.Now(), func(tx *sql.Tx) error { |
| - return removeMemberTx(tx, acct.ID, target) |
| + var err error |
| + rev, err = removeMemberRevokingTx(tx, acct.ID, target) |
| + return err |
| }) |
| unlock() |
| if err != nil { |
| log.Printf("console: remove member: %v", err) |
| s.setFlash(w, "err", removalAdvice(err, target)) |
| } else { |
| + s.afterMemberRemoved(r, acct, rev) |
| s.setFlash(w, "ok", target+" is no longer a member of this account.") |
| } |
| http.Redirect(w, r, "/a/"+acct.Sqid+"/team", http.StatusSeeOther) |
diff --git a/internal/console/store.go b/internal/console/store.go| index 5a0f91b72..1f62e5dd9 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -1616,9 +1616,27 @@ func (s *Store) RemoveMember(accountID int64, address string) error { |
| // removeMemberTx is RemoveMember inside the caller's transaction (a |
| // MembershipTransition write). It never commits. |
| func removeMemberTx(tx *sql.Tx, accountID int64, address string) error { |
| + _, err := removeMemberRevokingTx(tx, accountID, address) |
| + return err |
| +} |
| + |
| +// removeMemberRevokingTx is removeMemberTx answering what it revoked: every |
| +// credential the member minted for the account goes in the same |
| +// transaction (revokeMemberCredentialsTx, security hunt H4-M1), and the |
| +// caller publishes the door keys and link channels after the commit. |
| +func removeMemberRevokingTx(tx *sql.Tx, accountID int64, address string) (memberRevocation, error) { |
| if err := lastOwnerGuard(tx, accountID, address); err != nil { |
| - return err |
| + return memberRevocation{}, err |
| } |
| + rev, err := revokeMemberCredentialsTx(tx, accountID, address, time.Now()) |
| + if err != nil { |
| + return memberRevocation{}, err |
| + } |
| + return rev, removeMembershipRowsTx(tx, accountID, address) |
| +} |
| + |
| +// removeMembershipRowsTx deletes the membership and the member's own rows. |
| +func removeMembershipRowsTx(tx *sql.Tx, accountID int64, address string) error { |
| if _, err := tx.Exec(`DELETE FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address); err != nil { |
| return err |
| } |
diff --git a/internal/console/svcpage_test.go b/internal/console/svcpage_test.go| index 407d6b093..3fde1ab86 100644 |
| --- a/internal/console/svcpage_test.go |
| +++ b/internal/console/svcpage_test.go |
| @@ -576,7 +576,11 @@ func TestPersonalSettingsRefusesAnAppTokenRevokeAfterRemoval(t *testing.T) { |
| t.Fatalf("CLITokens = %d rows %v, want the app token", len(toks), err) |
| } |
| id := toks[0].ID |
| - if err := fx.st.RemoveMember(otherID, "paul@keymail.dev"); err != nil { |
| + // The membership ends WITHOUT RemoveMember's revocation (security hunt |
| + // H4-M1 now revokes what a removed member minted): a token that |
| + // survived a removal made before that, which this door must still |
| + // refuse to let its old minter revoke. |
| + if _, err := fx.st.db.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`, otherID, "paul@keymail.dev"); err != nil { |
| t.Fatal(err) |
| } |