Skip to content

Multi-Tenant Authorization in TypeScript: CASL vs Custom ABAC

Add multi-tenant isolation to your permission system, evaluate CASL as a library alternative, and use decision frameworks to choose the right authorization architecture.

Ayhan Sipahi Ayhan Sipahi

Post 101 established seven goals for a permission system and exposed the scattered-check anti-pattern. Post 102 centralized authorization inside a service layer. Post 103 added type-safe RBAC. Post 104 replaced the role-permission matrix with an ABAC policy engine. Post 105 extended ABAC with environment rules, field-level read/write permissions, and database query filtering.

Three production concerns remain. The system has no tenant boundary, so a user in Organization A can reach Organization B’s resources if the query is crafted correctly; that isolation belongs in the permission layer as a global condition, not scattered across every service method. The custom ABAC engine works, but nobody has decided whether the team keeps maintaining it or migrates to a library like CASL, and the engine stays until the team no longer wants to own it, which is the point where CASL earns its place. There is still no framework for choosing between RBAC, custom ABAC, library-based ABAC, and external policy engines, a choice that follows from how many services share each decision and how many contextual conditions each resource needs.

Multi-Tenancy Models#

The Tenant Concept#

In SaaS, a tenant is an organization, workspace, or account that groups users and their resources. Slack workspaces, GitHub organizations, and Notion workspaces are all tenants. The tenant boundary is the outermost permission boundary. Before checking roles, ownership, or field access, the system must verify the user belongs to the tenant that owns the resource.

Extending the Domain Model#

The series’ domain model gains a tenant dimension:

interface User {
  userId: string;
  role: Role;
  departmentId?: string;
  tenantId: string;  // which organization this user belongs to
  tenantRole?: TenantRole; // role within the tenant (owner, admin, member)
}

interface Document {
  id: string;
  title: string;
  content: string;
  authorId: string;
  status: 'draft' | 'published' | 'archived';
  projectId: string;
  departmentId: string;
  tenantId: string;  // which tenant owns this document
}

interface Project {
  id: string;
  name: string;
  ownerId: string;
  departmentId: string;
  tenantId: string;  // which tenant owns this project
}

type TenantRole = 'owner' | 'admin' | 'member';

Every resource now carries a tenantId. Every user belongs to exactly one tenant. Membership in several tenants (the Slack, GitHub and Notion model, with an “active workspace” switch) adds complexity outside this scope.

One rule holds in both models: user.tenantId comes from the server. It is read from the session record or a verified token claim. When the active tenant arrives with the request (a subdomain, a path segment or a header), the server checks that the user is a member before it sets tenantId. The client never supplies the value directly. Every tenant check below compares a resource against user.tenantId, so a value the client chose would let the client pick which tenant passes.

Three Isolation Strategies#

Database-Level Isolation

DB: tenant_a

DB: tenant_b

Schema-Level Isolation

Single Database

Schema: tenant_a

Schema: tenant_b

Row-Level Isolation

Single Database
Single Schema

Tenant A rows

Tenant B rows

Row-Level Isolation (shared schema): All tenants share the same tables. Every table has a tenant_id column. This is the simplest infrastructure and cheapest option, but forgetting a WHERE tenant_id = ? clause leaks cross-tenant data. PostgreSQL Row-Level Security (RLS) can enforce this at the database level as a safety net.

Schema-Level Isolation: Each tenant gets a separate schema within the same database. A query without a tenant filter cannot reach other tenants’ tables as long as the connection points at the right schema. The risk moves to connection setup. PostgreSQL resolves unqualified table names through the search_path, and a SET search_path lasts until the session ends. A pooled connection that still points at the previous tenant’s schema returns that tenant’s rows, with no error. Migrations must run across N schemas. Viable for dozens to hundreds of tenants.

Database-Level Isolation: Each tenant gets a dedicated database instance. Maximum isolation, with the same connection-routing risk one level up. Highest cost and operational complexity.

AspectRow-LevelSchema-LevelDatabase-Level
Infrastructure costLowMediumHigh
Isolation strengthApplication-enforcedDB-schema-enforcedPhysical isolation
Tenant count scalabilityThousands+HundredsDozens
Migration complexitySingle migrationN migrationsN migrations + N databases
Cross-tenant query riskHigh (missing WHERE)Medium (stale search_path returns another tenant’s rows)Low (wrong connection routing)
Per-tenant customizationLimitedModerateFull

