Skip to content

Advanced ABAC: Field-Level Permissions and DB Integration

Extend ABAC with environment-based rules, field-level read and write permissions, and automatic database query filtering that eliminates duplicate permission logic.

Ayhan Sipahi Ayhan Sipahi

Post 104 built a type-safe ABAC policy engine with a builder pattern. The can(user, action, resource, data?) function evaluates subject, resource, and action attributes through declarative conditions. Ownership, department scoping, and resource status became policy rules; the scattered helper functions are gone. Two gaps are left, and both close by extending that builder rather than by adding checks around it.

First, can() returns a boolean; the user either sees the entire resource or nothing. There is no way to control which fields a user can read or write. An admin sees internalNotes; an author should not. An editor can update content but not publishedAt. Second, all conditions evaluate in application memory against already-loaded objects. For list views, the application loads all records, calls can() on each, and discards the ones that fail. The database should do that filtering.

Three additions close them: environment conditions enter the type system, field-level permissions control read and write visibility per role, and ABAC conditions convert into database where clauses for query-level enforcement. Environment is the fourth attribute category of the NIST SP 800-162 model, introduced in Post 104 as a forward reference. Time-based access, IP restrictions, and feature flags belong inside the policy engine rather than in separate middleware checks.

// Preview: what the completed system looks like
// user: the subject from Post 104's subjectFor()
const fields = getVisibleFields(user, 'document', docData, env);
const plan = toWhereClause(user, 'document', 'read', env);
// -> { kind: 'where', where } | { kind: 'deny' } | { kind: 'in-memory' }

Every default in these additions fails closed, following the principle from Post 101: a role without field entries sees no fields, a condition without environment data denies, and a filter that cannot be built never turns into “no filter”.

Environment-Based Rules#

Extending the Type System#

Post 104’s Condition<R> type receives (user: User, data: ResourceDataMap[R]) => boolean. Environment attributes (time, IP address, locale, feature flags) are external to both subject and resource. They need their own type.

// lib/permissions.ts

interface Environment {
  currentTime: Date;
  ipAddress?: string; // set by a trusted proxy hop, never the raw header
  network?: 'office' | 'external'; // derived from ipAddress on the server
  locale?: string;
  featureFlags?: Record<string, boolean>;
}

// Extend condition to receive environment
type Condition<R extends Resource> = (
  user: User,
  data: ResourceDataMap[R],
  env?: Environment
) => boolean;

// Updated can() signature
function can<R extends Resource>(
  user: User,
  action: Action,
  resource: R,
  data?: ResourceDataMap[R],
  env?: Environment
): boolean

The can() signature has evolved across the series:

// Post 103 (RBAC):
can(role, resource, action): boolean

// Post 104 (ABAC):
can<R>(user, action, resource, data?): boolean

// Post 105 (Advanced ABAC):
can<R>(user, action, resource, data?, env?): boolean

The env parameter is optional. Existing conditions from Post 104 continue working unchanged. Making environment optional preserves backward compatibility while completing the NIST four-attribute model.

Practical Examples#

Time-based restriction: billing operations only during business hours:

// Business hours in the rule's own time zone, not the server's
function isBusinessHours(at: Date, timeZone: string): boolean {
  const parts = new Intl.DateTimeFormat('en-US', {
    timeZone,
    weekday: 'short',
    hour: 'numeric',
    hourCycle: 'h23',
  }).formatToParts(at);
  const weekday = parts.find((p) => p.type === 'weekday')?.value;
  const hour = Number(parts.find((p) => p.type === 'hour')?.value);
  return weekday !== 'Sat' && weekday !== 'Sun' && hour >= 9 && hour < 17;
}

const BILLING_TIME_ZONE = 'Europe/Istanbul';

.role('billing_admin')
  .can(['create', 'update'], 'invoice', [
    // No environment = no proof of the time = deny
    (user, data, env) =>
      env !== undefined && isBusinessHours(env.currentTime, BILLING_TIME_ZONE),
  ])

Date.prototype.getHours() and getDay() read the server’s local time zone. On AWS Lambda that zone is UTC (the runtime sets TZ to :UTC), so a 9-to-17 rule written with getHours() would open and close three hours late for a team in Istanbul. The time zone belongs to the rule, so it is a parameter of the condition. In a multi-tenant system it would come from the tenant’s settings. Intl.DateTimeFormat with a timeZone option returns the hour and weekday in that zone, whatever the server’s clock is set to.

IP-based restriction: document deletion only from the office network:

.forbid('delete', 'document', [
  // Deny unless the request came from the office network.
  // A missing environment leaves network undefined: deny.
  (user, doc, env) => env?.network !== 'office',
])

The deny applies when the service passes the document’s data, as every service method in Post 104 does. Post 104’s can() skips a conditional entry without data, deny entries included, so a data-less check only answers whether the role can delete documents at all.

Feature flag gating: new functionality behind feature flags:

