Fine-Grained Authorization Pattern

The Fine-Grained Authorization Pattern decouples who authenticated at login from what specific action that principal is allowed to perform on an exact domain resource under current tenant, organizational, relationship, and environmental constraints. Authentication (OAuth and OIDC Deep Dive) confirms identity; authorization governs every read, list, mutation, workflow approval, and export inside enterprise software.

Simple boolean role checks (if (user.role === "ADMIN")) break down rapidly in real applications: enterprise workspaces require project-level collaborators, document sharing hierarchies, department approvals, customer-support impersonation with explicit consent windows, and dollar-value spending limits. Scrambling those rules into scattered controller if branches makes audits impossible and leaves indirect Object-Level Authorization (BOLA / IDOR) holes in GraphQL resolvers, bulk-export endpoints, and background jobs. For broader context, see Authentication and Authorization Hub, API Security Patterns, and Zero Trust Architecture.


1. Choosing Between RBAC, ABAC, and ReBAC Policy Models

Modern enterprise systems rarely rely on a single authorization paradigm; they compose Policy Decision Points (PDP) and Policy Enforcement Points (PEP) across three complementary models:

graph TD
    Caller["Authenticated Request (sub, org_id, scopes)"] --> PEP["Policy Enforcement Point (Service / Gateway)"]
    PEP -->|"authorize(subject, action, resource, env)"| PDP["Centralized Policy Decision Point"]
    PDP --> RBAC["Role Catalog (Org Admin, Billing Editor)"]
    PDP --> ABAC["Contextual Attributes (amount, geo, clearance)"]
    PDP --> ReBAC["Relationship Graph (Folder -> Document -> Viewer)"]
    PDP -->|"Allow / Deny + Reason + Obligations"| PEP
    PEP -->|"Record Allow/Deny Event"| Audit["Audit Trail Sink"]

    click Caller "/wiki/OauthAndOidcDeepDive" "OAuth and OIDC Deep Dive"
    click PEP "/wiki/ApiSecurityPatterns" "API Security Patterns"
    click Audit "/wiki/SecurityLoggingAndAuditTrails" "Security Logging and Audit Trails"
ModelCore AbstractionStrengthsWeaknesses at ScaleCanonical Enterprise Examples
RBAC (Role-Based)Principal -> Role -> Permission[]Simple mental model, fast JWT claim lookup, easy SOC 2 role reviewsRole explosion (project_42_finance_reviewer) when permissions depend on specific recordsOrganization admin, billing manager, read-only auditor
ABAC (Attribute-Based)Rule(subject.*, action, resource.*, env.*)Handles dynamic predicates (amount <= limit, business hours, IP range, MFA age)Harder to answer "who can access document X?" without scanning all policiesApprove purchase orders under $25,000; export PII only from corporate VPN
ReBAC (Relationship-Based, Zanzibar)Tuple graph (object, relation, subject)Expresses nested folders, teams, ownership, and delegated inheritance cleanly; supports reverse index queriesRequires synchronization pipeline (outbox/CDC) to keep relation tuples fresh; graph cycle limitsGoogle Drive folder sharing, GitHub repo teams, multi-workspace SaaS

In practice, most B2B SaaS platforms pair RBAC for coarse tenant roles, ReBAC tuples (or scoped SQL join tables) for object hierarchies, and ABAC predicates for workflow thresholds and compliance obligations.


2. Authorization Latency, Caching, and Staleness Budgets

Because every API endpoint invokes authorize(...)—often multiple times when filtering list views—authorization checks sit directly on the p99 critical path. Evaluating a ReBAC graph over network RPC for every item in a 100-row table creates catastrophic fan-out unless you bound evaluation cost and staleness explicitly.

Suppose an enterprise workspace handles \lambda = 3{,}000\text{ req/s} peak read traffic, and each list page displays M = 25 entities:

Quantify the cache trade-off cleanly. Let h be the authorization cache hit ratio, L_{\text{cache}} = 0.6\text{ ms} be local/Redis lookup latency, and L_{\text{pdp}} = 6.5\text{ ms} be full graph/DB evaluation latency:

L_{\text{auth}} = h \cdot L_{\text{cache}} + (1 - h) \cdot L_{\text{pdp}}