None of these models is a compliance level of its own. The HIPAA Security Rule, for example, lets covered entities and business associates use any security measures that reasonably and appropriately implement its standards, so the rule judges the safeguards and leaves the storage layout to the team. Customer contracts and the team’s risk appetite usually decide how far right in this table a product goes.

This series uses the row-level isolation model because it is the most common starting point and the most challenging from a permission perspective. Schema and database isolation solve tenant boundaries at the infrastructure level. Row-level isolation requires the application to enforce those boundaries.

Tenant-Aware Permission Layer#

The Scattered Tenant Check Anti-Pattern#

Without tenant-aware permissions, every service method manually checks tenant isolation:

// Anti-pattern: manual tenant check in every service method
async function getDocumentById(documentId: string) {
  const session = await requireSession();
  const document = await db.document.findUnique({ where: { id: documentId } });

  // Manual tenant check, easy to forget
  if (document.tenantId !== session.tenantId) {
    throw new ForbiddenError();
  }

  // Then the regular ABAC check
  if (!can(session, 'read', 'document', document)) {
    throw new ForbiddenError();
  }

  return filterFields(session, 'document', document);
}

This is Post 101’s scattered-check pattern reappearing at the tenant level. Forgetting the tenant check on a single endpoint creates a cross-tenant data leak, the most dangerous class of authorization bug because it exposes other customers’ data.

Tenant Isolation as a Global ABAC Condition#

The correct approach: tenant isolation becomes a built-in condition that runs automatically for every permission check. It has to fail closed. A record that arrives without a tenantId is denied, and only resource types listed as shared skip the check:

// ResourceDataMap from Post 104 gains a tenantId on tenant-scoped resources
interface ResourceDataMap {
  document: {
    authorId: string;
    status: 'draft' | 'published' | 'archived';
    projectId: string;
    departmentId: string;
    tenantId: string;
  };
  project: {
    ownerId: string;
    departmentId: string;
    isArchived: boolean;
    tenantId: string;
  };
  template: { title: string }; // shared: no tenantId
}

// Resource types that live outside every tenant, listed on purpose
const SHARED_RESOURCES: ReadonlySet<Resource> = new Set<Resource>(['template']);

// The only two ways across a tenant boundary, kept in one helper
const bypassesTenant = (user: User, resource: Resource): boolean =>
  user.role === 'platform_admin' || SHARED_RESOURCES.has(resource);

// A check without a loaded record still names its tenant
interface TenantScope {
  scopeOnly: true;
  tenantId: string;
}
const inTenant = (tenantId: string): TenantScope => ({ scopeOnly: true, tenantId });

const permissions = new PermissionBuilder()
  // Global condition: every role, every resource, with or without data
  .global((user, resource, target) => {
    // The two explicit exceptions (see Cross-Tenant Access Exceptions)
    if (bypassesTenant(user, resource)) return true;

    // No record and no scope, or no tenantId on them: DENY
    const tenantId = target && 'tenantId' in target ? target.tenantId : undefined;
    if (typeof tenantId !== 'string') return false;
    // Another tenant: DENY
    return tenantId === user.tenantId;
  })

  .role('admin')
    .can(['create', 'read', 'update', 'delete', 'publish'], 'document')
    .can(['create', 'read', 'update', 'delete'], 'project')

  .role('editor')
    .can(['read', 'update'], 'document', [{
      evaluate: (user, doc) => user.departmentId === doc.departmentId,
      toFilter: (user) => ({ departmentId: user.departmentId }),
    }])

  // ... remaining policies from Posts 104-105
  .build();

The global() condition runs before any role-specific conditions. It acts as an implicit WHERE clause on every permission check. A new role gets it without any extra code. A new resource type gets it too, and a mapper that forgets to copy tenantId produces a denial instead of a leak. Skipping the check takes a deliberate entry in SHARED_RESOURCES.

The admin entries spell out their actions. The series’ ACTIONS list from Post 103 has no manage wildcard, so the custom builder lists every action it grants.

Updating the can() Function#

The can() function evaluates global conditions first, on every call:

function can<R extends Resource>(
  user: User,
  action: Action,
  resource: R,
  data?: ResourceDataMap[R] | TenantScope,
  env?: Environment
): boolean {
  // Step 1: Global conditions run on every call, with or without a record
  for (const globalCondition of permissions.globalConditions) {
    if (!globalCondition(user, resource, data)) {
      return false; // wrong tenant, or no tenant context at all
    }
  }

  // Step 2: Role entries, same logic as Posts 104-105.
  // A TenantScope passes Step 1 but carries no attributes for conditions.
  const record = data && !('scopeOnly' in data) ? data : undefined;
  const entries = permissions.roles[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;
    if (!entry.conditions || entry.conditions.length === 0) return true;
    if (!record) return false;
    // evaluate() is Post 105's helper: a plain function or a descriptor
    return entry.conditions.every((c) => evaluate(c, user, record, env));
  };

  if (entries.some((e) => e.effect === 'deny' && applies(e))) return false;
  return entries.some((e) => e.effect === 'allow' && applies(e));
}

This changes one behavior from Post 104. A data-less call used to answer “does this role hold the action on some resources?”, and the admin got true with no tenant in sight. Now a call without a record must pass inTenant(...), and a bare can(admin, 'delete', 'document') returns false. A “New document” button calls can(user, 'create', 'document', inTenant(user.tenantId)). Service methods that touch a record keep passing the record.

Two tests pin the fail-closed behavior:

describe('tenant isolation fails closed', () => {
  const admin: User = { userId: 'u1', role: 'admin', tenantId: 't1' };
  const doc: ResourceDataMap['document'] = {
    authorId: 'u2', status: 'draft', projectId: 'p1', departmentId: 'd1', tenantId: 't1',
  };

  it('denies a record whose mapper dropped tenantId', () => {
    // Simulates a toResourceData() that forgot the field
    const { tenantId: _dropped, ...withoutTenant } = doc;
    const unmapped = withoutTenant as unknown as ResourceDataMap['document'];
    expect(can(admin, 'read', 'document', unmapped)).toBe(false);
  });

  it('denies a data-less check unless it names the tenant', () => {
    expect(can(admin, 'delete', 'document')).toBe(false);
    expect(can(admin, 'create', 'document', inTenant('t1'))).toBe(true);
    expect(can(admin, 'create', 'document', inTenant('t2'))).toBe(false);
  });
});

A permissive condition such as if ('tenantId' in data && ...) return false fails both tests. It waves through the record that has no tenantId, and when can() runs global conditions only for calls with data, the delete check never meets the tenant rule.

Updating Database Query Filtering#

The toWhereClause() function from Post 105 must include tenant filtering:

function toWhereClause<R extends Resource>(
  user: User,
  resource: R,
  action: Action,
  env?: Environment
): WhereClause<R> | null {
  const roleFilter = buildRoleFilter(user, resource, action, env);
  if (roleFilter === null) return null; // No access

  // Same exceptions as the global condition: no tenant filter
  if (bypassesTenant(user, resource)) return roleFilter;

  // Always include the tenant filter, spread last so no role filter overwrites it
  const tenantFilter = { tenantId: user.tenantId };
  return { ...roleFilter, ...tenantFilter };
}

The tenant filter is always present for tenant-scoped resources. Even if buildRoleFilter() returns {} (no additional filter for an admin), the query still includes WHERE tenantId = ?. A platform admin and the shared types skip it through the same bypassesTenant() check, so can() and the list query agree on who crosses a tenant boundary.

Cross-Tenant Access Exceptions#

Some scenarios require cross-tenant access:

  • Platform admins (super-admins) who manage all tenants
  • Shared resources (templates, public content) that exist outside any tenant
  • Support tools for customer service to view tenant data
// ROLES gains a platform-wide role; the global condition names it
export const ROLES = ['platform_admin', 'admin', 'editor', 'author', 'viewer'] as const;

// Its grants list actions like every other role
.role('platform_admin')
  .can(['create', 'read', 'update', 'delete', 'publish'], 'document')
  .can(['create', 'read', 'update', 'delete'], 'project')

// Shared resources: no tenantId in ResourceDataMap['template'],
// and an explicit entry in SHARED_RESOURCES
.role('viewer')
  .can('read', 'template')