.role('editor')
  .can('publish', 'document', [
    (user, doc) => user.departmentId != null && user.departmentId === doc.departmentId,
    (user, doc, env) => env?.featureFlags?.['bulk-publish'] === true,
  ])

Note

Environment conditions follow the same AND logic as other conditions in the builder. All conditions in an array must pass for the permission to be granted.

Entries for the same action still combine with OR, as in Post 104. The billing and feature-flag examples therefore replace any entry the role already has for those actions; added next to an unconditional entry, they would only widen access. A rule that must narrow access for every role is a deny, which is why the network rule uses forbid().

Service Layer Integration#

The service layer constructs the Environment object from the request context. It builds it once per request, then passes it through:

// lib/environment.ts
import 'server-only';
import { BlockList, isIP } from 'node:net';

// Reverse proxies you run in front of the app (load balancer, CDN)
const TRUSTED_PROXY_HOPS = 1;

const officeNetwork = new BlockList();
officeNetwork.addSubnet('10.0.0.0', 16); // office range 10.0.0.0/16

// The address the outermost trusted proxy saw. Entries to its left
// come from the client and can be forged.
function clientIp(request: Request): string | undefined {
  const hops = (request.headers.get('x-forwarded-for') ?? '')
    .split(',')
    .map((hop) => hop.trim())
    .filter(Boolean);
  // Fewer entries than proxies: the request skipped a proxy
  if (hops.length < TRUSTED_PROXY_HOPS) return undefined;
  return hops[hops.length - TRUSTED_PROXY_HOPS];
}

export function getEnvironment(request: Request): Environment {
  const ipAddress = clientIp(request);
  const inOffice =
    ipAddress !== undefined &&
    isIP(ipAddress) === 4 &&
    officeNetwork.check(ipAddress, 'ipv4');
  return {
    currentTime: new Date(),
    ipAddress,
    network: inOffice ? 'office' : 'external',
    locale: request.headers.get('accept-language')?.split(',')[0],
    featureFlags: getFeatureFlags(),
  };
}

// In a service method (user: the subject from subjectFor())
const env = getEnvironment(request);
if (!can(user, 'update', 'document', documentData, env)) {
  throw new ForbiddenError();
}

A key design decision: environment data comes from the request context. It stays out of ResourceDataMap, which describes database-backed resources. Mixing request context with resource data breaks the NIST model and makes conditions harder to reason about.

X-Forwarded-For is a list (client, proxy1, proxy2), and any client can send the header with a value of its choice. Each proxy appends the address it received the request from, so only the entries your own proxies added can be trusted. With one proxy, that is the rightmost entry; with N proxies, it is the Nth from the right. The leftmost value is whatever the client wrote: a check like startsWith('10.0.') on it lets anyone pass by sending X-Forwarded-For: 10.0.0.1. If the application server can also be reached directly from the internet, no entry of the header is trustworthy, and the network rule has nothing to stand on. The subnet test uses Node’s built-in net.BlockList instead of string prefixes. It sits in a server-only module because node:net does not exist in the browser, while the policy file is also imported by client components; the condition reads only the derived network attribute.

Treat the network rule as one layer that works alongside authentication. An address tells where a request came from; the session tells who sent it.

Field-Level Read Permissions#

The Problem#

Consider the document resource with these fields: id, title, content, status, authorId, departmentId, internalNotes, reviewComments, publishedAt.

Different roles need different field visibility:

Fieldadmineditorauthor (own)viewer
id, title, content, status, publishedAtyesyesyesyes
authorIdyesyesyes—
departmentIdyesyes——
internalNotesyes———
reviewCommentsyesyes (in review)——

Without field-level permissions, the service returns the full object and trusts the frontend to hide fields. This is security by obscurity. The API response contains sensitive data regardless of what the UI renders.

Post 104’s ResourceDataMap['document'] holds only the four attributes its conditions read. For field permissions it lists every field above, and toResourceData() extends Post 104’s documentAttributes() to copy them from the row (departmentId still comes from document.project, so every query loads that relation). The fields beyond the four policy attributes are optional, because a document that is about to be created has no id or publishedAt yet.

Type System Extension#

The field permission system maps resources to their field names with conditions:

type ResourceField<R extends Resource> = keyof ResourceDataMap[R] & string;

// Explicit marker for "every field of the resource"
export const ALL_FIELDS = '*';

interface FieldPermissionEntry<R extends Resource> {
  resource: R;
  action: 'read' | 'write';
  fields: ResourceField<R>[] | typeof ALL_FIELDS;
  conditions?: Condition<R>[];
}

Add field permissions to the builder:

.role('admin')
  .canReadFields('document', ALL_FIELDS)

.role('author')
  .canReadFields('document',
    ['id', 'title', 'content', 'status', 'publishedAt', 'authorId'],
    [(user, doc) => doc.authorId === user.userId]
  )
  .canReadFields('document',
    ['id', 'title', 'content', 'status', 'publishedAt']
    // no condition -- public fields for any document
  )