At h = 0.94, average authorization overhead drops to:

L_{\text{auth}} = 0.94(0.6) + 0.06(6.5) = 0.564 + 0.390 = 0.954\text{ ms}

To guarantee bounded revocation lag T_{\text{revoke}} while keeping h > 0.90:


3. Fail-Closed Enforcement Point and Policy Engine Structure

Never bake authorization assumptions into UI button visibility alone, and never rely on an API gateway JWT check for record-level ownership. Enforce decisions inside a dedicated Authorization Guard invoked inside the service/application slice (Vertical Slice Architecture) before any state mutation or sensitive read, paired with an immutable audit event (Security Logging and Audit Trails).

// Centralized PEP + Deterministic Policy Evaluator (RBAC + ABAC + Relationship Hook)
export type Action =
  | "invoice:read"
  | "invoice:create"
  | "invoice:approve"
  | "invoice:export_pii";

export interface AuthSubject {
  readonly userId: string;
  readonly tenantId: string;
  readonly roles: ReadonlySet<string>;
  readonly departmentIds: ReadonlySet<string>;
  readonly mfaVerifiedAtEpochSec: number;
  readonly approvalLimitCents: number;
}

export interface InvoiceResource {
  readonly id: string;
  readonly tenantId: string;
  readonly ownerUserId: string;
  readonly departmentId: string;
  readonly amountCents: number;
  readonly status: "DRAFT" | "PENDING_APPROVAL" | "APPROVED";
}

export interface AuthContext {
  readonly nowEpochSec: number;
  readonly requestIpTrusted: boolean;
}

export interface AuthDecision {
  readonly allowed: boolean;
  readonly reasonCode: string;
  readonly requiredObligation?: "STEP_UP_MFA" | "DUAL_APPROVAL";
}

export function evaluateInvoicePolicy(
  subject: AuthSubject,
  action: Action,
  resource: InvoiceResource,
  ctx: AuthContext
): AuthDecision {
  // 1. Invariant tenant boundary: fail closed even for platform roles unless explicit break-glass
  if (subject.tenantId !== resource.tenantId) {
    return { allowed: false, reasonCode: "TENANT_MISMATCH" };
  }

  // 2. Explicit Deny / Separation-of-Duties (SoD): creator cannot self-approve
  if (action === "invoice:approve" && resource.ownerUserId === subject.userId) {
    return { allowed: false, reasonCode: "SOD_SELF_APPROVAL_FORBIDDEN" };
  }

  switch (action) {
    case "invoice:read": {
      if (
        subject.roles.has("ORG_ADMIN") ||
        subject.roles.has("FINANCE_AUDITOR") ||
        resource.ownerUserId === subject.userId ||
        subject.departmentIds.has(resource.departmentId)
      ) {
        return { allowed: true, reasonCode: "ROLE_OR_DEPT_SCOPE" };
      }
      return { allowed: false, reasonCode: "NO_READ_RELATION" };
    }

    case "invoice:approve": {
      if (!subject.roles.has("FINANCE_APPROVER") && !subject.roles.has("ORG_ADMIN")) {
        return { allowed: false, reasonCode: "MISSING_APPROVER_ROLE" };
      }
      if (resource.status !== "PENDING_APPROVAL") {
        return { allowed: false, reasonCode: "INVALID_STATE_FOR_APPROVAL" };
      }
      // ABAC spending ceiling + step-up MFA freshness (< 15 minutes for >= $10,000)
      if (resource.amountCents > subject.approvalLimitCents) {
        return {
          allowed: false,
          reasonCode: "EXCEEDS_APPROVAL_LIMIT",
          requiredObligation: "DUAL_APPROVAL",
        };
      }
      const mfaAgeSec = ctx.nowEpochSec - subject.mfaVerifiedAtEpochSec;
      if (resource.amountCents >= 1_000_000 && mfaAgeSec > 900) {
        return {
          allowed: false,
          reasonCode: "MFA_STEP_UP_REQUIRED",
          requiredObligation: "STEP_UP_MFA",
        };
      }
      return { allowed: true, reasonCode: "APPROVED_WITHIN_LIMIT" };
    }

    case "invoice:export_pii": {
      if (!subject.roles.has("COMPLIANCE_OFFICER") || !ctx.requestIpTrusted) {
        return { allowed: false, reasonCode: "PII_EXPORT_RESTRICTED" };
      }
      return { allowed: true, reasonCode: "COMPLIANCE_EXPORT_GRANTED" };
    }

    default:
      // Exhaustive default fail-closed guarantee
      return { allowed: false, reasonCode: "DEFAULT_DENY" };
  }
}