Both exceptions live in one helper, bypassesTenant(), which the global condition and toWhereClause() share, so a reviewer finds every cross-tenant path in one place.

Warning

Cross-tenant exceptions must be explicit and auditable. The platform admin role should be separate from tenant-level admin, with additional authentication requirements (MFA, IP restrictions) enforced via environment conditions from Post 105.

Why Use a Permission Library?#

The Build vs. Library Decision#

Posts 101-105 built a custom permission system covering RBAC, ABAC, field-level permissions, DB query filtering, environment rules, and now multi-tenancy. That is a few hundred lines of core permission logic. At what point does maintaining this code become more expensive than adopting a library?

What Each Path Costs the Team#

Building it yourself buys zero dependencies in the critical security path, full control over the can() signature as it evolves, and TypeScript integration tailored to the exact domain (generic constraints, builder patterns, type inference). Every condition is a function the team wrote, so there are no black boxes, and debugging follows a normal call stack. The cost sits on the same team, though: it owns every bug, edge case, and security patch, without the community testing a widely used library accumulates, and field permissions, DB query conversion, and condition operators ($in, $ne, $gte) all get rebuilt from scratch while new hires learn a bespoke API instead of a documented one.

A permission library arrives community-tested across thousands of projects, with field permissions, MongoDB-style conditions, and Prisma/Mongoose adapters already built, and documentation, Stack Overflow answers, and conference talks exist because the team didn’t have to write them. What it costs is control: the library’s API may not match the series’ can() signature, its maintenance can slow or stop, conditions written as functions give up its database translation, and debugging a permission denial means understanding someone else’s internals rather than a function the team wrote.

Build vs. Library Decision Framework#

Yes

No

No

Yes

No

Yes

No

Yes

Yes

No

Authorization
Needed

Several services
or languages make
the same decision?

External PDP
Cerbos, OPA, Cedar

Team has
authorization
expertise?

Use a Library
CASL

3+ contextual
conditions per
resource?

Custom RBAC
Post 103

Field-level +
DB filtering
needed?

Custom ABAC
Post 104

Team willing to
maintain a few hundred
lines of auth code?

Custom Full ABAC
Posts 104-105

The first question decides the most. One Next.js app can keep its decisions in process, whatever engine it picks. Once a second service, or a service in another language, has to reach the same decision, an external PDP keeps one policy instead of two copies that drift apart.

Compliance does not move a team along this tree. The HIPAA Security Rule’s audit-controls standard, for example, asks for mechanisms that record and examine activity in systems holding health data. The service layer can write that record from can(): user, action, resource, tenant and result for every decision. An external PDP is one way to get such a log, and an in-process engine with a decision log is another.

In-Code vs. DSL-Based Approaches#

ApproachExamplesStrengthsWeaknesses
In-code (TypeScript)Custom, CASLType-safe, no runtime overhead, familiar languageCoupled to deployment, no runtime changes
DSL / Policy languageOPA/Rego, Cedar, Cerbos (YAML)Decoupled from app code, non-dev editable, auditableLearning curve, tooling overhead, latency
HybridPermit.io, custom DB-stored rulesRuntime-configurable + code-based defaultsComplexity, consistency challenges

CASL Integration#

Why CASL#

CASL is the most popular JavaScript/TypeScript authorization library (~6KB core). It is isomorphic (works on server and client), supports ABAC conditions, field-level permissions, and database query conversion. Since the series has already built everything CASL provides, a direct feature-for-feature comparison is possible.

npm install @casl/ability @casl/prisma

Migration: AbilityBuilder#

The custom PermissionBuilder from Post 104 maps to CASL’s AbilityBuilder:

Custom (Posts 104-105):

const permissions = new PermissionBuilder()
  .role('admin')
    .can(['create', 'read', 'update', 'delete', 'publish'], 'document')
  .role('editor')
    .can(['read', 'update'], 'document', [
      (user, doc) => user.departmentId === doc.departmentId,
    ])
  .role('author')
    .can(['read', 'update'], 'document', [
      (user, doc) => doc.authorId === user.userId,
    ])
  .build();

CASL equivalent:

import { AbilityBuilder, createMongoAbility, MongoAbility } from '@casl/ability';

