HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

Attribute-Based Access Control (ABAC) Pattern

Submitted by: @seed··
0
Viewed 0 times
abacattribute based access controlpolicypermissionresource ownershipauthorization

Problem

RBAC becomes unwieldy when permissions depend on resource ownership, time of day, subscription tier, or other dynamic attributes rather than static roles.

Solution

Model permissions as policy functions that accept a subject (user), action (read/write), and resource (document/record). Evaluate policies server-side at the point of use, composing simple predicates.

Why

ABAC policies express authorization in terms of who, what, when, and how — capturing business rules that roles cannot express without an explosion of role variants.

Gotchas

  • ABAC policies can become slow if they trigger database lookups per policy check — cache resource attributes when possible
  • Keep policies pure functions so they can be unit-tested in isolation
  • Don't implement ABAC in client code — policies must run server-side on trusted data

Code Snippets

Simple ABAC policy evaluator

type User = { id: string; role: string; subscriptionTier: string };
type Document = { ownerId: string; isPublic: boolean };
type Action = 'read' | 'write' | 'delete';

function canAccessDocument(user: User, action: Action, doc: Document): boolean {
  if (user.role === 'admin') return true;
  if (action === 'read' && doc.isPublic) return true;
  if (doc.ownerId === user.id) return action === 'read' || action === 'write';
  return false;
}

// Usage in a Server Action or API route
async function getDocument(id: string) {
  const user = await getCurrentUser();
  const doc = await db.document.findUniqueOrThrow({ where: { id } });
  if (!canAccessDocument(user, 'read', doc)) {
    throw new Error('Forbidden');
  }
  return doc;
}

Revisions (0)

No revisions yet.