Attribute-Based Access Control in TypeScript: Building an ABAC Policy Engine
Build an ABAC policy engine in TypeScript with the builder pattern, conditional permissions, and type-safe policy evaluation that replaces RBAC's limitations.
Post 103 built type-safe RBAC with a can(role, resource, action) function and a declarative permission matrix. Adding a role stays a one-line change, and server and client share a single source of truth. But contextual decisions (ownership, department scoping, document status) stay outside that matrix as custom helper functions. canModifyDocument, canEditInDepartment, and canPublishInReviewStatus proliferate alongside can(), each an if/else chain the type system cannot verify.
The fix is to move those conditions into the policy itself. ABAC (Attribute-Based Access Control), formalized by NIST SP 800-162, evaluates attributes of four entities: the subject (user), the resource (object), the action (operation), and the environment (context). Instead of can(role, 'document', 'update') plus a separate ownership check, one policy decision covers both.
For a TypeScript application, that engine fits in a builder-pattern policy store. Ownership, department scoping, and resource state become declarative rules, and generics type-check each rule against the resource’s data shape. Project membership stays where Post 103 put it: the role the policy sees is the one the user holds in the project. The service layer architecture from Post 102 does not change; only the can() signature evolves.
The ABAC Model#
From Roles to Attributes#
RBAC’s core question: “Does this role have this permission?”
ABAC’s core question: “Given the subject’s attributes, the resource’s attributes, this action, and the environment, does the policy allow access?”
The shift: RBAC is a lookup (role -> permission set -> yes/no). ABAC is an evaluation (attributes -> policy engine -> decision).
NIST SP 800-162: The Four Attribute Categories#
NIST Special Publication 800-162 defines ABAC as “a logical access control methodology where authorization to perform a set of operations is determined by evaluating attributes associated with the subject, object, requested operations, and, in some cases, environment conditions.”
The four categories:
-
Subject Attributes: Properties of the user requesting access: role, department, userId, clearance level. In our domain:
session.role,session.userId,session.departmentId. -
Resource (Object) Attributes: Properties of the resource being accessed: owner, status, classification. In our domain:
document.authorId,document.status,document.project.departmentId. -
Action Attributes: The operation being requested: create, read, update, delete, publish. Same as RBAC’s actions, but ABAC can attach conditions to specific action-resource combinations.
-
Environment Attributes: Contextual conditions external to the subject and resource: current time, IP address, feature flags. In our domain: business hours, feature flags.
How ABAC Evaluates a Request#
In enterprise ABAC (XACML), the architecture includes PEP, PDP, PIP (Policy Information Point), and PAP (Policy Administration Point) as separate services. For application-level TypeScript, the service layer is the PEP and the can() function is the PDP. Attributes come from the already-loaded session and database objects; no separate PIP/PAP needed.
One subject attribute still needs a lookup: the role. In the project model from Post 103, a user is an editor in one project and a viewer in another, so the role is stored in project.members. The service layer loads the members with the document and resolves the role before calling can(). That query is the application’s PIP step: XACML describes a PIP as a source of attribute values, and here the source is the relation the service already reads.
ABAC in Our Domain#
Mapping the NIST model to the running example from Posts 101-103:
| NIST Concept | RBAC (Post 103) | ABAC (Post 104) |
|---|---|---|
| Decision Input | Role only | Subject + Resource + Action + Environment |
| Decision Logic | Map lookup | Condition evaluation |
| ”Member of this project?” | Project-scoped role from effectiveRole() | Same role, resolved before can() |
| ”Can edit own docs?” | Helper function outside can() | Condition: subject.userId === resource.authorId |
| ”Only in department” | Helper function outside can() | Condition: sameDepartment (null-safe) |
| “Only draft status” | Cannot express | Condition: resource.status === 'draft' |
| Adding a contextual rule | Write a new helper function | Add a condition to the policy |
TypeScript Type System for ABAC#
Resource Types with Data Shapes#
In RBAC, resources were just string literals ('document' | 'project'). ABAC needs to know the shape of each resource’s data so conditions can reference attributes type-safely.
// lib/permissions.ts
// Role, Action, ROLES and effectiveRole() carry over from Post 103
// The subject -- role is the project-scoped role, not the session's
export interface User {
userId: string;
role: Role;
departmentId?: string; // optional: not every user has a department
}
// Resource data shapes -- what attributes each resource has
interface ResourceDataMap {
document: {
authorId: string;
status: 'draft' | 'published' | 'archived';
projectId: string;
departmentId: string;
};
project: {
ownerId: string;
departmentId: string;
isArchived: boolean;
};
}
export type Resource = keyof ResourceDataMap;
This is the fundamental type-level shift from Post 103. Resource is still a string key, but it maps to a data type. When a policy says “the document’s authorId must equal the user’s userId,” TypeScript can verify that authorId actually exists on the document type.
Conditions as Types#
Conditions are functions that evaluate subject and resource attributes. The type system ensures conditions reference valid attributes:
// A condition receives the user and resource data,
// returns true (allow) or false (deny)
type Condition<R extends Resource> = (
user: User,
data: ResourceDataMap[R]
) => boolean;
The generic parameter R extends Resource links the condition to a specific resource type. A condition for 'document' receives ResourceDataMap['document']. TypeScript knows the shape includes authorId, status, projectId, departmentId. Referencing data.nonexistent is a compile-time error.
The Permission Store Type#
The permission store replaces ROLE_PERMISSIONS from Post 103. Instead of a flat map from roles to permission strings, it maps roles to resource-action pairs with optional conditions:
interface PermissionEntry<R extends Resource> {
effect: 'allow' | 'deny';
resource: R;
actions: Action[];
conditions?: Condition<R>[];
}
// The full permission store: role -> array of permission entries
type PermissionStore = {
[R in Role]: PermissionEntry<Resource>[];
};
Each PermissionEntry says: “For this resource, allow (or deny) these actions, optionally only if these conditions are met.” If conditions is undefined or empty, the entry applies to every resource of that type (same as RBAC). If conditions are present, ALL must evaluate to true (AND logic). Allow entries grant; a matching deny entry overrides every allow, which is how a rule such as “archived documents are read-only” holds for all roles at once.
RBAC Types vs. ABAC Types#
A side-by-side comparison makes the evolution visible:
// Post 103 (RBAC) -- flat permission strings
type Permission = `${Resource}:${Action}`;
const ROLE_PERMISSIONS: Record<Role, readonly Permission[]>;
function can(role: Role, resource: Resource, action: Action): boolean;
// Post 104 (ABAC) -- conditions on resource data
interface PermissionEntry<R extends Resource> {
effect: 'allow' | 'deny';
resource: R;
actions: Action[];
conditions?: Condition<R>[];
}
type PermissionStore = { [R in Role]: PermissionEntry<Resource>[] };
function can<R extends Resource>(
user: User,
action: Action,
resource: R,
data?: ResourceDataMap[R]
): boolean;
The can() function now receives the full user object, which also carries the role, and optionally the resource data. If a permission has conditions, the data is needed for evaluation. If no conditions exist (like admin’s unconditional access), data can be omitted. The user object is not the raw session: its role is the project-scoped role, resolved the way Post 103 resolved it.
Permission Builder Pattern#
Why a Builder?#
Directly constructing the PermissionStore object is verbose and error-prone:
// Without builder -- verbose, hard to read
const store: PermissionStore = {
admin: [
{ effect: 'allow', resource: 'document', actions: ['create', 'read', 'update', 'delete', 'publish'] },
{ effect: 'allow', resource: 'project', actions: ['create', 'read', 'update', 'delete'] },
],
editor: [
{ effect: 'allow', resource: 'document', actions: ['read'] },
{
effect: 'allow',
resource: 'document',
actions: ['create', 'update', 'publish'],
conditions: [
(user, doc) =>
user.departmentId != null && user.departmentId === doc.departmentId,
],
},
{ effect: 'allow', resource: 'project', actions: ['read'] },
],
// ... more roles, and every rule meant for all roles copied into each
};
A builder pattern provides a fluent API that reads like a policy declaration.
The PermissionBuilder Class#
export class PermissionBuilder {
private store: PermissionStore = {
admin: [],
editor: [],
author: [],
viewer: [],
};
// Start defining permissions for a role
role(role: Role): RoleBuilder {
return new RoleBuilder(this, this.store, role);
}
// Deny for every role, whatever the allow entries say
forbid<R extends Resource>(
actions: Action | Action[],
resource: R,
conditions?: Condition<R>[]
): this {
for (const role of ROLES) {
addEntry(this.store, role, 'deny', actions, resource, conditions);
}
return this;
}
build(): PermissionStore {
return this.store;
}
}
export class RoleBuilder {
constructor(
private root: PermissionBuilder,
private store: PermissionStore,
private currentRole: Role
) {}
// Grant permissions on a resource, optionally with conditions
can<R extends Resource>(
actions: Action | Action[],
resource: R,
conditions?: Condition<R>[]
): RoleBuilder {
addEntry(this.store, this.currentRole, 'allow', actions, resource, conditions);
return this;
}
// Switch to another role
role(role: Role): RoleBuilder {
return this.root.role(role);
}
// Global denies may follow the role blocks
forbid<R extends Resource>(
actions: Action | Action[],
resource: R,
conditions?: Condition<R>[]
): PermissionBuilder {
return this.root.forbid(actions, resource, conditions);
}
build(): PermissionStore {
return this.store;
}
}
function addEntry<R extends Resource>(
store: PermissionStore,
role: Role,
effect: 'allow' | 'deny',
actions: Action | Action[],
resource: R,
conditions?: Condition<R>[]
): void {
store[role].push({
effect,
resource,
actions: Array.isArray(actions) ? actions : [actions],
conditions,
// Widening cast: from here on, TypeScript no longer ties
// the conditions to R. The runtime resource check in can() does.
} as PermissionEntry<Resource>);
}
Key points about this design:
RoleBuilder.can()andforbid()are generic onR extends Resource. The conditions array is typed to the specific resource, so TypeScript checks that condition functions reference valid attributes.- Method chaining via
return thisenables the fluent API. forbid()writes one deny entry into every role’s list. A rule that must hold for everyone is declared once.- The builder pattern separates construction from representation. The final
PermissionStoreis a plain object, but the construction process is guided and type-checked. - The type check stops at the store.
Condition<'document'>is not assignable toCondition<'document' | 'project'>understrict, soaddEntry()widens each entry with a cast, andcan()narrows it back with another. Both casts are safe only becausecan()filters entries byresourceat runtime.
Using the Builder#
// Null-safe department match: a missing value never equals another
const sameDepartment = (
user: User,
data: { departmentId: string | null | undefined }
): boolean =>
user.departmentId != null && user.departmentId === data.departmentId;
export const permissions = new PermissionBuilder()
// Admin: every action on every resource
.role('admin')
.can(['create', 'read', 'update', 'delete', 'publish'], 'document')
.can(['create', 'read', 'update', 'delete'], 'project')
// Editor: reads every document in the project,
// writes inside their own department
.role('editor')
.can('read', 'document')
.can(['create', 'update', 'publish'], 'document', [sameDepartment])
.can('read', 'project')
// Author: published documents plus their own
.role('author')
.can('read', 'document', [(user, doc) => doc.status === 'published'])
.can(['create', 'read', 'update'], 'document', [
(user, doc) => doc.authorId === user.userId,
])
.can('read', 'project')
// Viewer: published documents only
.role('viewer')
.can('read', 'document', [(user, doc) => doc.status === 'published'])
.can('read', 'project')
// Global denies: no role overrides these
.forbid(['update', 'publish'], 'document', [
(user, doc) => doc.status === 'archived',
])
.forbid('publish', 'document', [
(user, doc) => doc.authorId === user.userId, // separation of duty
])
.build();
Each line states one rule: an author can read a document if it is published, and can create, read, and update it if they wrote it. The conditions that were scattered across helper functions in Post 103 are now inline with the permission declaration. Apart from the global admin, the roles here are project roles, so an allow entry applies only inside a project where the user holds that role.
The can() Function Rewritten#
Implementation#
export function can<R extends Resource>(
user: User,
action: Action,
resource: R,
data?: ResourceDataMap[R]
): boolean {
// Static checking ends here: TypeScript cannot tie entry.resource
// to R, so the runtime filter keeps project conditions away from
// document data, and the cast only restates what the filter proved
const entries = permissions[user.role].filter(
(entry) => entry.resource === resource
) as unknown as PermissionEntry<R>[];
const applies = (entry: PermissionEntry<R>): boolean => {
if (!entry.actions.includes(action)) return false;
// No conditions: the entry applies to every resource of this type
if (!entry.conditions || entry.conditions.length === 0) return true;
// Conditions without data cannot be evaluated: skip the entry
if (!data) return false;
// All conditions must pass (AND logic)
return entry.conditions.every((condition) => condition(user, data));
};
// A matching deny wins over any allow, whatever the entry order
if (entries.some((e) => e.effect === 'deny' && applies(e))) return false;
// Any matching allow grants; no match means deny by default
return entries.some((e) => e.effect === 'allow' && applies(e));
}
Several design decisions are embedded in this implementation:
-
Deny by default: If no allow entry matches, the function returns
false. This is the fail-closed principle from Post 101. -
Unconditional permissions: If
conditionsis undefined or empty, the entry applies without evaluating data. This handles admin-style access; same behavior as RBAC. -
Data-dependent permissions: If conditions exist, the resource data must be provided. If data is missing, that entry is skipped (not denied globally). Another entry for the same resource-action might be unconditional.
-
AND logic for conditions: All conditions in an entry must pass. “Editor can update document IF same department AND document is draft” requires both conditions to be true. OR logic comes from separate entries for the same resource-action pair, as the author’s two
readentries show. -
Deny overrides allow: Deny entries are checked first, and one match ends the evaluation. Entry order therefore never changes a decision. A deny is skipped without data like any conditional entry. As a result, a data-less check sees only unconditional allow entries and ignores every deny, so it can answer yes where the full check says no. Service methods always pass data.
-
Where type checking stops: The generic
Rensures that whenresourceis'document',datamust beResourceDataMap['document'], at every call site. Insidecan(), the double cast replaces that proof with the runtime filter onentry.resource. A directas PermissionEntry<R>[]fails undertsc --strict(error TS2352), which is why the cast goes throughunknown.
Signature Evolution#
The can() function signature across the series:
// Post 103 (RBAC):
can(role: Role, resource: Resource, action: Action): boolean
// Post 104 (ABAC):
can<R extends Resource>(
user: User,
action: Action,
resource: R,
data?: ResourceDataMap[R]
): boolean
What changed:
rolebecomesuser: The full user object carries every subject attribute the policy can read: the project-scoped role, userId, departmentId.data?: ResourceDataMap[R]: Optional resource data for condition evaluation. Optional because unconditional permissions (admin) do not need it.- Generic
R extends Resource: Links the resource string to its data type for type-safe conditions.
Resolving the Subject per Project#
Two small helpers sit next to can(). subjectFor() turns a session into the subject for one project, using effectiveRole() from Post 103. documentAttributes() maps a loaded row to the attributes the policy reads, so service methods stop repeating the same object literal.
// lib/permissions.ts (continued)
// The PIP step: resolve the subject for this project (Post 103)
export function subjectFor(
session: { userId: string; role: string; departmentId?: string },
project: { members: ProjectMember[] }
): User | null {
const role = effectiveRole(session, project);
if (role === null) return null; // not a member: no subject, no access
return { userId: session.userId, role, departmentId: session.departmentId };
}
// Map a loaded document row to the attributes the policy reads
export function documentAttributes(document: {
authorId: string;
status: 'draft' | 'published' | 'archived';
projectId: string;
project: { departmentId: string };
}): ResourceDataMap['document'] {
return {
authorId: document.authorId,
status: document.status,
projectId: document.projectId,
departmentId: document.project.departmentId,
};
}
Passing the session straight into can() would bring back the regression Post 103 warned about: a user whose global role is author would get author rights in every project. With subjectFor(), a non-member has no subject at all, and the caller denies before the policy runs.
The Optional data Parameter#
Why is data optional instead of required?
Unconditional entries need no data. can(admin, 'delete', 'document') answers without a resource, the same way RBAC did. Multi-tenancy changes that: in Post 106, a call without a record must name its tenant with inTenant(...), and a bare data-less check returns false.
Conditional entries do need it, and create is the case that trips people up. When rendering a “Create” button, no document exists yet. The document the user would create has known attributes, though: the user becomes its author, it starts as a draft, and it lands in the current project. Passing those proposed attributes lets the editor’s department condition and the author’s ownership condition run.
// UI, on a project page: "Should we show the Create button?"
// No document exists yet: pass the attributes the new one will have
const subject = subjectFor(session, project);
const showCreate =
subject !== null &&
can(subject, 'create', 'document', {
authorId: subject.userId,
status: 'draft',
projectId: project.id,
departmentId: project.departmentId,
});
Without data, the editor’s conditional create entry is skipped and the editor never sees the button. The service method that creates the document runs the same check with the same proposed attributes before it inserts the row.
Policy Definitions for All Roles#
Admin Policy#
.role('admin')
.can(['create', 'read', 'update', 'delete', 'publish'], 'document')
.can(['create', 'read', 'update', 'delete'], 'project')
No conditions on the allow entries. The global admin is the one platform-wide role (effectiveRole() returns 'admin' without a membership), so these entries apply in every project. The global denies below still apply to the admin.
Editor Policy#
.role('editor')
.can('read', 'document')
.can(['create', 'update', 'publish'], 'document', [sameDepartment])
.can('read', 'project')
The editor has two document entries. The unconditional read covers every document in a project where the user is an editor, drafts included, as in Post 102. The conditional entry scopes create, update, and publish to the editor’s own department.
In Post 103, the department rule required a separate canEditInDepartment() helper. Now it is a declarative condition. Compared with Post 102, where an editor could edit any document in the project, the policy differs in three deliberate ways: the department scope and the separation-of-duty rule from Post 103, and the archived deny below.
sameDepartment checks user.departmentId != null before comparing. departmentId is optional on User, and the database can return a project without a department. A plain user.departmentId === doc.departmentId would then compare undefined with undefined and grant access (see Common Pitfalls).
Author Policy#
.role('author')
.can('read', 'document', [(user, doc) => doc.status === 'published'])
.can(['create', 'read', 'update'], 'document', [
(user, doc) => doc.authorId === user.userId,
])
.can('read', 'project')
Authors read the published documents of their project plus their own drafts, through two entries joined by OR. They update only their own documents. create sits in the ownership entry: the proposed authorId of a new document is the creator, so the condition passes for the author’s own new document and fails for anything else. The ownership check that was a helper function in Post 103 (document.authorId === session.userId) is now a condition.
Viewer Policy#
.role('viewer')
.can('read', 'document', [(user, doc) => doc.status === 'published'])
.can('read', 'project')
Read-only access to published documents, as in Post 102: drafts stay with their author and the project’s editors.
Global Denies#
.forbid(['update', 'publish'], 'document', [
(user, doc) => doc.status === 'archived',
])
.forbid('publish', 'document', [
(user, doc) => doc.authorId === user.userId, // separation of duty
])
Allow-only policies cannot say “archived documents are read-only” once. Every role that can update would need its own status !== 'archived' condition, and a role added later would start without it. forbid() states the rule once for all roles, and the deny-first evaluation in can() makes it win over any allow. The second deny carries over the separation-of-duty rule from Post 103’s canPublishDocument(): whoever wrote a document does not publish it.
The denies apply to the admin too. Restoring an archived document therefore needs its own action (an unarchive added to ACTIONS), granted to whoever may restore; this model does not define one.
Policy Matrix#
The RBAC permission table from Post 103 evolves to include conditions:
| Resource:Action | admin | editor | author | viewer |
|---|---|---|---|---|
| document:create | yes | yes (department) | yes (own) | — |
| document:read | yes | yes | yes (published or own) | yes (published) |
| document:update | yes (not archived) | yes (department, not archived) | yes (own, not archived) | — |
| document:delete | yes | — | — | — |
| document:publish | yes (not own, not archived) | yes (department, not own, not archived) | — | — |
| project:create | yes | — | — | — |
| project:read | yes | yes | yes | yes |
| project:update | yes | — | — | — |
| project:delete | yes | — | — | — |
The annotations are conditions. “(department)”, “(own)” and “(published)” come from allow entries; “(not archived)” and “(not own)” come from the global denies. Every column except admin applies only inside a project where the user holds that role; a non-member gets no column at all. This table is still inspectable and auditable, but now captures the contextual rules that were hidden in Post 103’s helper functions.
Service Layer ABAC Integration#
Before: RBAC + Helper Functions (Post 103)#
Post 103’s helpers (exported from lib/permissions.ts for this comparison), composed in one service method, with the status rule added as the inline check it would have needed:
// lib/services/document-service.ts
import 'server-only';
import {
effectiveRole,
canModifyDocument,
canEditInDepartment,
} from '@/lib/permissions';
export async function updateDocument(
documentId: string,
content: string
) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: { project: { include: { members: true } } },
});
if (!document) throw new NotFoundError();
const role = effectiveRole(session, document.project);
// Role + ownership: canModifyDocument()
if (!canModifyDocument(role, session.userId, document)) {
throw new ForbiddenError();
}
// Role + department: canEditInDepartment()
if (!canEditInDepartment(role, session, document)) {
throw new ForbiddenError();
}
// Status: no helper exists, so another inline check
if (document.status === 'archived') {
throw new ForbiddenError();
}
const updated = await db.document.update({
where: { id: documentId },
data: { content },
});
return toDocumentDTO({ ...updated, project: document.project }, session);
}
Three permission checks stack up in one method, and each helper repeats the role check. Ownership and department scoping live in helpers outside can(), and the status rule is a hand-written if. Adding a new contextual rule means adding another one.
After: Unified ABAC can() (Post 104)#
// lib/services/document-service.ts
import 'server-only';
import { can, subjectFor, documentAttributes } from '@/lib/permissions';
export async function updateDocument(
documentId: string,
content: string
) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: { project: { include: { members: true } } },
});
if (!document) throw new NotFoundError();
// Project role first (PIP step), then one policy decision
const user = subjectFor(session, document.project);
if (!user || !can(user, 'update', 'document', documentAttributes(document))) {
throw new ForbiddenError();
}
const updated = await db.document.update({
where: { id: documentId },
data: { content },
});
return toDocumentDTO({ ...updated, project: document.project }, session);
}
What changed:
- Three separate checks (ownership, department, status) collapsed into one subject resolution and one
can()call. - The resource data is passed explicitly through
documentAttributes(). TypeScript ensures the shape matchesResourceDataMap['document']. - Adding a new condition (e.g., “only draft documents can be updated”) happens in the policy builder; this service method stays as it is.
- The method still returns a DTO, as in Post 102.
More Service Method Examples#
Publishing a document: Post 103’s separation-of-duty helper, the department check, and the archived check become a single decision:
// Before: Post 103 helper + manual checks
export async function publishDocument(documentId: string) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: { project: { include: { members: true } } },
});
if (!document) throw new NotFoundError();
// Role + separation of duty: canPublishDocument()
if (!canPublishDocument(session, document)) {
throw new ForbiddenError();
}
// Department check -- manual
if (session.role !== 'admin' &&
session.departmentId !== document.project.departmentId) {
throw new ForbiddenError();
}
// Status check -- manual
if (document.status === 'archived') {
throw new ForbiddenError();
}
// ... publish logic
}
// After: single ABAC check
export async function publishDocument(documentId: string) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: { project: { include: { members: true } } },
});
if (!document) throw new NotFoundError();
const user = subjectFor(session, document.project);
if (!user || !can(user, 'publish', 'document', documentAttributes(document))) {
throw new ForbiddenError();
}
// ... publish logic
}
Reading a document: membership, published-or-own for authors and viewers, and the DTO from Post 102:
export async function getDocument(documentId: string) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: { project: { include: { members: true } } },
});
if (!document) throw new NotFoundError();
// Post 102's public rule: no membership needed for these
const publicRead =
document.project.visibility === 'public' &&
document.status === 'published';
if (!publicRead) {
const user = subjectFor(session, document.project);
if (!user || !can(user, 'read', 'document', documentAttributes(document))) {
throw new ForbiddenError();
}
}
// Never the raw row: the DTO decides which fields leave the server
return toDocumentDTO(document, session);
}
Post 102 also let any signed-in user read the published documents of a public project. A non-member has no project role, so subjectFor() returns null and the policy never runs for them. That rule therefore stays a check in front of the subject resolution.
The service layer’s structure from Post 102 is unchanged. Only the decision engine inside the permission checks evolved.
Common Pitfalls#
-
Passing incomplete resource data: If a permission has conditions but data is omitted, the conditional entry is skipped. This may cause unexpected denials, such as an editor who never sees the Create button. When a role’s permission has conditions, always pass the resource data, and for
create, pass the attributes the new resource will have. -
AND vs. OR confusion: Multiple conditions on a single
PermissionEntryuse AND logic (all must pass). For OR logic, create separate entries for the same resource-action pair. The author policy demonstrates this:readon published documents andreadon their own documents are two entries. -
Conditions with side effects: Conditions should be pure functions. No database calls, no mutations, no logging. They receive pre-loaded data and return a boolean. Side effects in conditions make the system unpredictable and untestable.
-
Optional attributes that match each other:
user.departmentId === doc.departmentIdistruewhen both sides areundefined. A user without a department then matches every document whose project has no department, and the policy fails open. Guard optional attributes on the subject side (user.departmentId != null && ...), assameDepartmentdoes, or make the attribute required in the type. -
Feeding the global role to the policy:
can(session, ...)type-checks whenever the session hasuserIdandrole. It also grants a global author author rights in every project. Resolve the subject per project withsubjectFor()and treatnullas a denial. -
Repeating a universal rule in every role: A rule that must hold for all roles (“archived documents are read-only”) copied into each role’s conditions drifts the first time someone adds a role. Declare it once with
forbid(); deny entries win regardless of where they sit in the builder. -
Conflating application-level and enterprise ABAC: Enterprise ABAC (XACML, OPA/Rego) involves separate PDP servers and network requests. Application-level ABAC is a local function call with in-memory conditions. The policy engine is a TypeScript module that runs in-process.
RBAC to ABAC Migration Benefits#
What Changed#
| Aspect | RBAC (Post 103) | ABAC (Post 104) |
|---|---|---|
| Decision function | can(role, resource, action) + helpers | can(user, action, resource, data?) |
| Project membership | effectiveRole() before can() | subjectFor() (wrapping effectiveRole()) before can() |
| Ownership check | canModifyDocument() helper | Condition: doc.authorId === user.userId |
| Department scoping | canEditInDepartment() helper | Condition: sameDepartment (null-safe) |
| Resource status check | Not expressible | Condition: doc.status === 'published'; deny on 'archived' |
| Rules for every role | Repeated in each helper | One forbid() entry |
| Adding a contextual rule | New helper function + find all call sites | Add condition to policy builder |
| Policy visibility | Permission matrix + scattered helpers | All in policy builder |
| Type safety of conditions | None (helpers are imperative) | Typed at the builder and at can() call sites; the store uses casts |
| Service method changes | One can() + multiple if blocks | One subjectFor() + one can() call |
What Stayed the Same#
- The service layer architecture (Post 102) is unchanged
verifySession()still provides the session the subject is built from- Project membership still decides the role, through
effectiveRole()from Post 103 - Service methods still return DTOs (
toDocumentDTO()from Post 102), never raw rows - The service layer is still the security boundary
- UI permission checks are still for UX, not security
- The shared module pattern (no
server-onlyon permissions.ts) still applies - The fail-closed principle (Post 101) still applies
Testing with Truth Tables#
A rewrite of authorization code needs tests that pin the decisions the old code made. Most rows below are one attribute combination with the answer Post 102’s canAccessDocument() and canEditDocument(), or Post 103’s canPublishDocument(), gave for it. The archived rows pin the new deny. The test goes through subjectFor(), so membership is part of what it checks, and the project is private, so the public-read path stays out of it:
// __tests__/permissions/document-policy.test.ts
import { can, subjectFor, documentAttributes } from '@/lib/permissions';
type Status = 'draft' | 'published' | 'archived';
type DocAction = 'create' | 'read' | 'update' | 'publish';
// Caller u1 (department d1) against a document in project p1.
// memberRole is u1's role in p1; null means not a member.
function decide(
globalRole: string,
memberRole: string | null,
action: DocAction,
status: Status,
authorId: string,
docDepartment = 'd1'
): boolean {
const session = { userId: 'u1', role: globalRole, departmentId: 'd1' };
const project = {
departmentId: docDepartment,
members: memberRole ? [{ userId: 'u1', role: memberRole }] : [],
};
const document = { authorId, status, projectId: 'p1', project };
const user = subjectFor(session, project);
return (
user !== null &&
can(user, action, 'document', documentAttributes(document))
);
}
// [case, global role, project role, action, status, author, expected]
type Row = [string, string, string | null, DocAction, Status, string, boolean];
const rows: Row[] = [
['non-member, private project', 'author', null, 'read', 'published', 'u2', false],
['viewer, published doc', 'author', 'viewer', 'read', 'published', 'u2', true],
['viewer, draft', 'author', 'viewer', 'read', 'draft', 'u2', false],
["author, colleague's published doc", 'author', 'author', 'read', 'published', 'u2', true],
["author, colleague's draft", 'author', 'author', 'read', 'draft', 'u2', false],
['author, own draft', 'author', 'author', 'read', 'draft', 'u1', true],
['author updates own draft', 'author', 'author', 'update', 'draft', 'u1', true],
["author updates colleague's draft", 'author', 'author', 'update', 'draft', 'u2', false],
["editor reads colleague's draft", 'author', 'editor', 'read', 'draft', 'u2', true],
["editor updates colleague's draft", 'author', 'editor', 'update', 'draft', 'u2', true],
["editor publishes colleague's draft", 'author', 'editor', 'publish', 'draft', 'u2', true],
['editor publishes own draft', 'author', 'editor', 'publish', 'draft', 'u1', false],
['editor updates archived doc', 'author', 'editor', 'update', 'archived', 'u2', false],
['global admin, no membership', 'admin', null, 'update', 'draft', 'u2', true],
['global admin, archived doc', 'admin', null, 'update', 'archived', 'u2', false],
];
describe('document policy keeps the Post 102 and 103 decisions', () => {
for (const [name, globalRole, memberRole, action, status, authorId, expected] of rows) {
it(name, () => {
expect(decide(globalRole, memberRole, action, status, authorId)).toBe(expected);
});
}
it('scopes editor writes to their department', () => {
expect(decide('author', 'editor', 'update', 'draft', 'u2', 'd2')).toBe(false);
});
it('lets an editor create with proposed attributes', () => {
expect(decide('author', 'editor', 'create', 'draft', 'u1')).toBe(true);
});
it('fails closed when neither side has a department', () => {
// A project row without a department, as the database may return it
const missing = undefined as unknown as string;
expect(can({ userId: 'u1', role: 'editor' }, 'update', 'document', {
authorId: 'u2', status: 'draft', projectId: 'p1', departmentId: missing,
})).toBe(false);
});
});
The tests need no mocks, no database, and no test doubles, because the policy engine is a pure function. They also catch the two ways a policy rewrite drifts. Passing session straight to can() fails the first row, because a global author reads every published document. An unconditional viewer read fails the third row, because viewers then see drafts. The department scope, separation of duty and the archived deny are the intended differences from Post 102.
Decision Framework: RBAC vs. ABAC vs. External Engine#
| Criterion | RBAC | ABAC (App-Level) | External Engine |
|---|---|---|---|
| Permissions depend on | Role only | Role + attributes | Role + attributes + relationships |
| Number of contextual rules | 0 | 3-20 | 20+ or cross-service |
| Where policies live | Code (TypeScript map) | Code (builder/conditions) | External policy store |
| Evaluation location | In-process, sync | In-process, sync | Network call, async |
| Type safety | Full (TypeScript) | Builder and call sites (generics); store cast | Partial (policy language) |
| Latency per check | Microseconds | Microseconds | Milliseconds (network) |
Trade-offs#
Declarativeness vs. debuggability: Declarative policies are easier to read than imperative helpers, but when a permission is unexpectedly denied, tracing which condition failed requires stepping through the can() function. A canWithReason() variant that returns the failing condition can help during development.
Type safety vs. learning curve: TypeScript generics enforce that conditions reference valid resource attributes. This catches bugs at compile time but makes the type definitions more complex. The guarantee also has an edge: the store holds widened entries, and the two casts in addEntry() and can() rely on the runtime resource filter. Teams unfamiliar with generics may find the types initially challenging.
Centralized policy vs. performance: All policies in one builder is great for visibility. But the can() function iterates through all entries on every call. For simple applications (4 roles, 5-10 entries per role), this is microseconds. For complex policies with many entries, consider optimization (Post 105 addresses this).
Application-level vs. external engine: ABAC written in TypeScript is fast, type-safe, and adds no network overhead. But policies are coupled to the application code and require deployment to change. External engines (OPA, Cedar) decouple policies from code but add latency and operational complexity (Post 106 covers this decision).
What’s Next#
App-level ABAC holds as long as every condition can be evaluated against objects already loaded in application memory. Two limits appear past that line: controlling which fields a user can see or modify, and pushing conditions into the database so queries return only permitted rows.
In Post 105, the ABAC engine extends to field-level permissions and database integration. Conditions get converted into ORM-compatible where clauses, so the database enforces permissions at the query level.
// Preview -- full implementation in Post 105
// user: the subject from subjectFor()
// Field-level: which fields can this user see?
const fields = getVisibleFields(user, 'document');
// -> ['title', 'content'] for author
// -> ['title', 'content', 'internalNotes'] for admin
// Database-level: push conditions into the query
const documents = await db.document.findMany({
where: toWhereClause(user, 'document', 'read'),
// -> { status: 'published' } for viewer
// -> { OR: [{ status: 'published' }, { authorId: user.userId }] } for author
// -> {} for admin
});
References#
- NIST SP 800-162: Guide to Attribute Based Access Control (ABAC) (opens in new tab) - The foundational NIST standard defining the four attribute categories, functional components, and considerations for ABAC deployment
- NIST SP 800-162 Full Text (PDF) (opens in new tab) - Complete text of the ABAC guide with formal definitions of subject, object, action, and environment attributes
- RBAC vs ABAC vs ReBAC (Web Dev Simplified) (opens in new tab) - Practical TypeScript comparison of three permission models with code examples for ABAC condition evaluation
- OWASP Authorization Cheat Sheet (opens in new tab) - Best practices including centralized authorization, deny by default, and ABAC recommendations for fine-grained access control
- Attribute-Based Access Control (Wikipedia) (opens in new tab) - Overview of ABAC history, XACML standard, and PEP/PDP/PIP/PAP architecture
- XACML - eXtensible Access Control Markup Language (Wikipedia) (opens in new tab) - Reference for the XACML architecture components (PEP, PDP, PIP, PAP) and their application-level equivalents
- CASL - Isomorphic Authorization JavaScript Library (opens in new tab) - The library that inspired the
can()function pattern and builder-like permission definition API - RBAC vs ABAC: Differences and When to Use (Oso) (opens in new tab) - Detailed comparison covering when each model is appropriate and hybrid approaches
- How to Implement ABAC Authorization (Permit.io) (opens in new tab) - Step-by-step ABAC implementation guide covering attribute categories and PEP/PDP evaluation flow
- Using ABAC to Solve Role Explosion (Thoughtworks) (opens in new tab) - Analysis of how ABAC solves the role explosion problem with migration patterns
- TypeScript Generics Documentation (opens in new tab) - Official reference for the generic constraint patterns used in
Condition<R extends Resource> - Cedar Policy Language (StrongDM) (opens in new tab) - Overview of AWS Cedar as an external policy engine alternative to application-level ABAC
Permission Systems that Scale
Part 4 of 6A comprehensive guide to building scalable permission systems in TypeScript and Next.js, progressing from naive checks through RBAC and ABAC to production-grade multi-tenant authorization.
All posts in this series
Related posts
Authentication vs authorization, common permission pitfalls, the fail-closed principle, and the goals every permission system should meet.
typescript · nextjs · authorization +2
Refactor scattered permission checks into a centralized service layer, add Next.js middleware guards, and build a defense-in-depth authorization architecture.
typescript · nextjs · authorization +2
Build a type-safe RBAC system in TypeScript, create a unified can() function, sync permissions across UI and backend, and learn when RBAC reaches its limits.
typescript · nextjs · authorization +2
Extend ABAC with environment-based rules, field-level read and write permissions, and automatic database query filtering that eliminates duplicate permission logic.
typescript · nextjs · authorization +2
Add multi-tenant isolation to your permission system, evaluate CASL as a library alternative, and use decision frameworks to choose the right authorization architecture.
typescript · nextjs · authorization +3