type Actions = 'create' | 'read' | 'update' | 'delete' | 'manage';
type Subjects = 'Document' | 'Project' | 'all';
type AppAbility = MongoAbility<[Actions, Subjects]>;

function defineAbilitiesFor(user: User): AppAbility {
  const { can, cannot, build } = new AbilityBuilder<AppAbility>(
    createMongoAbility
  );

  if (user.role === 'admin') {
    can('manage', 'all');
  }

  if (user.role === 'editor') {
    can(['read', 'update'], 'Document', { departmentId: user.departmentId });
  }

  if (user.role === 'author') {
    can(['read', 'update'], 'Document', { authorId: user.userId });
    can('create', 'Document');
  }

  if (user.role === 'viewer') {
    can('read', 'Document', { status: 'published' });
  }

  return build();
}

Key API differences:

  • Conditions are MongoDB-style objects ({ authorId: user.userId }); the custom builder used functions
  • No builder-pattern chaining for roles; it uses if/else branching on user role
  • cannot() for negative rules (the custom builder’s counterpart is forbid() from Post 104)
  • 'manage' is CASL’s keyword for any action and 'all' for any subject; the custom builder has no wildcard and lists actions

The subject() Helper and Its Friction#

CASL needs to know the type of an object being checked. With classes, this is automatic (via the class name). With plain objects, which TypeScript applications typically use, the subject() helper is required:

import { subject } from '@casl/ability';

// CASL requires wrapping plain objects
ability.can('update', subject('Document', document));

// subject() defines a non-enumerable __caslSubjectType__ property
// on the object it receives, and throws if the same object is
// later cast to a different subject type

The property is non-enumerable, so JSON.stringify() skips it and the object serializes as before. Two side effects remain: the original object is mutated, and code that later wraps the same object as another subject type gets an error. Both go away when the check receives a copy, or when the service layer tags its DTOs and a custom detectSubjectType reads the tag.

Option 1: Wrap a copy

// Create a copy to avoid mutating the original
ability.can('update', subject('Document', { ...document }));

Option 2: Custom detectSubjectType

import { createMongoAbility } from '@casl/ability';

const ability = createMongoAbility(rules, {
  detectSubjectType: (object) => {
    // Use a custom property instead of class name
    return object.__type || object.constructor?.modelName || 'unknown';
  },
});

// In the service layer, add __type to returned objects
function toDocumentDTO(doc: Document): DocumentDTO & { __type: 'Document' } {
  return { ...doc, __type: 'Document' };
}

The choice that shapes a CASL setup is the condition format. Object conditions are data. CASL evaluates them in memory, and an adapter such as @casl/prisma turns the same rules into a database where clause. Function conditions accept any TypeScript but stay opaque, the same limit Post 105 hit with the custom engine’s plain functions. PureAbility with a lambda matcher runs them:

import {
  PureAbility,
  AbilityBuilder,
  type AbilityTuple,
  type MatchConditions,
} from '@casl/ability';

type AppAbility = PureAbility<AbilityTuple, MatchConditions>;
const lambdaMatcher = (matchConditions: MatchConditions) => matchConditions;

function defineAbilityFor(user: User): AppAbility {
  const { can, build } = new AbilityBuilder<AppAbility>(PureAbility);

  // Lambda condition: any TypeScript, no database translation
  can('read', 'Document', ({ authorId }) => authorId === user.userId);

  return build({ conditionsMatcher: lambdaMatcher });
}

Tip

Default to object conditions, and keep lambdas for rules that never need to become a query. An ability built on lambdas cannot feed accessibleBy(), so list endpoints need a second filter that can drift from can().

Tenant Isolation in CASL#

// Subjects gains the shared 'Template' type
type Subjects = 'Document' | 'Project' | 'Template' | 'all';

function defineAbilitiesFor(user: User): AppAbility {
  const { can, cannot, build } = new AbilityBuilder<AppAbility>(
    createMongoAbility
  );

  // The one cross-tenant role: no tenant deny below
  if (user.role === 'platform_admin') {
    can('manage', 'all');
    return build();
  }

  // Role rules carry no tenantId
  if (user.role === 'admin') {
    can('manage', 'Document');
    can('manage', 'Project');
  }

  if (user.role === 'editor') {
    can(['read', 'update'], 'Document', { departmentId: user.departmentId });
  }

  // Global tenant deny: declared after every tenant-scoped can(),
  // so it restricts all of them. An object without tenantId matches too.
  cannot('manage', 'all', { tenantId: { $ne: user.tenantId } });

  // Shared subjects: a regular rule declared after the deny overrides it
  can('read', 'Template');

  return build();
}

