<a id="permissions-in-postgres-spicedb"></a>

# Permissions in Postgres & SpiceDB

Dads splits authorization into two layers: a database-free permission model ([`@dads-framework/access`](https://dadsframework.dev/docs/package-access)) and an execution engine ([`@dads-framework/postgres-access`](https://dadsframework.dev/docs/package-postgres-access) for PostgreSQL, or [`@dads-framework/authorization`](https://dadsframework.dev/docs/package-authorization) for SpiceDB).

Your domains import only `@dads-framework/access`. Business logic and unit tests stay database-free, while production checks execute inside PostgreSQL transactions.

![Transactional PostgreSQL ReBAC flow](https://dadsframework.dev/docs/source/website/site/assets/diagrams/postgres-rebac-transaction.svg)

<a id="1-declare-entities-roles-and-inheritance"></a>

## 1\. Declare entities, roles, and inheritance

Define typed entity handles and compose permissions with `access()` and `through()` (`apps/workbench/src/access.ts`):

```ts
export const workbenchUser = entityHandle({
  wireName: "user",
  idSchema: resourceId,
});
const workspaceEntity = entityHandle({
  wireName: "workspace",
  idSchema: resourceId,
  kind: "scope",
});
const taskEntity = entityHandle({
  wireName: "task",
  idSchema: resourceId,
  kind: "record",
});
const userDefinition = access(workbenchUser, {
  roles: {},
  permissions: () => ({}),
});
export const workbenchWorkspace = access(workspaceEntity, {
  roles: { owner: workbenchUser, member: workbenchUser },
  permissions: ({ owner, member }) => ({
    view: [asPermissionTerm([owner, member])],
    manage: [owner],
  }),
});
export const workbenchTask = access(taskEntity, {
  roles: { workspace: workspaceEntity },
  permissions: ({ workspace }) => ({
    view: [through(workspace, workbenchWorkspace.permissions.view)],
    manage: [through(workspace, workbenchWorkspace.permissions.manage)],
  }),
});

/** Task state, including claims, never grants independent access. */
export const workbenchAccessModel = accessModel([
  userDefinition,
  workbenchWorkspace,
  workbenchTask,
]);
```

Because `workbenchTask` inherits through `workspace`, revoking a user's workspace membership immediately revokes access to every task inside that workspace.

<a id="2-guard-writes-inside-a-serializable-postgres-transaction"></a>

## 2\. Guard writes inside a serializable Postgres transaction

Install the standalone packages in any PostgreSQL project (Node.js 22 or later):

```sh
npm install @dads-framework/access @dads-framework/postgres @dads-framework/postgres-access zod
```

When an operation mutates data, re-check the permission inside the same serializable transaction as the write using `withProtectedPostgresTransaction` (`assembly/protected-write.ts`):

```ts
export function createProtectedWrite(
  database: DrizzleHandle,
  authorization: PostgresAuthorization,
): WriteWithPermission {
  return async ({ subject, permission, resourceId }, write) => {
    try {
      return await withProtectedPostgresTransaction(
        { database, authorization },
        async ({ tx, authorization: scoped }) => {
          const allowed = await scoped.check({
            subject,
            permission: permission.permissionName,
            resource: { type: permission.entityWireName, id: resourceId },
          });
          if (!allowed)
            throw notFound("RESOURCE_NOT_FOUND", "Resource not found");
          return write(tx, scoped);
        },
      );
    } catch (fault) {
      if (fault instanceof PostgresSerializationConflict) {
        throw conflict(
          fault.code,
          "The transaction could not finish. Retry the request.",
          { retryable: true },
        );
      }
      throw fault;
    }
  };
}
```

Both the permission check and the business write share one PostgreSQL transaction snapshot. Removing a member and deleting their business rows commit or roll back together, with zero authorization outbox lag.

<a id="3-export-permission-guards-and-attach-them-to-routes"></a>

## 3\. Export permission guards and attach them to routes

Export named access handles from `domains/<feature>/access/index.ts` so routes stay declarative and share one policy definition (`domains/notes/access/index.ts`):

```ts
import { fromParam, type PermissionAccess } from "@dads-framework/http";
import { tenantAccess } from "../../../libraries/app-runtime/index.js";

export const notesPermission = tenantAccess.tenant.permissions.view;

/** Notes are visible only inside a tenant the account can view. */
export const notesAccess: PermissionAccess = {
  kind: "permission",
  resourceType: notesPermission.entityWireName,
  permission: notesPermission.permissionName,
  resourceId: fromParam("tenantId"),
};
```

Route enforcement runs in strict order:

1.  Missing or invalid session returns **`401 Unauthorized`**.
2.  Missing relationship returns **`404 Not Found`** before body or query validation runs, preventing existence leaks.
3.  Only authorized requests reach Zod validation and your handler.

<a id="4-test-grants-denials-and-revocations-without-a-database"></a>

## 4\. Test grants, denials, and revocations without a database

Use `@dads-framework/access/testing` to prove both allowed calls and fail-closed denials in fast unit tests. Every protected route should include at least one test verifying that a caller without a relationship receives `404`.

<a id="5-emit-spicedb-zed-from-the-same-model"></a>

## 5\. Emit SpiceDB `.zed` from the same model

If you already operate SpiceDB or outgrow a single PostgreSQL primary later, call `emitZed(model)` from `@dads-framework/access` to generate SpiceDB schema text directly from the same TypeScript model, then swap `PostgresAuthorization` for [`@dads-framework/authorization`](https://dadsframework.dev/docs/package-authorization) in `assembly/services.ts`. Domain files, route guards, and tests stay unchanged.

<a id="related-references"></a>

## Related references

*   [`@dads-framework/access`](https://dadsframework.dev/docs/package-access) for combinators (`through`, `both`, `excluding`), `grantable`, and `emitZed(model)`
*   [`@dads-framework/postgres-access`](https://dadsframework.dev/docs/package-postgres-access) for standalone setup, prepared point checks, lookup reuse, and benchmarks
*   [ADR 0001: Transactional PostgreSQL ReBAC](https://github.com/brytoncooper/dads-framework/blob/main/docs/decisions/0001-transactional-postgres-rebac.md)

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