<a id="permissions-cookbook-patterns"></a>

# Permissions Cookbook & Patterns

Source-backed, tested recipes and production best practices for `@dads-framework/access`, `@dads-framework/postgres-access`, `@dads-framework/sqlite-access`, and `@dads-framework/spicedb-access/migration`.

New here? Start with the [5-Minute Access Quickstart](https://dadsframework.dev/docs/permissions) first.

* * *

<a id="1-zero-dual-writes-with-columnrelations-91-smaller-storage"></a>

## 1\. Zero dual-writes with `columnRelations` (91× smaller storage)

Most SaaS apps already store ownership and hierarchy foreign keys on their own tables: `documents.org_id`, `documents.owner_id`, `folders.parent_id`. Copying 10 million of those rows into a separate relationship table wastes gigabytes of disk and creates a drift bug waiting to happen.

Instead, declare your normal model and bind single-target foreign keys directly with `columnRelations` (`packages/server/postgres-access/src/column-relations.integration.test.ts`):

```ts
function buildColumnAccessModel() {
  const user = actor("user");
  const org = resource("org", {
    roles: { admin: user, member: user },
    can: ({ admin, member }) => ({
      view: anyOf(admin, member),
      manage: admin,
    }),
  });
  const folder = resource("folder", {
    recursive: true,
    roles: {
      org,
      viewer: user,
    },
    can: ({ org: orgRole, viewer }) => ({
      view: anyOf(viewer, orgRole.view),
    }),
  });
  const doc = resource("document", {
    roles: {
      org,
      folder,
      owner: user,
      banned: user,
    },
    can: ({ org: orgRole, folder: folderRole, owner, banned }) => ({
      view: anyOf(owner, orgRole.view, folderRole.view).unless(banned),
      strict_org_view: every(orgRole).view,
    }),
  });
  return {
    model: compileAccess([user, org, folder, doc]),
    user,
    org,
    folder,
    doc,
  };
}

function createColumnBindings(schema: ReturnType<typeof buildColumnAccessModel>): readonly ColumnRelationBinding[] {
  return [
    {
      role: schema.folder.roles.org,
      table: "folders",
      idColumn: "id",
      targetIdColumn: "org_id",
    },
    {
      role: schema.folder.roles.parent,
      table: "folders",
      idColumn: "id",
      targetIdColumn: "parent_id",
    },
    {
      role: schema.doc.roles.org,
      table: "documents",
      idColumn: "id",
      targetIdColumn: "org_id",
    },
    {
      role: schema.doc.roles.folder,
      table: "documents",
      idColumn: "id",
      targetIdColumn: "folder_id",
    },
    {
      role: schema.doc.roles.owner,
      table: "documents",
      idColumn: "id",
      targetIdColumn: "owner_id",
    },
  ];
}
```

At startup, verify live columns and index status with `verifyColumnRelations()`, and generate recommended `(targetIdColumn, idColumn)` index DDL with `columnRelationIndexSql(bindings)` (`packages/server/postgres-access/src/column-relations.integration.test.ts`):

```ts
    const beforeIndexes = await authz.verifyColumnRelations();
    expect(beforeIndexes.every((entry) => !entry.hasRecommendedIndex)).toBe(true);
    for (const ddl of columnRelationIndexSql(bindings)) {
      await postgres.pool.query(ddl);
    }
    const afterIndexes = await authz.verifyColumnRelations();
    expect(afterIndexes.every((entry) => entry.hasRecommendedIndex)).toBe(true);
```

<a id="best-practice-rule-what-goes-where"></a>

### Best-practice rule: what goes where?

| Put in `columnRelations` (your app table) | Keep in `dad_authorization_relationship` (tuple table) |
| :-- | :-- |
| Single-target parent FKs (`documents.org_id`, `tasks.project_id`) | Org & team memberships (`org#member`, `team#admin`) |
| Direct actor FKs (`documents.owner_id`, `tickets.assignee_id`) | Group usersets (`group#member`), public wildcards (`user:*`) |
| Recursive self-FKs (`folders.parent_id`) — cycles terminate safely | Expiring grants (`expiresAt`), explicit bans (`.unless(banned)`) |
| Schema-qualified tables (`app.documents`) | Polymorphic multi-type links (`parents: [org, folder]`) |

<a id="safety-guarantees-guardrails"></a>

### Safety guarantees & guardrails

*   **Impossible drift:** Calling `writeRelationships` or `deleteRelationships` on a column-backed relation throws immediately (`Relation document#org is column-backed by documents.org_id; update the application table directly`).
*   **`NULL` = absent:** Setting `documents.owner_id = NULL` revokes ownership immediately in the same SQL `UPDATE`.
*   **Single-row moves & revokes:** Moving a folder with 100k child docs updates **1 row** (`folders.parent_id`), and revoking an org admin deletes **1 row** (`org#admin`) — zero 100k-row fan-out updates.
*   **UUID and text columns both work natively:** `columnRelations` casts comparisons and `UNION` projections cleanly so native PostgreSQL `uuid` primary/foreign keys and `text` IDs both work across `check`, `checkMany`, `lookupResources`, `lookupSubjects`, `compileFilter`, and `resolveFilter`. For multi-API apps (customer vs. staff), use `filterColumnRelationsForModel(model, bindings)` so each host binds only the entities mounted in its model.
*   **Protecting permission-bearing columns:** Because `columnRelations` reads your table columns directly, exclude `org_id`, `owner_id`, and `parent_id` from general `PATCH` DTOs, put an immutability `BEFORE UPDATE` trigger on tenant columns like `org_id` that should never change after `INSERT`, and chunk intentional bulk transfers (1,000–5,000 rows per transaction).
*   **10M-row measured win:** On a live 10,000,000-row logged PostgreSQL database (Run B), enabling `columnRelations` shrank `dad_authorization_relationship` from **2.73 GB → 30 MB (91× smaller)**, sustained **2,479 checks/sec (8 workers) / 2,492 checks/sec (16 workers) on 1 vCPU** (and **8,274 checks/sec on 3 vCPUs**), and jumped mixed reads + live `UPDATE` permission flips from **4,603 → 6,802 ops/sec (+48%)** with **0 errors**. See [Benchmarks & Proof](https://dadsframework.dev/docs/benchmarks-and-proof).

* * *

<a id="2-fast-paginated-lists-on-10m-rows-resolvefilter-scopecolumns-auto"></a>

## 2\. Fast paginated lists on 10M rows (`resolveFilter` + `scopeColumns: "auto"`)

Never load 1,000,000 authorized IDs into Node just to render page 1 (`LIMIT 50`). Embed a compiled authorization filter directly into your SQL `WHERE` clause (`packages/server/postgres-access/src/column-relations.integration.test.ts`):

```ts
    const resolvedFilter = await authz.resolveFilter({
      subject: { type: "user", id: "alice" },
      permission: "view",
      resourceType: "document",
      idColumn: "doc.id",
      scopeColumns: "auto",
    });
    expect(resolvedFilter.sql).toContain("(doc.org_id)::text = ANY");
    const resolvedRows = await postgres.pool.query<{ id: string }>(
      `SELECT doc.id FROM documents doc WHERE ${resolvedFilter.sql} ORDER BY doc.id`,
      [...resolvedFilter.values],
    );
    expect(resolvedRows.rows.map((row) => row.id)).toEqual(["doc-org"]);
```

<a id="why-resolvefilter-beats-plain-compilefilter-on-large-tables"></a>

### Why `resolveFilter` beats plain `compileFilter` on large tables

When a permission has multiple ways in (for example `anyOf(owner, viewer, org.view).unless(banned)`), an SQL `OR` across two different columns (`doc.id IN (...) OR doc.org_id IN (...)`) often prevents Postgres from doing a single clean index scan.

`resolveFilter` executes one tiny tagged index probe, **prunes every empty branch**, and emits minimal `= ANY($N::text[])` predicates:

*   **User with 0 access:** returns `sql: "FALSE"` in **0.39 ms** without scanning `documents`.
*   **Org member (1,000 docs out of 10M):** prunes the empty `owner`/`viewer` branches and hits `Index Only Scan` on `(org_id, updated_at DESC, id)` in **0.62 ms** (`Heap Fetches: 0`).
*   **Broad admin (1,000,000 docs across 1,000 orgs out of 10M):** finishes in **1.88 ms**.

> **Best practice:** Add a composite index on `(org_id, updated_at DESC, id)` (matching your `ORDER BY` key) alongside `columnRelationIndexSql(bindings)`. Use `paramOffset` when embedding after existing `$1..$k` parameters. On SQLite, use `authz.compileFilter({ ..., scopeColumns: "auto" })`.

* * *

<a id="3-complex-graphs-nested-folders-teams-wildcards-expiry-every"></a>

## 3\. Complex graphs: nested folders, teams, wildcards, expiry & `every()`

Dads supports the full Zanzibar permission algebra in plain TypeScript — every combinator works identically across PostgreSQL, SQLite, SpiceDB, and the in-memory test harness (`packages/access/src/testing/access-harness.test.ts`):

```ts
function buildTestSchema() {
  const user = actor("user");
  const groupMemberRef = roleToken("app/group", "member", user.handle);
  const group = resource("app/group", {
    roles: {
      member: [user.expiring, user.anyone.expiring, groupMemberRef],
    },
    can: ({ member }) => ({ read: member }),
  });
  const workspace = resource("app/workspace", {
    roles: {
      owner: user.expiring,
      member: [user.expiring, group.roles.member.expiring, user.anyone],
      banned: user,
    },
    can: ({ owner, member, banned }) => ({
      view: anyOf(owner, member).unless(banned),
      admin: owner.unless(banned),
    }),
  });
  const folder = resource("app/folder", {
    parents: [workspace],
    recursive: true,
    roles: {
      viewer: user.expiring,
    },
    can: ({ parents, viewer }) => ({
      view: anyOf(viewer, parents.view),
    }),
  });
  const document = resource("app/document", {
    parents: [workspace, folder],
    roles: {
      viewer: [user.expiring, group.roles.member, user.anyone],
      approver: user,
      banned: user,
    },
    can: ({ parents, viewer, approver, banned }) => ({
      view: anyOf(parents.view, viewer).unless(banned),
      strict_view: every(parents).view,
      publish: allOf(viewer, approver).unless(banned),
    }),
  });
  return {
    user,
    group,
    workspace,
    folder,
    document,
    model: compileAccess([user, group, workspace, folder, document]),
  };
}
```

*   **Nested cyclic groups:** `roleToken("app/group", "member", user.handle)` allows `group#member` inside `group#member` — cycles terminate safely.
*   **Self-nested folders (`recursive: true`):** automatically wires `parent->view` and terminates safely even if cyclic `parent_id` rows exist.
*   **Universal intersection (`every(parents).view`):** fails closed (`false`) when a resource has zero active parents, and requires `view` on every active parent otherwise.

* * *

<a id="4-protected-writes-automatic-40001-retries"></a>

## 4\. Protected writes & automatic `40001` retries

Always re-check permissions inside the same database transaction that performs the write — otherwise a concurrent revoke between your route guard and your `UPDATE` can slip through. Pass `retries` to `withProtectedPgTransaction` to recover automatically from PostgreSQL `40001` serialization conflicts (`packages/server/postgres-access/src/column-relations.integration.test.ts`):

```ts
    // Update inside a protected serializable transaction; scoped authz preserves columnRelations.
    await withProtectedPgTransaction(
      { pool: postgres.pool, authorization: authz, retries: 2 },
      async ({ client, authorization: scoped }) => {
        await client.query("UPDATE documents SET owner_id = 'alice' WHERE id = 'doc-null'");
        expect(
          await scoped.check({
            subject: { type: "user", id: "alice" },
            permission: "view",
            resource: { type: "document", id: "doc-null" },
          }),
        ).toBe(true);
      },
    );
```

*   **Keep callbacks idempotent** when `retries > 0` (pure DB reads/writes inside the transaction — do not send emails or charge cards inside the retry loop).
*   **Scoped handles expire automatically** as soon as the callback returns or throws, making it impossible to leak a transaction client.
*   **SQLite equivalent:** `withProtectedSqliteTransaction({ executor, authorization, now }, work)` runs inside `BEGIN IMMEDIATE` with a single pinned clock snapshot.

* * *

<a id="5-testing-pyramid-microseconds-in-memory-sqlite-postgres"></a>

## 5\. Testing pyramid: microseconds in memory → SQLite → Postgres

<a id="layer-1-zero-await-policy-unit-tests-dads-frameworkaccesstesting"></a>

### Layer 1: Zero-`await` policy unit tests (`@dads-framework/access/testing`)

`createAccessHarness(model)` runs our `InMemoryAuthorization` engine synchronously — differentially tested against the Lean 4 oracle with zero mismatches, no Docker, no `async`/`await`, deterministic clock (`advanceTime`), cycle safety, and decision explanation trees on failure (`packages/access/src/testing/access-harness.test.ts`):

```ts
    const access = createAccessHarness(model);
    const alice = access.actor(user, "alice");
    const bob = user("bob");
    const stranger = access.actor(user, "stranger");

    // Mix token style and instance-proxy style seamlessly, zero awaits
    access.grant(workspace.roles.owner, "workspace-1").to(alice);
    access.grant(folder.roles.parent, "folder-1").to(workspace, "workspace-1");
    access.grant(folder.roles.parent, "folder-2").to(folder, "folder-1");
    // Deliberate folder cycle: folder-1 -> folder-2 -> folder-1
    access.grant(folder.roles.parent, "folder-1").to(folder, "folder-2");
    access.grant(document("doc-1").parent).to(folder("folder-2"));

    // Group + expiring direct grant for Bob
    access.grant(group.roles.member, "team-1").expiringIn("1h").to(bob);
    access.grant(document.roles.viewer, "doc-1").to(access.members(group.roles.member, "team-1"));
    access.grant(document.roles.approver, "doc-1").to(bob);

    access.assertCan(alice, document.permissions.view, "doc-1");
    access.assertCan(bob, document("doc-1").publish);
    access.assertCannot(stranger, document.permissions.view, "doc-1");
    access.assertVisible(alice, document.permissions.view, ["doc-1"]);

    // Advance clock past 1h: Bob's group membership expires
    access.advanceTime("2h");
    access.assertCannot(bob, document.permissions.view, "doc-1");
    access.assertCannot(bob, document.permissions.publish, "doc-1");

    // Ban overrides Alice's inherited workspace ownership
    access.grant(document.roles.banned, "doc-1").to(alice);
    access.assertCannot(alice, document.permissions.view, "doc-1");

    // Revoking the ban restores Alice's inherited access
    access.revoke(document.roles.banned, "doc-1").from(alice);
    access.assertCan(alice, document.permissions.view, "doc-1");
```

<a id="layer-2-instant-sql-filter-parity-tests-in-sqlite-dads-frameworksqlite-accesstesting"></a>

### Layer 2: Instant SQL & filter parity tests in SQLite (`@dads-framework/sqlite-access/testing`)

Prove your compiled SQL filters return the exact same rows as `lookupResources` in ~5 ms with zero Docker (`packages/server/sqlite-access/src/testing.test.ts`):

```ts
    using testEnv = createSqliteTestAuthorization(model);

    testEnv.db.exec("CREATE TABLE app_documents (id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL);");
    const insertDoc = testEnv.db.prepare("INSERT INTO app_documents (id, workspace_id) VALUES (?, ?)");
    insertDoc.run("doc-1", "workspace-1");
    insertDoc.run("doc-2", "workspace-1");
    insertDoc.run("doc-3", "workspace-2");

    const alice = user("alice");
    const bob = user("bob");
    const stranger = user("stranger");

    await proveAccess(model, { authorization: testEnv.authorization, clock: testEnv.clock }, (scenario) => {
      scenario.grant(workspace.roles.owner, "workspace-1").to(alice);
      scenario.grant(document.roles.scope_workspace, "doc-1").to(workspace, "workspace-1");
      scenario.grant(document.roles.scope_workspace, "doc-2").to(workspace, "workspace-1");
      scenario.grant(document.roles.scope_workspace, "doc-3").to(workspace, "workspace-2");
      scenario.grant(document.roles.banned, "doc-2").to(alice);
      scenario.grant(document.roles.viewer, "doc-3").expiringIn("30m").to(bob);

      scenario.assertCan(alice, document.permissions.view, "doc-1");
      scenario.assertCannot(alice, document.permissions.view, "doc-2");
      scenario.assertCan(bob, document.permissions.view, "doc-3");
      scenario.assertVisible(alice, document.permissions.view, ["doc-1"]);

      scenario.advanceTime("1h");
      scenario.assertCannot(bob, document.permissions.view, "doc-3");
    });

    await proveSqliteFilterParity({
      db: testEnv.db,
      authorization: testEnv.authorization,
      table: "app_documents",
      idColumn: "id",
      permission: document.permissions.view,
      scopeColumns: { scope_workspace: "workspace_id" },
      subjects: [alice, bob, stranger],
    });
```

<a id="layer-3-postgres-filter-parity-dads-frameworkpostgres-accesstesting"></a>

### Layer 3: Postgres filter parity (`@dads-framework/postgres-access/testing`)

Call `provePostgresFilterParity({ db: pool, authorization, table: "documents", idColumn: "id", permission: document.permissions.view, scopeColumns: "auto", subjects })` in integration tests to prove `compileFilter`, `resolveFilter`, and `lookupResources` return identical row sets against your real Postgres schema.

* * *

<a id="6-migrations-two-way-spicedb-portability"></a>

## 6\. Migrations & two-way SpiceDB portability

<a id="evolving-your-model-safely-from-to-migrations"></a>

### Evolving your model safely (`(from, to)` migrations)

Use `diffAccessModels(v1, v2)` (or `npx dad access diff v1.ts v2.ts`) to detect breaking tuple changes, declare portable steps with `defineAccessMigration` (`copyRole`, `dropRole`, `copyParent`, `dropParent`), apply them with `runPostgresAccessMigrations` / `runSqliteAccessMigrations` / `runSpiceDbAccessMigrations`, and fail boot if behind with `assertAccessMigrationsUpToDate`.

<a id="migrating-from-spicedb-postgresql-zero-downtime"></a>

### Migrating FROM SpiceDB → PostgreSQL (zero downtime)

```sh
npx dads-import-spicedb \
  --endpoint localhost:50051 \
  --token "$SPICEDB_TOKEN" \
  --database-url "$DATABASE_URL" \
  --namespace acme \
  --out ./src/access.ts \
  --verify
```

1.  Streams schema + all tuples (`subject_relation`, wildcards, `expiresAt`) into Postgres and generates typed Dads TypeScript.
2.  `--verify` runs `verifySpiceDbPostgresParity` to confirm 0 mismatches.
3.  Wrap both in `new ShadowAuthorization({ primary: spiceDb, shadow: postgres, mode: "shadow-read" })`, verify 0 live mismatches, flip to `"primary-new"`, and retire SpiceDB.

<a id="migrating-from-postgresql-even-with-columnrelations-spicedb"></a>

### Migrating FROM PostgreSQL (even with `columnRelations`) → SpiceDB

If you ever outgrow a single Postgres cluster and want a dedicated multi-region SpiceDB deployment, you are **not locked in** — even if you used `columnRelations` everywhere (`packages/server/spicedb-access/src/migration/lib/postgres-to-spicedb/postgres-to-spicedb.integration.test.ts`):

```ts
    const exportedTuples: SpiceDbExportedTuple[] = [];
    const migration = await migratePostgresToSpiceDb({
      model: schema.model,
      postgres: pool,
      spiceDb: rawSpiceClient,
      namespace: "exit-ns",
      columnRelations: bindings,
      batchSize: 3,
      pageSize: 2,
      onBatch: (batch) => exportedTuples.push(...batch),
    });

    // 4 active tuples (expired-user skipped) + 6 non-NULL column-backed FK edges = 10 total!
    expect(migration.tupleTableCount).toBe(4);
    expect(migration.columnRelationCount).toBe(6);
    expect(migration.totalWrittenCount).toBe(10);

    const parity = await verifySpiceDbPostgresParity({
      spiceDb: spiceAuth,
      postgres: pgAuth,
      definitions: migration.definitions,
      tuples: exportedTuples,
      negativeSubjectIds: ["stranger", "expired-user"],
    });
    expect(parity.total).toBeGreaterThan(20);
    expect(parity.mismatches).toEqual([]);

    // Install outbox sync triggers and prove live INSERT/UPDATE/DELETE feed authorization_outbox automatically!
    const triggers = columnRelationOutboxTriggerSql(schema.model, bindings);
    for (const statement of triggers.up) {
      await pool.query(statement);
    }
```

1.  `columnRelationOutboxTriggerSql(model, bindings)` creates Postgres triggers so future `INSERT`/`UPDATE`/`DELETE` writes to column-backed tables automatically feed `authorization_outbox` — **zero app-code rewrites**.
2.  `migratePostgresToSpiceDb` emits & writes `.zed`, streams active rows from `dad_authorization_relationship`, and materializes every non-`NULL` `columnRelations` row via keyset pagination into idempotent SpiceDB `TOUCH` writes.
3.  `verifySpiceDbPostgresParity` proves **0 decision mismatches** before switching traffic.

* * *

<a id="7-formal-verification-proof-guarantees"></a>

## 7\. Formal verification & proof guarantees

Unlike hand-rolled RBAC or untyped SQL helpers, Dads' authorization semantics and SQL compiler optimizations are **machine-checked in Lean 4** ([`formal/access-proofs`](https://github.com/brytoncooper/dads-framework/blob/main/formal/access-proofs/README.md)):

*   **27 zero-`sorry` Lean 4 theorems** (standard axioms only) proving:
    *   Fail-closed unknown permissions and non-vacuous `every()` (`throughAll`)
    *   Exact expiration cutoff (`expires_at <= now` never grants access)
    *   `.unless()` exclusion dominance and revocation monotonicity (deleting tuples can never escalate access)
    *   Strict namespace isolation
    *   Least-fixed-point stability on cyclic graphs (cycles never self-justify)
    *   Forward-vs-reverse equivalence (`check` ⇔ `lookupResources` ⇔ `compileFilter`)
    *   Multi-`scopeColumns`, `resolveFilter` branch pruning, per-relation userset shortcut, and **`columnRelations` equivalence**
*   **Native Lean 4 differential oracle (`dads-access-oracle`):** Continuously compares live PostgreSQL, SQLite, and `InMemoryAuthorization` against the verified Lean 4 evaluator (**0 mismatches** across 1,300 randomized schemas and 299,200 queries).

See [BENCHMARK.md](https://github.com/brytoncooper/dads-framework/blob/main/packages/server/postgres-access/BENCHMARK.md) for full 10M-row numbers and `EXPLAIN (ANALYZE, BUFFERS)` query plans.

Canonical page: <https://dadsframework.dev/docs/permissions-cookbook>