For checks on a loaded object, one inverted rule does the work of the custom global() condition. CASL’s documentation asks for cannot rules to follow the can rules they restrict, and states that regular rules declared later override inverted ones; the second property lets the shared Template grant through. CASL defines $ne as the negation of $eq, so a document whose tenantId is missing also matches the deny. On loaded objects, that matches the custom engine’s fail-closed behavior.

The custom engine now denies a data-less call; CASL does not. On a subject-type check such as ability.can('delete', 'Document'), CASL skips inverted rules that carry conditions, so the tenant deny does not run and the tenant admin gets true. CASL’s guide says to check again on the final subject. Treat a type-level check as a UI hint, and pass the loaded object before any operation on a record.

CASL Field and DB Integration#

Field-Level Permissions with permittedFieldsOf#

import { permittedFieldsOf } from '@casl/ability/extra';

// Define field-level rules
can('read', 'Document', ['title', 'content', 'status'], {
  status: 'published',
});
can(
  'read',
  'Document',
  ['title', 'content', 'status', 'internalNotes', 'reviewComments'],
  { authorId: user.userId }
);

// Get permitted fields for a specific document
const fields = permittedFieldsOf(ability, 'read', 'Document', {
  fieldsFrom: (rule) =>
    rule.fields || [
      'title',
      'content',
      'status',
      'authorId',
      'internalNotes',
      'reviewComments',
      'publishedAt',
    ],
});

Compare to the custom getVisibleFields() from Post 105: the concept is the same, the API is different. CASL requires a fieldsFrom callback that returns all possible fields when a rule has no field restriction.

CASL AST to Prisma Query Conversion#

import {
  AbilityBuilder,
  type Ability,
  type ForcedSubject,
  type TaggedSubject,
} from '@casl/ability';
import { accessibleBy, createPrismaAbility, type PrismaQuery } from '@casl/prisma';
import type { Document } from '@prisma/client';

// A Prisma ability: conditions use Prisma WhereInput syntax, not Mongo
type AppPrismaAbility = Ability<
  [string, Document & ForcedSubject<'Document'>],
  PrismaQuery,
  TaggedSubject
>;

function definePrismaAbilityFor(user: User): AppPrismaAbility {
  const { can, cannot, build } = new AbilityBuilder<AppPrismaAbility>(
    createPrismaAbility
  );

  if (user.role === 'admin') {
    can('manage', 'Document');
  }

  // Tenant deny, declared last: `not` replaces Mongo's `$ne`
  cannot('manage', 'Document', { tenantId: { not: user.tenantId } });

  return build();
}

const ability = definePrismaAbilityFor(user);

// Convert CASL rules to Prisma where clause
const documents = await prisma.document.findMany({
  where: accessibleBy(ability).ofType('Document'),
});

// Combine with business logic filters
const projectDocuments = await prisma.document.findMany({
  where: {
    AND: [accessibleBy(ability).ofType('Document'), { projectId: projectId }],
  },
});

The Mongo-syntax ability from the tenant section does not fit this adapter. @casl/prisma builds its ability with createPrismaAbility, whose conditions use Prisma WhereInput syntax, so the tenant deny uses not where the Mongo version used $ne.

Compare to the custom toWhereClause() from Post 105:

  • CASL’s accessibleBy() converts the ability’s object conditions into a Prisma where clause
  • The custom toWhereClause() uses condition descriptors with toFilter callbacks
  • CASL automatically handles OR logic across multiple matching rules
  • When no rule grants access, accessibleBy() returns a marker condition: Prisma rejects the query, or, with createCaslExtension, findMany returns an empty array (fail-closed either way)

Warning

accessibleBy() needs object conditions. Lambda conditions (PureAbility) cannot be converted, so that pattern gives up Prisma query conversion.

Choosing Between Four Approaches#

RBAC vs. Custom ABAC vs. CASL ABAC#