.role('editor')
  .canReadFields('document',
    ['id', 'title', 'content', 'status', 'publishedAt', 'authorId', 'departmentId']
  )
  .canReadFields('document',
    ['id', 'title', 'content', 'status', 'publishedAt', 'authorId', 'departmentId', 'reviewComments'],
    [(user, doc) => doc.status === 'review']
  )

.role('viewer')
  .canReadFields('document',
    ['id', 'title', 'content', 'status', 'publishedAt']
  )

The rule: a role sees only the fields its entries name, provided it has read access via can(). No entries means no fields. The admin gets full visibility through the explicit ALL_FIELDS marker, so a role added later starts with no visible fields. The viewer entry is what keeps authorId and internalNotes out of a viewer’s response.

The getVisibleFields() Function#

Read and write permissions share one collector. It returns the union of the fields from every entry that applies:

function collectFields<R extends Resource>(
  user: User,
  resource: R,
  action: 'read' | 'write',
  data?: ResourceDataMap[R],
  env?: Environment
): ResourceField<R>[] {
  // Same widening cast as Post 104's can(): the filter on
  // entry.resource is what makes the narrowing safe
  const entries = (fieldPermissions[user.role] ?? []).filter(
    (e) => e.resource === resource && e.action === action
  ) as unknown as FieldPermissionEntry<R>[];

  // No entries: an empty set, never "all fields" (fail closed)
  const fields = new Set<ResourceField<R>>();
  for (const entry of entries) {
    const applies =
      !entry.conditions || entry.conditions.length === 0
        ? true
        : data !== undefined &&
          entry.conditions.every((c) => c(user, data, env));
    if (!applies) continue;

    // resourceSchemas: one object per resource whose keys are its fields
    const granted =
      entry.fields === ALL_FIELDS
        ? (Object.keys(resourceSchemas[resource]) as ResourceField<R>[])
        : entry.fields;
    granted.forEach((f) => fields.add(f));
  }
  return Array.from(fields);
}

function getVisibleFields<R extends Resource>(
  user: User,
  resource: R,
  data?: ResourceDataMap[R],
  env?: Environment
): ResourceField<R>[] {
  // No read access to the record: no fields at all
  if (!can(user, 'read', resource, data, env)) return [];
  return collectFields(user, resource, 'read', data, env);
}

The filterFields() utility takes a resource object and a list of visible fields, returning a new object with only those fields:

function filterFields<R extends Resource>(
  data: ResourceDataMap[R],
  fields: ResourceField<R>[]
): Partial<ResourceDataMap[R]> {
  const result: Partial<ResourceDataMap[R]> = {};
  for (const field of fields) {
    if (field in data) {
      (result as Record<string, unknown>)[field] = data[field as keyof typeof data];
    }
  }
  return result;
}

Service Layer Integration#

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();

  // The subject for this document's project (Post 104)
  const user = subjectFor(session, document.project);
  const docData = toResourceData(document);
  if (!user || !can(user, 'read', 'document', docData)) {
    throw new ForbiddenError();
  }

  // Filter fields based on role and conditions
  const visibleFields = getVisibleFields(user, 'document', docData);
  return filterFields(docData, visibleFields);
}

UI Field Hiding#

On the client side, use getVisibleFields() to conditionally render fields:

function DocumentDetail({ document, user }: Props) {
  const fields = getVisibleFields(user, 'document', document);

  return (
    <div>
      <h1>{document.title}</h1>
      {fields.includes('internalNotes') && (
        <section>{document.internalNotes}</section>
      )}
      {fields.includes('reviewComments') && (
        <section>{document.reviewComments}</section>
      )}
    </div>
  );
}

UI hiding is for UX, not security. The service layer already filtered the fields in the API response. The client cannot render what it did not receive. As established in Post 102: the server is the security boundary, the client is the UX convenience.

Field-Level Write Permissions#

Builder Extension#

Write permissions are distinct from read permissions. An editor might read internalNotes but not write to it. A moderator might write status but not content.

.role('author')
  .canWriteFields('document', ['title', 'content'])

.role('editor')
  .canWriteFields('document', ['title', 'content', 'status', 'reviewComments'], [
    (user, doc) => user.departmentId != null && user.departmentId === doc.departmentId,
  ])

.role('admin')
  // An explicit list: id and authorId stay system-managed
  .canWriteFields('document',
    ['title', 'content', 'status', 'internalNotes', 'reviewComments', 'publishedAt']
  )

ALL_FIELDS works for write entries too, but for the admin it would also open id and authorId. A role without canWriteFields entries writes nothing, even when can() grants update.

The write permission matrix:

Fieldadmineditor (dept)author (own)
titleyesyesyes
contentyesyesyes
statusyesyes—
internalNotesyes——
reviewCommentsyesyes—
publishedAtyes——

The pickPermittedFields() Function#

