Browse documentation

Permissions in Postgres & SpiceDB

On this page

Dads splits authorization into two layers: a database-free permission model (@dads-framework/access) and an execution engine (@dads-framework/postgres-access for PostgreSQL, or @dads-framework/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

1. Declare entities, roles, and inheritance

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

TypeScript
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.

2. Guard writes inside a serializable Postgres transaction

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

Shell
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):

TypeScript
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.

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):

TypeScript
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.

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.

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 in assembly/services.ts. Domain files, route guards, and tests stay unchanged.