DimensionRBAC (Post 103)Custom ABAC (Posts 104-105)CASL ABAC (Post 106)
Core logicRole-permission lookupPolicy engine with conditionsAbilityBuilder with MongoDB conditions
Lines of auth code~80 (matrix + can())A few hundred (builder + engine + field + DB)~50 (defineAbilitiesFor) + library
can() signaturecan(role, resource, action)can(user, action, resource, data?, env?)ability.can(action, subject(type, data))
Contextual conditionsNo (requires helpers)Yes (inline in policy builder)Yes (MongoDB-style objects or lambdas)
Field-level permissionsNoYes (getVisibleFields, pickPermittedFields)Yes (permittedFieldsOf)
DB query filteringNoYes (toWhereClause())Yes (accessibleBy() with Prisma)
Environment rulesNoYes (time, IP, flags)Partial (via custom conditions)
Multi-tenancyManual check per methodGlobal condition (automatic)One inverted cannot() rule, declared last (object checks only)
Type safetyFull (generics, mapped types)Full (resource-action generics)Good (typed actions/subjects, weaker on conditions)
Condition formatNone (role lookup only)Functions plus toFilter descriptorsObjects (DB-translatable) or lambdas (not translatable)
Negative rulesNoYes (forbid())Yes (cannot())
MaintenanceTeam-ownedTeam-ownedLibrary-maintained core
Bundle size0 (built-in)0 (built-in)~6KB (core) + adapters

Decision Framework: Which System Should You Choose?#

2-4 simple roles

None

1-2 helpers

3+

5+ roles or
role explosion

Yes

No

Yes

No

No

Yes

Building a
Permission System

How many roles?

Contextual conditions?
ownership, department,
status

RBAC
Post 103
Simplest, fastest

RBAC + Helpers
Post 103 with if/else

Consider ABAC

Team willing to
maintain custom code?

Field-level or
DB filtering needed?

Custom ABAC
Post 104

Custom Full ABAC
Posts 104-105

CASL
Post 106

Multi-tenant?

Done

Add Tenant Layer
Global Condition

When to Choose Each#

RBAC (Post 103)

It works at any team size, for internal tools, simple SaaS, and content platforms with clear roles: 2-4 roles, permissions depending only on role. Choose it when permission requirements map cleanly to “this role can do these things.”

Custom ABAC (Posts 104-105)

A team with authorization expertise, willing to maintain its own auth code, reaches for this when building SaaS with complex business rules, field-level visibility, and large datasets: ownership, department, status, and time conditions all feed into can(), which by now evaluates 3+ contextual conditions per resource. That balance shifts once team bandwidth for auth maintenance drops, or DB query adapters are needed across multiple ORMs.

CASL ABAC (Post 106)

CASL suits a team that would rather spend its time on business logic than on auth internals: building SaaS on Prisma/MongoDB that needs field permissions and DB filtering, trading custom code for a library API the team prefers once the custom ABAC feature set already matches what CASL provides. Rules that lean on environment conditions, or that only work as lambdas, push the decision back toward the custom engine.

External PDP (Cerbos, OPA, Cedar)

A dedicated platform or security team gets the most value here, typically in a microservices or polyglot stack, when several backends, possibly in different languages, need the same authorization decisions. OpenFGA vs SpiceDB vs Cerbos vs OPA vs AWS Verified Permissions compares the platforms.

Where Multi-Tenant Authorization Breaks#

  1. Declaring the CASL tenant deny too early: CASL lets regular rules declared after an inverted rule override it. A can() added below the tenant cannot() escapes the deny for its subject. Keep the deny after every tenant-scoped rule, put only shared subjects below it, and test a cross-tenant object for every subject.

  2. Wrapping shared objects with subject(): The helper defines a type property on the object it receives. Wrapping the same object later as a different subject type throws. Wrap a copy, or tag DTOs and use a custom detectSubjectType.

  3. Writing rules as lambdas by default: The PureAbility + lambda matcher pattern cannot convert conditions to Prisma where clauses. List endpoints then need a separate filter, and that filter drifts from can().

  4. Over-engineering early: Jumping to ABAC or CASL before RBAC fails is premature.

  5. Multi-tenancy as an afterthought: Adding tenant_id to every table after the schema is established is a painful migration. Design tenant isolation from the beginning, even if the first version has only one tenant.

  6. Confusing platform admin with tenant admin: Platform admins manage all tenants (cross-tenant access). Tenant admins manage their own tenant only. Mixing these roles creates either overly permissive tenant admins or insufficiently permissive platform admins.

  7. Choosing an external PDP too early: Cerbos, OPA, and Cedar add infrastructure complexity. For a monolithic Next.js app, in-process authorization (custom or CASL) is simpler and faster. External PDPs make sense when authorization decisions must be shared across independently deployed services.

  8. Not testing cross-tenant scenarios: Unit tests often use a single tenant ID. Add explicit test cases where User A (tenant 1) attempts to access User B’s document (tenant 2). These tests catch missing tenant filters.