getWritableFields() is the write-side twin of getVisibleFields(). It does not call can(): the service method checks update or create on the record first.

function getWritableFields<R extends Resource>(
  user: User,
  resource: R,
  data?: ResourceDataMap[R], // existing or proposed resource data
  env?: Environment
): ResourceField<R>[] {
  return collectFields(user, resource, 'write', data, env);
}

function pickPermittedFields<R extends Resource>(
  user: User,
  resource: R,
  input: Partial<ResourceDataMap[R]>,
  data?: ResourceDataMap[R],
  env?: Environment
): Partial<ResourceDataMap[R]> {
  // No write entries: an empty set, so nothing passes
  const permitted = new Set<string>(
    getWritableFields(user, resource, data, env)
  );

  // Keep only the permitted fields of the input
  const result: Partial<ResourceDataMap[R]> = {};
  for (const [key, value] of Object.entries(input)) {
    if (permitted.has(key)) {
      (result as Record<string, unknown>)[key] = value;
    }
  }
  return result;
}

Silent Drop vs. Error#

Two approaches when a user submits a forbidden field:

  1. Silent drop: Strip the field and proceed. The user does not know the field was ignored. Simpler for the client, but hides errors.
  2. Error: Reject the entire submission with a 403. More explicit, but requires the client to know which fields are allowed before submitting.
// Option A: Silent drop (CASL's docs pair permittedFieldsOf() with lodash pick)
const permitted = pickPermittedFields(user, 'document', input, docData);
await db.document.update({ where: { id }, data: permitted });

// Option B: Explicit validation (for admin/audit contexts)
function validatePermittedFields<R extends Resource>(
  user: User,
  resource: R,
  input: Partial<ResourceDataMap[R]>,
  data?: ResourceDataMap[R],
  env?: Environment
): void {
  const permitted = pickPermittedFields(user, resource, input, data, env);
  const forbidden = Object.keys(input).filter(k => !(k in permitted));
  if (forbidden.length > 0) {
    throw new ForbiddenError(`Cannot write fields: ${forbidden.join(', ')}`);
  }
}

Silent drop for APIs, error for admin contexts works well in practice. The service layer chooses which to use based on the operation’s sensitivity.

Create and Update Flows#

Create Flow#

On create, no document exists yet, but the new one has known attributes: the creator becomes its author, it starts as a draft, and it lands in the current project. As in Post 104, the service passes these proposed attributes, so the author’s ownership condition and the editor’s department condition run on create too. The same attributes decide which fields the role may write:

export async function createDocument(projectId: string, input: DocumentInput) {
  const session = await requireSession();
  const project = await db.project.findUnique({
    where: { id: projectId },
    include: { members: true },
  });
  if (!project) throw new NotFoundError();

  const user = subjectFor(session, project);
  if (!user) throw new ForbiddenError(); // not a member

  // The attributes the new document will have (Post 104)
  const proposed = {
    authorId: user.userId,
    status: 'draft' as const,
    projectId,
    departmentId: project.departmentId,
  };
  if (!can(user, 'create', 'document', proposed)) {
    throw new ForbiddenError();
  }

  // Filter input to only fields this user can write
  const permitted = pickPermittedFields(user, 'document', input, proposed);

  // System sets authorId, status, projectId -- not from user input
  return await db.document.create({
    data: {
      ...permitted,
      authorId: user.userId,
      status: 'draft',
      projectId,
    },
  });
}

authorId and status are system-managed fields, never from user input. Even if the client sends authorId, pickPermittedFields() strips it because it is not in the author’s write fields.

Update Flow#

On update, existing resource data is available for conditions:

export async function updateDocument(documentId: string, input: DocumentInput) {
  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);
  const docData = toResourceData(document);
  if (!user || !can(user, 'update', 'document', docData)) {
    throw new ForbiddenError();
  }

  // Filter input to only fields this user can write
  const permitted = pickPermittedFields(user, 'document', input, docData);

  return await db.document.update({
    where: { id: documentId },
    data: permitted,
  });
}

Conditional Form Rendering#

The UI can use getWritableFields() to conditionally render form fields:

function DocumentForm({ document, user }: Props) {
  // On a create form, document holds the proposed attributes
  const writeFields = getWritableFields(user, 'document', document);

  return (
    <form>
      {writeFields.includes('title') && (
        <input name="title" defaultValue={document?.title} />
      )}
      {writeFields.includes('content') && (
        <textarea name="content" defaultValue={document?.content} />
      )}
      {writeFields.includes('status') && (
        <select name="status" defaultValue={document?.status}>
          <option value="draft">Draft</option>
          <option value="published">Published</option>
        </select>
      )}
      {writeFields.includes('internalNotes') && (
        <textarea name="internalNotes" defaultValue={document?.internalNotes} />
      )}
    </form>
  );
}

Form rendering is UX. The server-side pickPermittedFields() is the security boundary. Even if a malicious client adds hidden fields to the form submission, pickPermittedFields() strips them.