Handling UI Capability Hints Without Duplicating Policy Logic

Frontend views (Single-Page Application Architecture, Backend-for-Frontend Pattern) legitimately need to know whether to render an Approve button or disable an Export icon. Never re-implement evaluateInvoicePolicy in React components! Instead, let the BFF or resource endpoint return server-computed UI capability flags (such as _capabilities: { canApprove: false, approveBlockedReason: "MFA_STEP_UP_REQUIRED" }), while always re-evaluating the authoritative policy on the POST /approve mutation itself.


4. Production Failure Modes and Security Regressions

  1. Confusing 404 vs. 403 leakage on existence probes: Returning 403 Forbidden when Tenant B guesses Tenant A's UUID vs. 404 Not Found when the UUID does not exist acts as an existence oracle (BOLA/IDOR enumeration). For cross-tenant or private unshared objects where the caller lacks read permission, return uniform 404 Not Found (matching Multi-Tenant Isolation Pattern RLS behavior); return 403 Forbidden only when the caller clearly belongs to the workspace and owns read visibility, so explaining the missing action or obligation (MFA_STEP_UP_REQUIRED) is helpful rather than leaky.
  2. Broken list/search/aggregate filtering (authorization bypass via endpoints): Developers diligently protect GET /invoices/:id but leave GET /invoices/search, POST /reports/csv, or GraphQL nested edges checking only isAuthenticated(). Every query path, background export, and AI RAG retrieval endpoint must enforce the same authorization filter or ReBAC LookupResources set.
  3. Stale JWT claims after demotion or team removal: Stuffing mutable permissions and 40 project IDs into a 1-hour JWT means removing a terminated employee's role does nothing until token expiration. Keep JWTs minimal (sub, org_id, session_id, coarse scopes) and load live role/tuple state from a short-TTL revocable session or policy cache.
  4. Conflicting "Deny" vs. "Allow" precedence errors: Ad-hoc policy lists often evaluate allow first and return early, silently ignoring explicit Separation-of-Duties (SoD) or account-suspension denies. Always evaluate explicit denies (TENANT_MISMATCH, SUSPENDED, SOD_*) strictly before any allow rules, and default to deny.

5. Agent Implementation & Output Contract

When an automated coding agent implements protected APIs, workflows, or enterprise admin features using this pattern, enforce these deliverables and verification checks:

Required Policy Architecture

  1. Single authoritative PEP interface: Route every protected command and query through a single authorizeOrThrow(subject, action, resourceRef, ctx) boundary rather than inline if (user.role === ...) checks inside controllers or SQL repositories.
  2. Explicit policy table in the PR/module: Enumerate every (action, role/relation, ABAC predicate, SoD rule, cache freshness) rule in one centralized policy module (policies/<domain>.policy.ts or Rego/Cedar bundle).
  3. Audit parity: Emit a structured security event on both privileged allows (exports, approvals, role grants) and all denies containing actorId, tenantId, action, resourceId, decision, reasonCode, and traceId (Security Logging and Audit Trails).

Mandatory Verification Test Matrix to Generate

Every feature with protected operations must ship an automated table-driven policy test suite covering:

  1. Default-deny fallback: Unknown action or unmapped role yields allowed: false.
  2. Cross-tenant denial: Even ORG_ADMIN of Tenant A gets allowed: false (TENANT_MISMATCH) against Tenant B's resource.
  3. Separation-of-Duties & ABAC boundary: Creator attempting self-approval fails (SOD_SELF_APPROVAL_FORBIDDEN), and approval \ge limit triggers DUAL_APPROVAL / STEP_UP_MFA obligations.
  4. End-to-end route enforcement: HTTP integration tests confirming unauthenticated requests return 401, authorized reads return 200, and unauthorized mutations return 403/404 while leaving database state untouched.