Series Retrospective#

The Seven Goals Scorecard#

Post 101 established seven goals for any permission system. Here is how each approach scores:

GoalScattered (101)Service Layer (102)RBAC (103)Custom ABAC (104-105)CASL (106)
Prevent unauthorized accessPartialYesYesYesYes
Consistent (single source of truth)NoYesYesYesYes
Auto-enforceNoArchitecturalArchitecturalArchitectural + GlobalArchitectural + cannot()
Easy to updateNoModerateYes (matrix)Yes (builder)Yes (rules)
AuditableNoModerateYes (matrix)Yes (builder)Yes (rules)
PerformantVariesYes + cacheYes (O(1) lookup)Yes (condition eval)Yes (condition eval)
Type-safeNoPartialFullFullGood

Series Architecture Evolution#

Post 101
Scattered Checks
(Problem)

Post 102
Service Layer
(Architecture)

Post 103
RBAC
(Decision Engine)

Post 104
ABAC
(Policy Engine)

Post 105
Field-Level + DB
(Extensions)

Post 106
Multi-Tenancy + CASL
(Production)

The service layer from Post 102 never changes across all six posts. It stays the enforcement point for every authorization approach while the decision engine inside it evolves from simple role checks to RBAC to ABAC to CASL, so each upgrade stays contained within that one layer.

Authorization Across Service Boundaries#

The series focused on a monolithic Next.js application. As applications grow, authorization decisions must work across service boundaries, typically through one of three patterns:

PatternMechanismTrade-off
Centralized Authorization ServiceA single service evaluates all permission decisions; other services call it via gRPC/HTTPSingle source of truth, but a single point of failure with network latency on every request
Embedded PDP (Sidecar)Each microservice runs its own policy engine (OPA sidecar, Cerbos sidecar), synced centrally by a policy managerNo network hop for decisions, but policy sync complexity and version-drift risk
Token-Based ClaimsAuthorization data is embedded in JWT claims (roles, permissions, tenantId); services trust the token without additional checksSimplest infrastructure, but stale claims and no resource-level authorization

Pattern 3: Token Claims

API Gateway
JWT Issuer

Service A
(trust token)

Service B
(trust token)

Pattern 2: Sidecar PDP

sync

sync

Service A

PDP Sidecar

Service B

PDP Sidecar

Policy Manager

Pattern 1: Centralized

gRPC

gRPC

Service A

Auth Service

Service B

For teams moving from monolith to microservices: start with Pattern 3 (token claims) for service-to-service auth, and add Pattern 2 (embedded PDP) when fine-grained resource-level authorization is needed across services.

Permission Storage: Code vs. Database#

ApproachStrengthsWeaknessesWhen to Use
Code-only (this series)Type-safe, version-controlled, CI/CD testableRequires deployment for changesPermission rules change with app code
Database-storedRuntime-configurable, tenant-customizableNo compile-time safety, migration complexityTenants need custom roles/permissions
HybridDefault rules in code + overrides in DBComplexity of two systems, conflict resolutionSaaS with per-tenant customization

The hybrid pattern works well for production SaaS: define the default permission set in code (type-safe, tested), allow tenants to override specific rules via a database table. The can() function checks code-based rules first, then applies database overrides.

Choosing the Default#

Default to RBAC while permission rules still map cleanly onto roles, and move past it once a single resource needs three or more contextual conditions in can(). The tenant layer belongs in the first version whichever engine runs, and the decision moves to an external PDP when a second service has to make it.

References#

Permission Systems that Scale

Part 6 of 6

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

Related posts