From 46d50449255475a1964d1b74caeede0d34fbd367 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 18:59:21 +0000 Subject: [PATCH] Store: an upsert never moves an identity between accounts; unlinkLinkedIdentity is the one delete, under an account lock, refusing the last identity STORE_TABLE_PRIVILEGES.linked_identities gains DELETE; startup refuses a role without it. Co-Authored-By: Claude Sonnet 5.5 --- src/store/in-memory.ts | 14 +++++ src/store/postgres.ts | 49 +++++++++++++++-- src/store/types.ts | 26 +++++++++ tests/store.test.ts | 117 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 200 insertions(+), 6 deletions(-) diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index 5df37ea..b35decb 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -18,6 +18,7 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, + IdentityHeldElsewhereError, type StoredAccount, type StoredAuthAttempt, type StoredAuthCompletion, @@ -25,6 +26,7 @@ import { type StoredLinkedIdentity, type StoredSession, type StoredPrivateCommandReceipt, + type UnlinkResult, type UpsertLinkedIdentityInput, } from "./types.js"; @@ -148,6 +150,9 @@ export class InMemoryStore implements HeimdallStore { const existing = [...this.linkedIdentities.values()].find( (identity) => identity.provider === input.provider && identity.providerUserId === input.providerUserId ); + if (existing && existing.accountId !== input.accountId) { + throw new IdentityHeldElsewhereError(); + } const id = existing?.id ?? input.id ?? randomUUID(); const linkedIdentity: StoredLinkedIdentity = { id, @@ -188,6 +193,15 @@ export class InMemoryStore implements HeimdallStore { return clone(linkedIdentity); } + async unlinkLinkedIdentity(accountId: string, identityId: string): Promise { + const target = this.linkedIdentities.get(identityId); + if (!target || target.accountId !== accountId) return { kind: "not_found" }; + const held = [...this.linkedIdentities.values()].filter((identity) => identity.accountId === accountId).length; + if (held <= 1) return { kind: "last_identity" }; + this.linkedIdentities.delete(identityId); + return { kind: "unlinked", identity: clone(target) }; + } + async updateLinkedIdentityCredential( id: string, decide: (locked: StoredLinkedIdentity) => Promise, diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 247260c..0b05f61 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -18,6 +18,7 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, + IdentityHeldElsewhereError, OAUTH_STATE_PRUNE_BATCH, oauthStatePruneCutoffMs, type StoredAccount, @@ -27,6 +28,7 @@ import { type StoredLinkedIdentity, type StoredSession, type StoredPrivateCommandReceipt, + type UnlinkResult, type UpsertLinkedIdentityInput, } from "./types.js"; @@ -451,13 +453,15 @@ export function samePredicate(declared: string, actual: string, keyColumns: stri /** * What the store's statements do to each table, and so the privileges its * database role needs: it reads what it returns or looks up, inserts what it - * creates, updates what it changes or upserts, and deletes only expired - * oauth_state_uses rows (which needs SELECT for its WHERE). + * creates, updates what it changes or upserts, and deletes two things: + * expired oauth_state_uses rows (which needs SELECT for its WHERE), and the one + * linked_identities row an unlink names (unlinkLinkedIdentity, the only + * delete there; it needs SELECT for its WHERE and for the account's count). * audit_events is written and never read back. */ export const STORE_TABLE_PRIVILEGES: Readonly> = { accounts: ["SELECT", "INSERT", "UPDATE"], - linked_identities: ["SELECT", "INSERT", "UPDATE"], + linked_identities: ["SELECT", "INSERT", "UPDATE", "DELETE"], sessions: ["SELECT", "INSERT", "UPDATE"], auth_attempts: ["SELECT", "INSERT", "UPDATE"], private_command_receipts: ["SELECT", "INSERT"], @@ -780,7 +784,6 @@ export class PostgresStore implements HeimdallStore { ) ON CONFLICT (provider, provider_user_id) DO UPDATE SET - account_id = EXCLUDED.account_id, username = EXCLUDED.username, display_name = EXCLUDED.display_name, primary_email = EXCLUDED.primary_email, @@ -791,6 +794,7 @@ export class PostgresStore implements HeimdallStore { scopes = EXCLUDED.scopes, profile_json = EXCLUDED.profile_json, updated_at = EXCLUDED.updated_at + WHERE linked_identities.account_id = EXCLUDED.account_id RETURNING * `, [ @@ -811,7 +815,42 @@ export class PostgresStore implements HeimdallStore { ] ); - return mapLinkedIdentityRow(expectRow(result.rows[0], "upsertLinkedIdentity")); + // The conflict arm updates only the holder's own row; another account's yields no row. + if (!result.rows[0]) throw new IdentityHeldElsewhereError(); + return mapLinkedIdentityRow(result.rows[0]); + } + + async unlinkLinkedIdentity(accountId: string, identityId: string): Promise { + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + try { + // The account row serialises its unlinks: two clients racing for the last two identities queue here. + await client.query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE", [accountId]); + const held = await client.query<{ n: string | number }>( + "SELECT count(*) AS n FROM linked_identities WHERE account_id = $1", + [accountId] + ); + let result: UnlinkResult; + if (Number(held.rows[0]?.n ?? 0) <= 1) { + const mine = await client.query("SELECT 1 FROM linked_identities WHERE id = $1 AND account_id = $2", [identityId, accountId]); + result = mine.rowCount ? { kind: "last_identity" } : { kind: "not_found" }; + } else { + const deleted = await client.query( + "DELETE FROM linked_identities WHERE id = $2 AND account_id = $1 RETURNING *", + [accountId, identityId] + ); + result = deleted.rows[0] ? { kind: "unlinked", identity: mapLinkedIdentityRow(deleted.rows[0]) } : { kind: "not_found" }; + } + await client.query("COMMIT"); + return result; + } catch (error) { + await client.query("ROLLBACK"); + throw error; + } + } finally { + client.release(); + } } async updateLinkedIdentityCredential( diff --git a/src/store/types.ts b/src/store/types.ts index a2a792d..a056f9f 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -41,6 +41,24 @@ export interface StoredLinkedIdentity { updatedAt: string; } +/** + * An upsert named an identity another account holds. A provider identity + * belongs to the account that holds it until that account unlinks it; no + * write moves it. + */ +export class IdentityHeldElsewhereError extends Error { + constructor() { + super("This provider identity is held by another account."); + this.name = "IdentityHeldElsewhereError"; + } +} + +/** What unlinkLinkedIdentity decided; `identity` is the row as it was deleted. */ +export type UnlinkResult = + | { kind: "unlinked"; identity: StoredLinkedIdentity } + | { kind: "last_identity" } + | { kind: "not_found" }; + export interface UpsertLinkedIdentityInput { id?: string; accountId: string; @@ -311,7 +329,15 @@ export interface HeimdallStore { findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise; findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise; listStoredLinkedIdentitiesForAccount(accountId: string): Promise; + /** Writes the holder's own row; throws IdentityHeldElsewhereError rather than move another account's identity. */ upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise; + /** + * The only delete of a linked identity. One transaction locks the account, + * refuses to take its last identity, and deletes the row only if the + * account holds it (an id that is missing or another account's is the same + * `not_found`). + */ + unlinkLinkedIdentity(accountId: string, identityId: string): Promise; /** * Serialise decisions about one row's credential. `decide` receives the row * as read under the lock (never a caller's snapshot) and the decision is diff --git a/tests/store.test.ts b/tests/store.test.ts index dc0fbe2..76665cc 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -3,7 +3,7 @@ import { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { newDb } from "pg-mem"; import { type HeimdallConfig } from "../src/config.js"; -import { createStore, InMemoryStore } from "../src/store/index.js"; +import { createStore, IdentityHeldElsewhereError, InMemoryStore, type HeimdallStore } from "../src/store/index.js"; import { createPostgresStore, PostgresStore, @@ -203,6 +203,84 @@ describe("PostgresStore", () => { }); }); +// linked_identities has one writer that can move a row between accounts: none. +// upsert refreshes the holder's own row and refuses another account's; unlink is +// the only delete, and it never takes an account's last identity. +const unlinkStores: Array<[string, () => Promise]> = [ + ["InMemoryStore", async () => new InMemoryStore()], + [ + "PostgresStore on pg-mem", + async () => { + const store = new PostgresStore(new (newDb().adapters.createPg().Pool)()); + await store.ensureSchema(); + return store; + }, + ], +]; +describe.each(unlinkStores)("linked_identities writes, %s", (_name, make) => { + const at = "2026-11-13T12:00:00.000Z"; + const input = (accountId: string, providerUserId: string, extra: Record = {}) => ({ + accountId, + provider: "discord" as const, + providerUserId, + scopes: ["identify"], + profileJson: {}, + createdAt: at, + updatedAt: at, + ...extra, + }); + async function twoAccounts() { + const store = await make(); + const a = await store.createAccount({ createdAt: at, lastSeenAt: at }); + const b = await store.createAccount({ createdAt: at, lastSeenAt: at }); + return { store, a, b }; + } + + // pg-mem has neither ON CONFLICT ... WHERE nor row locks: these two run on real Postgres below. + const realPostgresOnly = _name !== "InMemoryStore"; + + it.skipIf(realPostgresOnly)("upsert on an identity another account holds throws IdentityHeldElsewhereError and leaves the row untouched", async () => { + const { store, a, b } = await twoAccounts(); + const held = await store.upsertLinkedIdentity(input(a.id, "u1", { username: "original", accessTokenEncrypted: "keep" })); + await expect( + store.upsertLinkedIdentity(input(b.id, "u1", { username: "thief", accessTokenEncrypted: "stolen", updatedAt: "2027-01-01T00:00:00.000Z" })) + ).rejects.toBeInstanceOf(IdentityHeldElsewhereError); + expect(await store.findStoredLinkedIdentity("discord", "u1")).toEqual(held); + expect(await store.listStoredLinkedIdentitiesForAccount(b.id)).toEqual([]); + }); + + it("upsert by the holder still refreshes its own row, keeping its id", async () => { + const { store, a } = await twoAccounts(); + const first = await store.upsertLinkedIdentity(input(a.id, "u1", { username: "one" })); + const again = await store.upsertLinkedIdentity(input(a.id, "u1", { username: "two", updatedAt: "2026-11-14T00:00:00.000Z" })); + expect([again.id, again.accountId, again.username]).toEqual([first.id, a.id, "two"]); + }); + + it("unlink: deletes one of two, refuses the last, reports another account's or a missing id as not_found", async () => { + const { store, a, b } = await twoAccounts(); + const one = await store.upsertLinkedIdentity(input(a.id, "u1")); + const two = await store.upsertLinkedIdentity(input(a.id, "u2")); + const theirs = await store.upsertLinkedIdentity(input(b.id, "u3")); + expect(await store.unlinkLinkedIdentity(a.id, theirs.id)).toEqual({ kind: "not_found" }); + expect(await store.unlinkLinkedIdentity(a.id, "no-such")).toEqual({ kind: "not_found" }); + expect(await store.unlinkLinkedIdentity(b.id, theirs.id)).toEqual({ kind: "last_identity" }); + const done = await store.unlinkLinkedIdentity(a.id, one.id); + expect(done).toMatchObject({ kind: "unlinked", identity: { id: one.id, provider: "discord", providerUserId: "u1" } }); + expect(await store.unlinkLinkedIdentity(a.id, two.id)).toEqual({ kind: "last_identity" }); + expect((await store.listStoredLinkedIdentitiesForAccount(a.id)).map((i) => i.id)).toEqual([two.id]); + expect(await store.findStoredLinkedIdentity("discord", "u3")).toMatchObject({ id: theirs.id, accountId: b.id }); + }); + + it.skipIf(realPostgresOnly)("two concurrent unlinks of an account's last two identities leave exactly one", async () => { + const { store, a } = await twoAccounts(); + const one = await store.upsertLinkedIdentity(input(a.id, "u1")); + const two = await store.upsertLinkedIdentity(input(a.id, "u2")); + const results = await Promise.all([store.unlinkLinkedIdentity(a.id, one.id), store.unlinkLinkedIdentity(a.id, two.id)]); + expect(results.map((r) => r.kind).sort()).toEqual(["last_identity", "unlinked"]); + expect(await store.listStoredLinkedIdentitiesForAccount(a.id)).toHaveLength(1); + }); +}); + describe("consent_receipts foreign key", () => { it("a revocation names a receipt of its own account: the schema says so and the memory store enforces it", async () => { expect(CREATE_SCHEMA_SQL).toContain("FOREIGN KEY (revokes_receipt_id, account_id) REFERENCES consent_receipts(id, account_id)"); @@ -496,6 +574,8 @@ async function exerciseStore(store: PostgresStore): Promise> { const linked = await s.upsertLinkedIdentity(identity); await s.updateLinkedIdentityCredential(linked.id, async () => ({ kind: "keep" })); await s.upsertLinkedIdentity({ ...identity, username: "again" }); + const spare = await s.upsertLinkedIdentity({ ...identity, providerUserId: "u-spare" }); + expect((await s.unlinkLinkedIdentity(account.id, spare.id)).kind).toBe("unlinked"); await s.findAccountByLinkedIdentity("discord", "u1"); await s.findStoredLinkedIdentity("discord", "u1"); await s.findStoredLinkedIdentityForAccount(account.id, "discord"); @@ -716,6 +796,41 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD } }); + it("startup refuses a role that lacks DELETE on linked_identities", async () => { + expect(STORE_TABLE_PRIVILEGES.linked_identities).toContain("DELETE"); + const { name, owner } = await appliedDatabase(); + await grant(owner, { ...STORE_TABLE_PRIVILEGES, linked_identities: ["SELECT", "INSERT", "UPDATE"] }); + expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); + }); + + it("on real Postgres: an upsert never moves an identity, and concurrent unlinks of the last two leave one", async () => { + const { name, owner } = await appliedDatabase(); + const clientA = new PostgresStore(owner); + const at = "2026-11-13T12:00:00.000Z"; + const a = await clientA.createAccount({ createdAt: at, lastSeenAt: at }); + const b = await clientA.createAccount({ createdAt: at, lastSeenAt: at }); + const base = { provider: "discord" as const, scopes: [], profileJson: {}, createdAt: at, updatedAt: at }; + const held = await clientA.upsertLinkedIdentity({ ...base, accountId: a.id, providerUserId: "u1", username: "original" }); + await expect(clientA.upsertLinkedIdentity({ ...base, accountId: b.id, providerUserId: "u1", username: "thief" })).rejects.toBeInstanceOf(IdentityHeldElsewhereError); + expect(await clientA.findStoredLinkedIdentity("discord", "u1")).toEqual(held); + + await clientA.upsertLinkedIdentity({ ...base, accountId: a.id, providerUserId: "u2" }); + // Two separate pools, as two Heimdall processes would be, race for the last two. + const other = fixturePool(urlFor(name)); + cleanup.push(async () => { + await other.end(); + }); + const storeB = new PostgresStore(other); + for (let round = 0; round < 10; round += 1) { + const [first, second] = await clientA.listStoredLinkedIdentitiesForAccount(a.id); + expect(first && second, `round ${round} starts with two`).toBeTruthy(); + const results = await Promise.all([clientA.unlinkLinkedIdentity(a.id, first!.id), storeB.unlinkLinkedIdentity(a.id, second!.id)]); + expect(results.map((r) => r.kind).sort(), `round ${round}`).toEqual(["last_identity", "unlinked"]); + expect(await clientA.listStoredLinkedIdentitiesForAccount(a.id)).toHaveLength(1); + await clientA.upsertLinkedIdentity({ ...base, accountId: a.id, providerUserId: `u-next-${round}` }); + } + }); + describe("oauth_state_uses retention", () => { const expMs = Date.parse("2026-04-26T12:10:00.000Z"); const boundary = expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS;