fix: preserve authorization security history
Two security records did not survive user deletion, because both hung off a cascading foreign key to the live Better Auth user row. Deleting a user with authorization history deleted that history. A subject with a create and a revoke audit row had zero rows afterwards: the record of what they had been granted, by whom, and when it was revoked disappeared at exactly the moment it mattered most. `ekklesia_core_authorization_audit.subject_user_id` is now a retained, non-null historical snapshot with no foreign key — a plain identifier that may name a user row which no longer exists. No name, email, or other profile data is copied into authorization tables. The Drizzle relation to the user table is dropped too, because modelling a retained snapshot as a live relation misdescribes the data. Live rows still cascade, as intended: deleting a user removes their grants and platform-owner row, so nothing continues authorizing a principal that no longer exists. Platform-owner bootstrap's single use was equally fragile. "Already consumed" meant "a row exists in ekklesia_core_platform_owner", and that table cascades too — so deleting the bootstrapped owner's user row removed the owner row, its audit evidence, and with them the only thing preventing the operation that establishes a platform's first administrator from being run again. A dedicated `ekklesia_core_platform_owner_bootstrap` singleton now carries that authority. Its id is pinned by a check constraint to the literal 'singleton', so the primary key makes a second row structurally impossible rather than merely unwritten by convention; it has no user foreign key, and Core never deletes from it. Bootstrap claims that record inside the same transaction as the owner row and its audit entry, so consumption is tied to success: a missing target user or any other failure rolls the sentinel back and leaves the one legitimate first use available. The existing transaction-scoped advisory lock still serializes concurrent first attempts to exactly one success. The operational consequence is deliberate and permanent: deleting the last platform owner does not reactivate bootstrap, and neither does revoking one. Core migration 0002_authorization_integrity creates the singleton table, drops the cascading audit-subject constraint, and backfills consumed state for any installation that already holds a platform-owner row — active or revoked — so an existing deployment cannot gain a fresh first use by upgrading. It records no subject, because a backfill cannot know which of several historical owner rows the original use targeted and guessing would fabricate history. A never-owned installation is untouched and keeps its one first use. One upgrade limitation is irrecoverable and is documented rather than papered over: if an operator manually deleted the bootstrapped owner's user row before this migration, the old cascade already erased the owner row and its audit evidence, so nothing remains to detect. At this checkpoint no supported Better Auth or API user-deletion path can produce that state; it requires direct database access. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
6b6b77c105
commit
532ce3803b
@@ -2,7 +2,12 @@ import type { EkklesiaUserId } from "@ekklesia/contracts";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { ekklesiaCoreUser } from "../identity/schema.js";
|
||||
import type { AuthorizationDrizzleDatabase } from "./database.js";
|
||||
import { ekklesiaCoreAuthorizationAudit, ekklesiaCorePlatformOwner } from "./schema.js";
|
||||
import {
|
||||
ekklesiaCoreAuthorizationAudit,
|
||||
ekklesiaCorePlatformOwner,
|
||||
ekklesiaCorePlatformOwnerBootstrap,
|
||||
PLATFORM_OWNER_BOOTSTRAP_SINGLETON_ID,
|
||||
} from "./schema.js";
|
||||
|
||||
export type PlatformOwnerBootstrapErrorCode =
|
||||
| "PLATFORM_OWNER_BOOTSTRAP_ALREADY_CONSUMED"
|
||||
@@ -54,17 +59,25 @@ export interface BootstrapPlatformOwnerInput {
|
||||
|
||||
/**
|
||||
* Core's dedicated, Hono-independent platform-owner bootstrap operation. Deliberately not a
|
||||
* composition of "check, then call the existing grant function": the single-use check, the target
|
||||
* composition of "check, then call the existing grant function": the single-use claim, the target
|
||||
* user's existence check, the owner-grant insert, and its audit entry are all one PostgreSQL
|
||||
* transaction, serialized by a transaction-scoped advisory lock acquired as the very first
|
||||
* statement — so two concurrent callers can never both observe "no owner yet" and both insert.
|
||||
* statement — so two concurrent callers can never both observe "not yet consumed" and both insert.
|
||||
* The second caller blocks on the lock until the first's transaction commits or rolls back, then
|
||||
* re-evaluates against the now-current state.
|
||||
*
|
||||
* "Already consumed" is global and permanent: it is true the moment
|
||||
* `ekklesia_core_platform_owner` has ever held any row for any user, including one whose
|
||||
* `revoked_at` is set — a later, separate owner-management flow (not part of this slice) is how a
|
||||
* platform owner would ever be re-established after a revocation, not this command.
|
||||
* **Single-use authority lives in `ekklesia_core_platform_owner_bootstrap`, never in the continued
|
||||
* existence of a platform-owner row.** The owner table's `user_id` cascades on user deletion, so
|
||||
* treating "an owner row exists" as the consumed marker meant deleting the bootstrapped owner's
|
||||
* user row silently reopened the one operation that establishes a platform's first administrator —
|
||||
* along with the audit evidence that it had ever run. The dedicated singleton has no user foreign
|
||||
* key, is never deleted by Core, and therefore survives owner revocation and user deletion alike.
|
||||
*
|
||||
* Consumption is deliberately tied to *success*: the sentinel is written inside the same
|
||||
* transaction as the owner row and its audit entry, so a missing target user, a constraint
|
||||
* violation, or any other failure rolls the sentinel back with everything else and leaves the one
|
||||
* legitimate first use still available. There is no reset command, deletion path, HTTP endpoint,
|
||||
* environment override, or force flag — by design, "consumed" is permanent.
|
||||
*/
|
||||
export async function bootstrapPlatformOwner(
|
||||
db: AuthorizationDrizzleDatabase,
|
||||
@@ -76,11 +89,11 @@ export async function bootstrapPlatformOwner(
|
||||
sql`select pg_advisory_xact_lock(${bootstrapLockNamespace}, ${bootstrapLockKey})`,
|
||||
);
|
||||
|
||||
const existingOwnerRows = await tx
|
||||
.select({ userId: ekklesiaCorePlatformOwner.userId })
|
||||
.from(ekklesiaCorePlatformOwner)
|
||||
const consumedRows = await tx
|
||||
.select({ id: ekklesiaCorePlatformOwnerBootstrap.id })
|
||||
.from(ekklesiaCorePlatformOwnerBootstrap)
|
||||
.limit(1);
|
||||
if (existingOwnerRows.length > 0) {
|
||||
if (consumedRows.length > 0) {
|
||||
throw new PlatformOwnerBootstrapError("PLATFORM_OWNER_BOOTSTRAP_ALREADY_CONSUMED");
|
||||
}
|
||||
|
||||
@@ -93,6 +106,15 @@ export async function bootstrapPlatformOwner(
|
||||
throw new PlatformOwnerBootstrapError("PLATFORM_OWNER_BOOTSTRAP_USER_NOT_FOUND");
|
||||
}
|
||||
|
||||
// The sentinel is claimed inside the same transaction as everything below it. The advisory
|
||||
// lock already serializes concurrent callers; the singleton primary key is the independent,
|
||||
// structural backstop that makes a second row impossible even if a future caller reached
|
||||
// this insert without the lock.
|
||||
await tx.insert(ekklesiaCorePlatformOwnerBootstrap).values({
|
||||
consumedForUserId: input.userId,
|
||||
id: PLATFORM_OWNER_BOOTSTRAP_SINGLETON_ID,
|
||||
});
|
||||
|
||||
await tx.insert(ekklesiaCorePlatformOwner).values({
|
||||
grantedByActorId: BOOTSTRAP_ACTOR_ID,
|
||||
grantedByActorType: BOOTSTRAP_ACTOR_TYPE,
|
||||
|
||||
@@ -72,11 +72,20 @@ export const ekklesiaCorePlatformOwner = pgTable(
|
||||
);
|
||||
|
||||
/**
|
||||
* Append-only: no update or delete path is ever exposed by Core's authorization store. `scope`
|
||||
* intentionally rejects an empty (but non-null) string — defense in depth matching the
|
||||
* application-layer `AuthorizationScope` contract, which never produces one — so a coding defect
|
||||
* that slipped an empty scope past that validation fails the whole grant-plus-audit transaction
|
||||
* atomically instead of recording a meaningless audit entry.
|
||||
* Append-only *by application convention*: Core's authorization store exposes no update or delete
|
||||
* path for these rows. That is a property of this codebase, not a database guarantee — no
|
||||
* PostgreSQL role, trigger, or rule prevents a database administrator, a future migration, or
|
||||
* anything else holding the same credentials from modifying them. `scope` intentionally rejects an
|
||||
* empty (but non-null) string — defense in depth matching the application-layer
|
||||
* `AuthorizationScope` contract, which never produces one — so a coding defect that slipped an
|
||||
* empty scope past that validation fails the whole grant-plus-audit transaction atomically instead
|
||||
* of recording a meaningless audit entry.
|
||||
*
|
||||
* `subject_user_id` is a **retained historical snapshot**, deliberately carrying no foreign key to
|
||||
* the live Better Auth user row. It previously cascaded on user deletion, which meant deleting a
|
||||
* user destroyed exactly the security history describing what that user had been granted and who
|
||||
* granted it — the audit trail disappeared precisely when it mattered most. The value stays a
|
||||
* plain, non-null identifier string; no name, email, or other profile data is ever copied here.
|
||||
*/
|
||||
export const ekklesiaCoreAuthorizationAudit = pgTable(
|
||||
"ekklesia_core_authorization_audit",
|
||||
@@ -85,9 +94,7 @@ export const ekklesiaCoreAuthorizationAudit = pgTable(
|
||||
action: text("action").notNull(),
|
||||
actorType: text("actor_type").notNull(),
|
||||
actorId: text("actor_id"),
|
||||
subjectUserId: text("subject_user_id")
|
||||
.notNull()
|
||||
.references(() => ekklesiaCoreUser.id, { onDelete: "cascade" }),
|
||||
subjectUserId: text("subject_user_id").notNull(),
|
||||
permissionId: text("permission_id"),
|
||||
scope: text("scope"),
|
||||
grantId: uuid("grant_id"),
|
||||
@@ -110,6 +117,40 @@ export const ekklesiaCoreAuthorizationAudit = pgTable(
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* The durable, single-row record meaning "platform-owner bootstrap was successfully consumed."
|
||||
*
|
||||
* Bootstrap's single-use authority previously came from the mere existence of a row in
|
||||
* `ekklesia_core_platform_owner` — which cascades on user deletion, so deleting the bootstrapped
|
||||
* owner's user row silently reopened the one-time operation that establishes the platform's first
|
||||
* administrator. This table exists specifically so that authority survives owner revocation and
|
||||
* user deletion: it has **no foreign key to any user**, and nothing in Core ever deletes from it.
|
||||
*
|
||||
* `id` is pinned by a check constraint to the single literal value `'singleton'`, so the primary
|
||||
* key makes a second row structurally impossible rather than merely unwritten by convention —
|
||||
* concurrent first attempts collide on the primary key inside their transactions.
|
||||
*
|
||||
* `consumed_for_user_id` is an optional historical snapshot of who bootstrap made an owner, in the
|
||||
* same retained-identifier style as the audit subject and carrying no profile data. It is null for
|
||||
* an installation whose consumed state was backfilled by migration, because a backfill cannot know
|
||||
* which of several historical owner rows the original single use actually targeted, and guessing
|
||||
* one would fabricate history.
|
||||
*/
|
||||
export const ekklesiaCorePlatformOwnerBootstrap = pgTable(
|
||||
"ekklesia_core_platform_owner_bootstrap",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
consumedAt: timestamp("consumed_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
consumedForUserId: text("consumed_for_user_id"),
|
||||
},
|
||||
(table) => [
|
||||
check("ekklesia_core_platform_owner_bootstrap_singleton_check", sql`${table.id} = 'singleton'`),
|
||||
],
|
||||
);
|
||||
|
||||
/** The only value `ekklesia_core_platform_owner_bootstrap.id` may ever hold. */
|
||||
export const PLATFORM_OWNER_BOOTSTRAP_SINGLETON_ID = "singleton";
|
||||
|
||||
export const ekklesiaCoreGrantRelations = relations(ekklesiaCoreGrant, ({ one }) => ({
|
||||
user: one(ekklesiaCoreUser, {
|
||||
fields: [ekklesiaCoreGrant.userId],
|
||||
@@ -127,19 +168,14 @@ export const ekklesiaCorePlatformOwnerRelations = relations(
|
||||
}),
|
||||
);
|
||||
|
||||
export const ekklesiaCoreAuthorizationAuditRelations = relations(
|
||||
ekklesiaCoreAuthorizationAudit,
|
||||
({ one }) => ({
|
||||
subject: one(ekklesiaCoreUser, {
|
||||
fields: [ekklesiaCoreAuthorizationAudit.subjectUserId],
|
||||
references: [ekklesiaCoreUser.id],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
// `ekklesiaCoreAuthorizationAudit` deliberately declares no `relations(...)` to the user table:
|
||||
// its subject is a retained historical identifier that may name a user row that no longer exists,
|
||||
// so modelling it as a live relation would misdescribe the data.
|
||||
|
||||
/** Explicit map passed to Drizzle, mirroring `identityAdapterSchema`'s explicit-mapping style. */
|
||||
export const authorizationSchema = {
|
||||
authorizationAudit: ekklesiaCoreAuthorizationAudit,
|
||||
grant: ekklesiaCoreGrant,
|
||||
platformOwner: ekklesiaCorePlatformOwner,
|
||||
platformOwnerBootstrap: ekklesiaCorePlatformOwnerBootstrap,
|
||||
} as const;
|
||||
|
||||
Reference in New Issue
Block a user