Automatic DB Query Filtering#

The ConditionDescriptor Approach#

Post 104’s conditions are opaque functions. They evaluate in memory but cannot be translated to SQL. For list views (“show me all documents I can read”), loading all records and filtering with can() in a loop is wasteful.

The idea: provide a declarative descriptor alongside each condition function that describes what it does in database terms:

interface ConditionDescriptor<R extends Resource> {
  // The function for in-memory evaluation (same as before)
  evaluate: (user: User, data: ResourceDataMap[R], env?: Environment) => boolean;
  // Declarative description for DB translation:
  // {} = matches every row, null = matches no row
  toFilter?: (user: User, env?: Environment) => WhereClause<R> | null;
}

// A builder condition is either a plain function or a descriptor
type PolicyCondition<R extends Resource> = Condition<R> | ConditionDescriptor<R>;

// can() calls evaluate() when the condition is a descriptor
const evaluate = <R extends Resource>(
  condition: PolicyCondition<R>,
  user: User,
  data: ResourceDataMap[R],
  env?: Environment
): boolean =>
  typeof condition === 'function'
    ? condition(user, data, env)
    : condition.evaluate(user, data, env);

type FieldFilter<V> =
  | V              // equality
  | { $ne: V }     // not equal
  | { $in: V[] }   // in list
  | { $gte: V }    // greater than or equal
  | { $lte: V };   // less than or equal

// ORM-agnostic where clause representation
type WhereClause<R extends Resource> =
  | { [K in keyof ResourceDataMap[R]]?: FieldFilter<ResourceDataMap[R][K]> }
  | { $or: WhereClause<R>[] }
  | { $and: WhereClause<R>[] }
  | { $not: WhereClause<R> };

This syntax is similar to MongoDB’s query format and CASL’s conditions. Prisma, Drizzle, and other ORMs can consume it with a simple adapter.

Updated builder with descriptors. The document rules are Post 104’s, with each condition rewritten as a descriptor:

// Post 104's null-safe department match, now with a filter:
// a subject without a department matches no rows
const sameDepartment: ConditionDescriptor<'document'> = {
  evaluate: (user, doc) =>
    user.departmentId != null && user.departmentId === doc.departmentId,
  toFilter: (user) =>
    user.departmentId == null ? null : { departmentId: user.departmentId },
};

const isPublished: ConditionDescriptor<'document'> = {
  evaluate: (user, doc) => doc.status === 'published',
  toFilter: () => ({ status: 'published' }),
};

const isOwnDocument: ConditionDescriptor<'document'> = {
  evaluate: (user, doc) => doc.authorId === user.userId,
  toFilter: (user) => ({ authorId: user.userId }),
};

const isArchived: ConditionDescriptor<'document'> = {
  evaluate: (user, doc) => doc.status === 'archived',
  toFilter: () => ({ status: 'archived' }),
};

// Project entries stay as in Post 104
const permissions = new PermissionBuilder()
  .role('admin')
    .can(['create', 'read', 'update', 'delete', 'publish'], 'document')
    // No conditions = no filter = every document in the project

  .role('editor')
    .can('read', 'document') // every document in the project, drafts too
    .can(['create', 'update', 'publish'], 'document', [sameDepartment])

  .role('author')
    .can('read', 'document', [isPublished])
    .can(['create', 'read', 'update'], 'document', [isOwnDocument])

  .role('viewer')
    .can('read', 'document', [isPublished]) // drafts never reach a viewer

  .forbid(['update', 'publish'], 'document', [isArchived])
  .forbid('publish', 'document', [isOwnDocument]) // separation of duty
  .build();

toFilter returns null when the subject lacks the attribute the condition needs. Returning { departmentId: user.departmentId } instead would hand the adapter { departmentId: undefined }, and Prisma treats an undefined filter as if the key were absent, so the query would match every row.

The toWhereClause() Function#

toWhereClause() produces a query plan with three outcomes: a where clause, a denial, or a signal that the rows need in-memory checks. It follows can() from Post 104: allow entries combine with OR, conditions inside an entry with AND, and a matching deny wins.

type QueryPlan<R extends Resource> =
  | { kind: 'where'; where: WhereClause<R> } // {} = every row in scope
  | { kind: 'deny' }                          // no row can match
  | { kind: 'in-memory' };                    // check rows with can()

const IN_MEMORY = Symbol('in-memory');
const isEmpty = (clause: object) => Object.keys(clause).length === 0;

// One entry: the AND of its conditions. null = the entry never matches
function entryFilter<R extends Resource>(
  entry: PermissionEntry<R>,
  user: User,
  env?: Environment
): WhereClause<R> | null | typeof IN_MEMORY {
  const parts: WhereClause<R>[] = [];
  for (const condition of entry.conditions ?? []) {
    if (typeof condition === 'function' || !condition.toFilter) return IN_MEMORY;
    const filter = condition.toFilter(user, env);
    if (filter === null) return null;
    if (!isEmpty(filter)) parts.push(filter);
  }
  if (parts.length === 0) return {}; // unconditional entry
  return parts.length === 1 ? parts[0] : { $and: parts };
}

