The user wants a "composable authz engine" that supports:
RBAC (Role-Based Access Control)
ABAC (Attribute-Based Access Control)
ReBAC (Relationship-Based Access Control)
Caching (for performance)
Audit (logging decisions)
The term "composable" implies that these different models shouldn't just be separate functions but should work together or be interchangeable parts of a decision pipeline. For example, a policy might require a specific Role AND a specific Attribute OR a Relationship.
Architecture:
Core Interface: The engine needs a central check(user, action, resource, context) -> boolean interface.
Policy Definition: How are rules defined?
Approach: A policy language or structure. Since this is code generation, I should define a TypeScript/Python/Go struct or class that represents a Policy.
Structure: A policy should specify the logic (AND/OR/NOT) combining RBAC, ABAC, and ReBAC conditions.
Adapters/Data Sources:
RBAC needs a Role Provider (User -> Roles).
ABAC needs an Attribute Provider (User/Resource -> Attributes).
ReBAC needs a Relationship/Graph Provider (User -> Resource relationships).
Decision Engine: The logic that evaluates the policy against the providers.
Caching Layer: A wrapper around the engine or providers to memoize decisions or data lookups.
Audit Logger: A middleware or side-effect that records the decision and the reasons.
Language Choice: TypeScript is usually the best for this type of system design example because it handles interfaces, types, and asynchronous data fetching cleanly, and is widely understood by engineers building backend systems. Python is a close second. I'll stick with TypeScript for the type safety which helps illustrate the "composable" nature.
The Engine: The AuthorizationEngine class. It takes providers and evaluates policies.
Caching: Implement a CachedAuthEngine wrapper or simple memoization decorator.
Audit: Implement an AuditLogger that logs inputs and outputs.
Refining the "Composable" aspect:
Instead of hardcoding "Check RBAC", then "Check ABAC", the engine should evaluate a Policy which is a tree of conditions. This makes it truly composable.
Code Structure:
Interfaces: Base types.
Providers: Mock implementations for demonstration.
Policy Language: The JSON/Config structure for rules.
Evaluator: The recursive function walking the policy tree.
Engine: The orchestrator.
Cross-Cutting Concerns: Cache and Audit.
Drafting the Code (Mental or Scratchpad):
RBAC:user.roles.includes('admin')
ABAC:resource.status === 'published' or user.age > 18
ReBAC: Check if user is editor of resource (Tuple: user, relation, resource).
Evaluator Logic:evaluate(condition):
if condition is Role -> check RoleProvider
if condition is Attr -> check AttributeProvider -> compare
if condition is Relation -> check RelationProvider
if condition is All/Any -> recurse
Caching:
We can cache the decision based on a hash of (User, Action, Resource, Context). Or cache the data (Roles, Attributes).
Decision: Cache the final boolean result. Key = ${userId}:${action}:${resourceId}:${hash(context)}. This is safer and easier to demonstrate.
Audit:
Just a hook onDecision.
Let's write the TypeScript code.
Self-Correction during thought process:
Initial thought: Just make functions checkRBAC, checkABAC.
Correction: That's not composable. A composable engine allows policies like "Role is Editor AND Resource is not Classified". I need a Policy Definition Language (PDL) structure.
ReBAC Specifics:
ReBAC usually requires a specific check: Check(user, relation, resource). The engine needs to support passing the resource object to the ReBAC provider to see if a relationship exists.
Final Polish:
I will create a modular system.
types.ts: Core definitions.
providers.ts: Abstractions for data fetching.
policy.ts: The logic structure.
engine.ts: The evaluator.
decorators.ts: Cache and Audit wrappers.
This structure demonstrates "Composition" in two ways:
Logic Composition: Policies combine RBAC/ABAC/ReBAC via boolean logic (AND/OR).
Structural Composition: The engine is composed of providers and wrapped by decorators (Middleware pattern).
Let's write it.
To build a truly composable Authorization (AuthZ) engine, we should move beyond monolithic if/else logic. We need an engine that treats RBAC, ABAC, and ReBAC as plug-and-play "sources of truth" and pipes the final decision through caching and auditing layers.
Below is a complete, TypeScript implementation of a composable AuthZ engine.
Architecture Design
Policy Language: A JSON structure allowing boolean logic (AND/OR/NOT) to combine Role, Attribute, and Relationship checks.
Providers: Interfaces for fetching data (Roles, Attributes, Relations).
Resolvers: The logic that translates Policy requests into Provider calls.
Pipeline: The engine orchestrates the flow: Request -> Cache -> Policy Evaluation -> Audit -> Response.
The Implementation
typescript
Example Usage
Here is how you would implement the providers and compose a complex policy (e.g., "A user can edit a document if they are an Admin OR if they are the Owner AND the document is not archived").
typescript
// ==========================================================
// 4. Mock Implementations (In-Memory for Demo)
// ==========================================================
class MockRoleProvider implements IRoleProvider {
private roles: Record<string, string[]> = {
'u1': ['editor'],
'u2': ['admin']
};
async getRoles(user: User): Promise<string[]> {
return this.roles[user.id] || [];
}
}
class MockAttributeProvider implements IAttributeProvider {
async getUserAttribute(user: User, key: string) {
return user[key]; // e.g. user.department
}
async getResourceAttribute(resource: Resource, key: string) {
return resource[key]; // e.g. resource.status
}
}
class MockRelationProvider implements IRelationProvider {
async checkRelation(user: User, relation: string, resource: Resource): Promise<boolean> {
// Simulate ReBAC graph lookup: Is User the 'owner' of Resource?
if (relation === 'owner') {
return resource.ownerId === user.id;
}
return false;
}
}
// ==========================================================
// 5. Running the Engine
// ==========================================================
(async () => {
// Setup
const engine = new AuthzEngine({
roleProvider: new MockRoleProvider(),
attrProvider: new MockAttributeProvider(),
relProvider: new MockRelationProvider(),
cache: new Map(),
auditLog: (entry) => console.log(`[AUDIT] ${entry.user.id} -> ${entry.action}: ${entry.decision} (${entry.reason})`)
});
// Define Policy:
// Allowed if (Role is ADMIN) OR (Relation is OWNER AND Resource Status is ACTIVE)
const editPolicy: Policy = {
id: 'doc-edit-v1',
condition: {
type: 'or',
conditions: [
{ type: 'hasRole', role: 'admin' },
{
type: 'and',
conditions: [
{ type: 'hasRelation', relation: 'owner' },
{ type: 'hasAttribute', key: 'resource.status', operator: 'eq', value: 'active' }
]
}
]
}
};
// Scenario 1: Admin User (u2) trying to edit an archived document
const adminUser = { id: 'u2', name: 'Alice' };
const archivedDoc = { type: 'document', id: 'd1', status: 'archived', ownerId: 'u1' };
const result1 = await engine.check(adminUser, 'edit', archivedDoc, editPolicy);
console.log(`Admin Edit Archived: ${result1.allowed}`); // True (Bypasses ABAC/ReBAC due to RBAC)
// Scenario 2: Owner User (u1) trying to edit their own archived document
const ownerUser = { id: 'u1', name: 'Bob' };
const result2 = await engine.check(ownerUser, 'edit', archivedDoc, editPolicy);
console.log(`Owner Edit Archived: ${result2.allowed}`); // False (Failed ABAC check: status != active)
// Scenario 3: Owner User (u1) editing active document
const activeDoc = { type: 'document', id: 'd2', status: 'active', ownerId: 'u1' };
const result3 = await engine.check(ownerUser, 'edit', activeDoc, editPolicy);
console.log(`Owner Edit Active: ${result3.allowed}`); // True
})();
Key Features of this Design
Composition via Tree Structure:
The policy is a tree of conditions. You can wrap an RBAC check inside a NOT, or put an ABAC check inside an AND with a ReBAC check. This removes the limitation of "choosing" one model. You use all of them simultaneously.
Provider Abstraction:
The AuthzEngine does not know where data comes from.
IRoleProvider could talk to Keycloak/Auth0.
IRelationProvider could talk to Postgres (for simple ownership) or a specialized Graph DB like SpiceDB (for complex ReBAC).
IAttributeProvider could fetch from your main application DB.
Audit Trail:
The auditLog callback captures every decision, how long it took (performance monitoring), and why (debugging). This is critical for compliance.
Performance Caching:
A simple Map is used, but because the key is generated based on inputs, this can easily be swapped for Redis. Note that caching AuthZ decisions can be dangerous if roles/relations change frequently; in a real production system, you would tag cache entries with a "revision" number from your Auth source to allow invalidation.