function toWhereClause<R extends Resource>(
  user: User,
  resource: R,
  action: Action,
  env?: Environment
): QueryPlan<R> {
  const entries = permissions[user.role].filter(
    (e) => e.resource === resource && e.actions.includes(action)
  ) as unknown as PermissionEntry<R>[];

  const allows: WhereClause<R>[] = [];
  const denies: WhereClause<R>[] = [];
  let allowInMemory = false;
  for (const entry of entries) {
    const filter = entryFilter(entry, user, env);
    if (filter === null) continue; // can never match
    if (filter === IN_MEMORY) {
      // An untranslatable deny could exclude any row
      if (entry.effect === 'deny') return { kind: 'in-memory' };
      allowInMemory = true;
      continue;
    }
    (entry.effect === 'deny' ? denies : allows).push(filter);
  }

  if (denies.some(isEmpty)) return { kind: 'deny' }; // unconditional deny
  if (!allows.some(isEmpty) && allowInMemory) return { kind: 'in-memory' };
  if (allows.length === 0) return { kind: 'deny' }; // deny by default

  // Allow entries: OR. An unconditional one covers every row.
  const allow: WhereClause<R> = allows.some(isEmpty)
    ? {}
    : allows.length === 1 ? allows[0] : { $or: allows };
  if (denies.length === 0) return { kind: 'where', where: allow };

  // Deny entries: exclude every row that any of them matches
  const notDenied: WhereClause<R> = {
    $not: denies.length === 1 ? denies[0] : { $or: denies },
  };
  return {
    kind: 'where',
    where: isEmpty(allow) ? notDenied : { $and: [allow, notDenied] },
  };
}

Against the policy above, the plans come out as follows (Prisma syntax after the adapter below):

SubjectActionPlan
viewerread{ status: 'published' }
authorread{ OR: [{ status: 'published' }, { authorId }] }
editor, adminread{}
editorupdate{ AND: [{ project: { is: { departmentId } } }, { NOT: { status: 'archived' } }] }
editor without departmentupdatedeny
authorpublishdeny

Warning

An empty object {} and null have different semantics. {} means “no filter; return all records” (the admin and editor read case). null from toFilter means “this condition can never match,” and with no other entry left, the plan is a denial. Returning {} instead of null for a denied subject would return all records. This distinction is critical for security.

ORM Adapter Layer#

The WhereClause<R> is ORM-agnostic. Adapters convert it to ORM-specific syntax. Two details matter for security. A policy attribute is not always a column: departmentId lives on the document’s project, so the adapter maps it to a relation filter. And an undefined value must stop the query instead of reaching the ORM, where it would silently drop the filter.

// Prisma adapter

// Where a policy attribute lives, when it is not a column of its own
type FieldPaths<R extends Resource> = Partial<Record<ResourceField<R>, string[]>>;

export const documentPaths: FieldPaths<'document'> = {
  departmentId: ['project', 'departmentId'], // no column on Document
};

// ['project', 'departmentId'] -> { project: { is: { departmentId: filter } } }
function nest(path: string[], filter: unknown): Record<string, unknown> {
  const [head, ...rest] = path;
  return rest.length === 0
    ? { [head]: filter }
    : { [head]: { is: nest(rest, filter) } };
}

function toPrismaOp(key: string, value: unknown): unknown {
  if (typeof value !== 'object' || value === null || value instanceof Date) {
    return value; // equality
  }
  const op = value as Record<string, unknown>;
  if (Object.values(op).some((v) => v === undefined)) {
    throw new Error(`Undefined filter value for "${key}"`);
  }
  if ('$ne' in op) return { not: op.$ne };
  if ('$in' in op) return { in: op.$in };
  if ('$gte' in op) return { gte: op.$gte };
  if ('$lte' in op) return { lte: op.$lte };
  throw new Error(`Unknown operator for "${key}"`);
}

function toPrismaWhere<R extends Resource>(
  clause: WhereClause<R>,
  paths: FieldPaths<R> = {}
): Record<string, unknown> {
  const parts: Record<string, unknown>[] = [];
  for (const [key, value] of Object.entries(clause)) {
    // Prisma ignores an undefined filter and returns every row
    if (value === undefined) {
      throw new Error(`Undefined filter value for "${key}"`);
    }
    if (key === '$or') {
      parts.push({ OR: (value as WhereClause<R>[]).map((c) => toPrismaWhere(c, paths)) });
    } else if (key === '$and') {
      parts.push({ AND: (value as WhereClause<R>[]).map((c) => toPrismaWhere(c, paths)) });
    } else if (key === '$not') {
      parts.push({ NOT: toPrismaWhere(value as WhereClause<R>, paths) });
    } else {
      const path = paths[key as ResourceField<R>] ?? [key];
      parts.push(nest(path, toPrismaOp(key, value)));
    }
  }
  if (parts.length === 0) return {};
  return parts.length === 1 ? parts[0] : { AND: parts };
}

// Drizzle adapter: columns maps each attribute to a column of the
// query's tables (departmentId -> projects.departmentId needs the join)
function toDrizzleWhere<R extends Resource>(
  clause: WhereClause<R>,
  columns: Record<string, Column>
): SQL {
  const parts: SQL[] = [];
  for (const [key, value] of Object.entries(clause)) {
    if (value === undefined) {
      throw new Error(`Undefined filter value for "${key}"`);
    }
    const nested = (v: unknown) =>
      (v as WhereClause<R>[]).map((c) => toDrizzleWhere(c, columns));
    if (key === '$or') parts.push(or(...nested(value)) ?? sql`false`);
    else if (key === '$and') parts.push(and(...nested(value)) ?? sql`true`);
    else if (key === '$not') parts.push(not(toDrizzleWhere(value as WhereClause<R>, columns)));
    else {
      const column = columns[key];
      if (!column) throw new Error(`No column mapped for "${key}"`);
      if (typeof value === 'object' && value !== null && !(value instanceof Date)) {
        const op = value as Record<string, unknown>;
        if (Object.values(op).some((v) => v === undefined)) {
          throw new Error(`Undefined filter value for "${key}"`);
        }
        if ('$ne' in op) parts.push(ne(column, op.$ne));
        else if ('$in' in op) parts.push(inArray(column, op.$in as unknown[]));
        else if ('$gte' in op) parts.push(gte(column, op.$gte));
        else if ('$lte' in op) parts.push(lte(column, op.$lte));
        else throw new Error(`Unknown operator for "${key}"`);
      } else {
        parts.push(eq(column, value));
      }
    }
  }
  // An empty clause matches every row
  return and(...parts) ?? sql`true`;
}

Prisma also offers a guard of its own: the strictUndefinedChecks preview feature turns an explicit undefined in a query into a runtime error. It is a second line of defense; the adapter check works without it.

Complete service layer integration for list views. The subject comes from Post 104’s subjectFor(), because the role only holds inside one project, and the project ID is always part of the query:

export async function listDocuments(projectId: string, request: Request) {
  const session = await requireSession();
  const project = await db.project.findUnique({
    where: { id: projectId },
    include: { members: true },
  });
  if (!project) throw new NotFoundError();

  const user = subjectFor(session, project);
  if (!user) throw new ForbiddenError(); // not a member

  const env = getEnvironment(request);
  const plan = toWhereClause(user, 'document', 'read', env);
  if (plan.kind === 'deny') return [];

  // 'where': push the permission into the query.
  // 'in-memory': load the project's rows and check each one.
  const rows = await db.document.findMany({
    where: {
      AND: [
        { projectId },
        plan.kind === 'where' ? toPrismaWhere(plan.where, documentPaths) : {},
      ],
    },
    include: { project: true },
  });

  return rows
    .map(toResourceData)
    .filter((doc) => plan.kind === 'where' || can(user, 'read', 'document', doc, env))
    .map((doc) => filterFields(doc, getVisibleFields(user, 'document', doc, env)));
}

The in-memory branch loads every document of the project before filtering, so it costs what the database filter was meant to save. Pagination does not combine well with it either: a page of 20 rows can shrink to 3 after the check. Treat an in-memory plan in a hot list view as a signal to add a toFilter to the condition that caused it.

What Cannot Be Pushed to the Database#

Not all conditions are translatable. Complex logic and cross-resource conditions generally stay in memory:

  • (user, doc) => doc.tags.some(t => user.expertise.includes(t)): array intersection logic
  • (user, doc) => doc.wordCount > 1000 && user.role === 'senior_editor': compound logic mixing subject and resource

Environment conditions sit in between. isBusinessHours(env.currentTime, zone) reads no resource attribute, so it never becomes a WHERE clause, but it can be decided before the query runs. Its toFilter returns {} inside business hours and null outside them.

The toFilter field is optional. If omitted, the condition falls back to in-memory evaluation: toWhereClause() returns an in-memory plan, and listDocuments() runs can() on each loaded row. Translatable conditions become WHERE clauses; untranslatable ones cost a post-fetch check and still return the correct rows.

This is the same pattern used by production authorization systems. OPA’s Compile API calls it “partial evaluation.” Cerbos’s PlanResources API returns three outcomes: ALWAYS_ALLOWED, ALWAYS_DENIED, or CONDITIONAL with an AST. QueryPlan keeps the same split: {} plays the role of always-allowed, deny of always-denied, and a non-empty where of conditional. The in-memory outcome is the price of opaque functions; with a policy language, the engine can analyze every condition itself. The lightweight TypeScript version here follows the same principle with less infrastructure.

The Unified System#

The complete system makes the policy builder a single source of truth. Changing a condition in the builder automatically propagates to every layer:

  • can(): record-level access control
  • getVisibleFields(): field-level read permissions
  • pickPermittedFields(): field-level write permissions
  • toWhereClause(): database query filtering

Yes

No

Deny

Allow

Read

Write

User Request

Service Layer

List View?

toWhereClause()
DB-level filter

Database Query
WHERE ...

Filtered Records

Load Single Record

can()
Record Access?

403 Forbidden

Read or Write?

getVisibleFields()
Field-level read

filterFields()
Strip hidden fields

API Response

pickPermittedFields()
Field-level write

Save to Database

getVisibleFields()
per record

Example: “Editors can now also see reviewComments if the document is in review status.” One change in the builder:

.role('editor')
  .canReadFields('document',
    ['id', 'title', 'content', 'status', 'reviewComments', 'publishedAt'],
    [(user, doc) => doc.status === 'review']
  )
  • getVisibleFields() now returns reviewComments for editors when status === 'review'
  • The React component already has {fields.includes('reviewComments') && ...}; it renders automatically
  • The API response already uses filterFields(); it includes the field automatically
  • No service method, React component, or database query needs to change

ABAC Pros and Cons#

When ABAC Excels#

  1. 3+ contextual rules per resource: If permissions depend on ownership, department, status, time, and other attributes, ABAC eliminates the helper function proliferation from Post 103.
  2. Field-level visibility requirements: When different roles see different fields of the same resource, field permissions are cleaner than ad-hoc field stripping.
  3. Database-level enforcement needed: When list views must be efficient, the toWhereClause() pattern moves the filtering of every translatable condition into the query.
  4. Audit requirements: A centralized policy builder is easier to audit than scattered helper functions. “What can an editor do?” is answerable by reading one section of the builder.
  5. Policy changes are frequent: When business rules change often, modifying one condition in the builder is faster and safer than updating all service methods and components.

When ABAC Is Overkill#

  1. Simple role-based access: If permissions depend only on role with no contextual conditions, RBAC from Post 103 is simpler and equally correct.
  2. Small team, few resources: With 2-3 resources and 3-4 roles, the ABAC type system overhead (generics, builders, condition descriptors) may exceed the complexity it saves.
  3. No field-level requirements: If all users see all fields of a resource, the field permission layer adds complexity without benefit.
  4. Prototyping stage: ABAC’s type system makes refactoring harder. During rapid prototyping where resource shapes change frequently, simpler checks are more practical.

Tip

Start with RBAC (Post 103). Add ABAC conditions only when helper functions start proliferating. Add field-level permissions only when different roles need different field visibility. Add DB query filtering only when list views load too many records.

Decision Framework#

None

1-2 rules

3+

No

Yes

No

Yes

Permission Check
Needed

Contextual conditions
ownership, department,
status, time?

RBAC - Post 103
Simplest, sufficient

RBAC + Helpers
Post 103 with if/else

Field-level control
needed?

Basic ABAC - Post 104
can with conditions

Efficient list views
needed?

ABAC + Fields
This Post, Sec 3-5

Full ABAC + DB
This Post, Sec 6-7

LayerAdd When…Skip When…
Environment rulesTime/IP/locale conditions exist; compliance requires context-aware accessAll permissions are context-independent
Field-level readDifferent roles see different fields; sensitive data existsAll roles see all fields
Field-level writeUsers can modify only specific fields; forms vary by roleAll writable users can modify all fields
DB query filteringList views with restricted roles; large datasetsOnly single-record views; small datasets

Common Pitfalls#

  1. Forgetting field filtering on nested resources: If a document has a project relation, loading document.project bypasses project field permissions. Apply filterFields() to nested resources as well.
  2. Condition descriptor drift: The evaluate function and toFilter descriptor must produce equivalent results. Test both against the same truth table to catch drift.
  3. Overusing field-level permissions: Not every resource needs field-level control. For a resource without restrictions, one canReadFields(resource, ALL_FIELDS) line per role keeps things simple and keeps the default closed.
  4. Confusing null and {}: In toFilter, {} means “no filter” (all records) and null means “no match” (deny). The same leak hides in a filter value: { departmentId: undefined } reaches Prisma as no filter at all. Getting either wrong is a security vulnerability.
  5. Missing select in DB queries: toWhereClause() filters rows, not columns. For true DB-level field enforcement, combine it with column selection. In practice, application-level filterFields() is often sufficient.

What’s Next#

This layering holds while every rule is an attribute comparison on the resource being accessed. Tenant isolation and relationship-based rules stretch it: they touch every query and every table, and one missed condition leaks data across customers.

Post 106 takes on the remaining production concerns: tenant isolation as a first-class permission concept, and library evaluation (CASL, Oso, Cerbos, Cedar) against custom code. It closes the series with a decision framework that weighs team size, regulatory requirements, and system complexity.

References#

Permission Systems that Scale

Part 5 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