Authorization patterns

From FerroxLabs/murage · View interactive version

Authorization patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level authorization patterns implementation: security and design-patterns decision frameworks, production-ready patterns, and concrete templates for authorization patterns workflows. Use when the user asks about authorization patterns, authorization patterns configuration, or security

How to use this skill

Skill file

Authorization Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Identify the Authorization Model Required

Start by gathering the access control requirements precisely. The model you choose has deep structural implications and is very hard to change later.

Quantitative thresholds:

2. Design the Permission Model

Once the model is chosen, define its constituent parts explicitly before writing any code.

3. Choose the Enforcement Architecture

Where and how authorization checks run has major performance and correctness implications.

4. Design Token Claims and Context Propagation

Authorization decisions depend on context. Decide what lives in the token vs. what is fetched at decision time.

5. Implement the Policy Enforcement Points (PEPs)

The PEP is the code that halts request processing and asks "is this allowed?" Write PEPs as middleware, not inline business logic.

6. Implement the Policy Decision Logic

Write the actual policy rules using the chosen model's primitives.

For RBAC with a permission table (SQL example):

-- Three-table RBAC schema
CREATE TABLE roles (id UUID PRIMARY KEY, name TEXT UNIQUE, tenant_id UUID);
CREATE TABLE role_permissions (role_id UUID, permission TEXT, PRIMARY KEY (role_id, permission));
CREATE TABLE user_roles (user_id UUID, role_id UUID, tenant_id UUID, PRIMARY KEY (user_id, role_id));

-- Authorization query: does user X have permission Y on tenant Z?
SELECT EXISTS (
  SELECT 1
  FROM user_roles ur
  JOIN role_permissions rp ON ur.role_id = rp.role_id
  WHERE ur.user_id = $1
    AND ur.tenant_id = $2
    AND rp.permission = $3
);

For ABAC with OPA/Rego:

package authz

default allow = false

allow {
  input.action == "document:read"
  user_is_member_of_org[input.resource.org_id]
  not document_is_archived
}

user_is_member_of_org[org_id] {
  data.memberships[input.principal.id][org_id]
}

document_is_archived {
  data.documents[input.resource.id].status == "archived"
}

For ReBAC with SpiceDB (Zanzibar-inspired):

Define a schema that expresses relations:

definition user {}
definition organization {
  relation member: user
  relation admin: user
  permission manage = admin
}
definition document {
  relation owner: user
  relation org: organization
  permission read = owner + org->member
  permission write = owner + org->admin
}

Then call CheckPermission(user:alice, read, document:123) which traverses the relationship graph.

7. Handle Authorization in List and Search Endpoints

The hardest part of authorization is not single-resource checks -- it is filtering collections efficiently.

8. Test and Audit the Authorization System

Authorization bugs are often silent -- the system returns 200 OK when it should return 403.


Output Format

When responding to a user authorization design question, produce the following structured output:

## Authorization Design -- [System Name]

### Model Selection
| Criterion                        | Assessment                      |
|----------------------------------|---------------------------------|
| Number of roles                  | [count]                         |
| Attribute conditions required    | [yes/no -- describe]            |
| Relationship graph traversal     | [yes/no -- describe depth]      |
| Multi-tenant isolation           | [yes/no]                        |
| Policy ownership (dev vs. ops)   | [who authors policies]          |
| **Recommended Model**            | **[RBAC / ABAC / ReBAC / PBAC]**|

### Permission Matrix
| Resource Type     | create | read | update | delete | list | admin |
|-------------------|--------|------|--------|--------|------|-------|
| [resource_type_1] | [roles]| [roles]| [roles]| [roles]| [roles]| [roles]|
| [resource_type_2] | ...    | ...  | ...    | ...    | ...  | ...   |

### Enforcement Architecture
- **Gateway layer:** [scope/token validation only -- yes/no, what checks]
- **Service layer:** [resource-level PEP -- middleware name/location]
- **PDP:** [inline / sidecar / centralized -- tool name]
- **Cache strategy:** [TTL, cache key, invalidation trigger]

### Token Claims Design

{

"sub": "user_id",

"tid": "tenant_id",

"roles": ["role_name"],

"scope": "api:access",

"iat": 1700000000,

"exp": 1700003600

}


### Core Policy Implementation
[Code block: SQL schema, Rego policy, or SpiceDB schema as appropriate]

### Enforcement Point Code
[Code block: middleware or decorator implementation in the user's language]

### List Endpoint Strategy
[Description of query rewriting or lookup approach for collection filtering]

### Testing Checklist
- [ ] Permission matrix tests (all role × action combinations)
- [ ] Cross-tenant isolation tests
- [ ] Deactivated principal tests
- [ ] Privilege escalation tests
- [ ] Policy version logging verified
- [ ] Authorization audit log format confirmed

### Known Trade-offs and Risks
[Specific risks for the chosen approach and mitigations]

Rules

  1. NEVER scatter if user.role == X checks directly in business logic. All authorization decisions must pass through a single authorize(principal, resource, action) boundary. Business logic that contains role checks cannot be tested in isolation and creates authorization drift.
  1. NEVER trust the tenant ID from the request body or URL parameters alone. Always verify the resource's actual tenant_id (fetched from the database) matches the tid claim in the authenticated token. Skipping this check is the #1 cause of cross-tenant data leakage in multi-tenant SaaS.
  1. NEVER embed dynamic permission lists in JWT tokens. Tokens cannot be invalidated mid-flight. If a user's permissions change (role revoked, account suspended), a token with embedded permission claims will continue to grant access until expiry. Put the user ID and roles in the token; look up fine-grained permissions at decision time from a fast store.
  1. ALWAYS return 403 Forbidden, not 404 Not Found, when a resource exists but the caller lacks permission -- unless the existence of the resource is itself sensitive (e.g., a private user profile). Document any intentional 404-for-auth responses in the API contract. Using 404 silently hides resources from unauthorized users but misleads authorized users who mistype an ID.
  1. NEVER evaluate authorization after the data has already been returned. The pattern fetch_resource() → check_permission() → return or error is wrong because the database round-trip has already occurred. The correct pattern is check_permission() → fetch_resource() → return or use query-level filtering so unauthorized records are never loaded.
  1. ALWAYS log the policy version, not just the decision. Authorization audit logs must contain: timestamp, principal_id, resource_id, action, decision (allow/deny), policy_version, decision_latency_ms. Without the policy version, you cannot reproduce a historical authorization decision during an audit.
  1. NEVER use RBAC with more than 50 roles. Above ~50 roles, the cognitive overhead of role management exceeds the overhead of a simple ABAC policy. Role explosion is a failure mode, not a feature. If you're approaching 50 roles, refactor to ABAC with attribute conditions.
  1. ALWAYS cache authorization decisions with a bounded TTL. For a centralized PDP, uncached decision latency (5-50ms) will compound across microservice call chains. Use Redis with a 30-60 second TTL keyed on (principal_id, resource_id, action). Invalidate immediately on role change events via a pub/sub channel.
  1. NEVER conflate service-to-service authorization with user authorization. Internal service calls use mTLS certificates or signed service tokens (not user JWTs). Define a separate principal type for services with its own permission set. A user JWT presented by a compromised internal service should not grant elevated access.
  1. ALWAYS write authorization denial reasons to server-side logs, but return only generic denial messages to clients. The client receives {"error": "forbidden"}. The server log records denied: user lacks document:write on document_id=X (user has roles: [viewer], required: [editor, admin]). Returning detailed denial reasons to clients enables permission enumeration attacks.

Edge Cases

Permission Cache Stale After Role Revocation

When an administrator revokes a user's role (e.g., offboarding, security incident), the user's cached authorization decisions remain valid until TTL expiry -- potentially 30-60 seconds with standard caching. For high-security events (account termination, suspected compromise), implement an emergency revocation path: push the user ID to a Redis blocklist set with TTL equal to the maximum token lifetime. Every authorization middleware checks this blocklist before the permission cache. This blocklist check must be fast (a single Redis GET) and must not be skippable.

Multi-Tenant Policy Isolation with ABAC

When multiple tenants can author their own policies (policy-as-configuration for enterprise customers), policy namespacing is critical. Each tenant's policies must execute in a sandboxed context with access only to their own data slice. In OPA, use bundle namespacing: tenant-specific policies live under data.tenants.{tenant_id}.authz and cannot reference data.tenants.{other_id}. Validate all tenant-authored policies against a meta-policy (policy about what policies are allowed to do) before activation. Reject any tenant policy that uses http.send, file I/O, or references cross-tenant data paths.

Hierarchical Resource Permissions (Inheritance)

When a user has project:admin permission, do they automatically have document:admin for all documents in that project? This is permission inheritance, and it must be made explicit rather than assumed. Define inheritance rules in the policy: allow document:write if allow project:admin on document.project_id. In ReBAC schemas, this is expressed as a parent relation: permission write = owner + project->admin. The risk: unintuitive permission grants where a user doesn't realize their project role grants document access. Always document the full effective permission set (including inherited permissions) in the permission matrix and expose it via a /permissions/explain debug endpoint for development environments.

Wildcard Permissions and Admin Roles

Super-admin roles that grant *:* (all permissions on all resources) are necessary but dangerous. Implement the following safeguards: (1) Require a second factor or re-authentication to activate super-admin mode (similar to sudo). (2) Log every action taken under a wildcard permission with elevated verbosity. (3) Scope super-admin to specific resource trees where possible (organization:* rather than *:*). (4) Never issue long-lived tokens for super-admin sessions -- force re-authentication after 1 hour of inactivity. (5) Require two-person authorization for destructive actions even with super-admin privilege (four-eyes principle).

Authorization in Async/Event-Driven Systems

In event-driven architectures, a message on a queue may be processed long after the originating user's token has expired. The common mistake is to re-use the original JWT for authorization at processing time. The correct pattern is: at publish time, resolve and record the authorization decision alongside the message payload ({"action": "document.export", "principal_id": "user_123", "authorized_at": "2024-01-15T10:00:00Z", "policy_version": "v2.3.1"}). The consumer trusts the pre-authorized decision if the event is processed within an acceptable window (e.g., 5 minutes). For long-running async jobs, re-evaluate authorization at key checkpoints using the principal's current permissions fetched from the permission store -- not the original token.

GraphQL and Field-Level Authorization

REST authorization maps cleanly to HTTP method + resource path. GraphQL requires field-level authorization because a single query can request fields with different sensitivity levels. Implement field-level resolvers that each call authorize(principal, parent_resource, field_action). Use a schema directive approach (@auth(requires: "document:read_sensitive")) to declare authorization requirements at the schema level, enforced by a server-side directive handler. Never return a field as null silently when the caller lacks permission -- either throw a field-level error with code FORBIDDEN or use a permission-aware type that excludes the field from the schema response for unauthorized callers. Mixing these behaviors in the same API without documentation is a source of client confusion and silent data leakage.

Database-Level vs. Application-Level Authorization

Row Level Security (RLS) in PostgreSQL is a powerful defense-in-depth tool, but it is not a substitute for application-level authorization. RLS operates at the database connection level using session variables (SET LOCAL app.current_user_id = $1). The risk: if your application uses a connection pool (PgBouncer in transaction mode), session variables may not be reliably set per-transaction. Use RLS as a secondary layer that catches bugs in the application layer, not as the primary enforcement mechanism. The application layer RBAC/ABAC check always runs first. RLS runs as a safety net. Test that RLS actually blocks unauthorized access by writing integration tests that bypass the application layer and query the database directly with different session variables.

Authorization for Machine-to-Machine (M2M) APIs

Service accounts and API keys require their own authorization model. Mistakes include: issuing API keys that have the same permission set as human admin users (scope them narrowly to specific operations), not expiring API keys (enforce a maximum lifetime of 1 year with 90-day rotation reminders), and not recording which service generated a key (always store created_by, purpose, and last_used_at on every key). For M2M, use OAuth2 client credentials flow to issue scoped access tokens rather than static API keys where possible. Define a separate service_account principal type with its own roles that cannot overlap with human user roles. Service accounts should never have user:impersonate or admin:manage_users permissions.


Example

Input: "We're building a multi-tenant document management SaaS. We have Organizations, Projects inside organizations, and Documents inside projects. Users can be members of an organization with roles of Admin, Editor, or Viewer. We're using Node.js with PostgreSQL and need to figure out the right authorization approach. We'll have roughly 100 tenants at launch with ~500 users."

Output:

Authorization Design -- Document Management SaaS

Model Selection

| Criterion | Assessment |

|----------------------------------|----------------------------------------------------------------|

| Number of roles | 3 per tenant (Admin, Editor, Viewer) -- stable and bounded |

| Attribute conditions required | Minimal -- ownership check for delete, active membership check |

| Relationship graph traversal | Shallow -- 3 levels max (org → project → document) |

| Multi-tenant isolation | Yes -- strict tenant boundary required |

| Policy ownership | Development team authors policies; tenant admins assign roles |

| Recommended Model | RBAC with hierarchical resource scoping |

At 3 roles and 3 resource levels, full ABAC is unnecessary overhead. The hierarchical inheritance (org admin implies project admin) is expressible as explicit policy rules in RBAC, not requiring a full ReBAC graph engine. SpiceDB or OPA would be correct at 10x this complexity; for this scope, a well-structured PostgreSQL permission schema plus a clean middleware layer is the right choice.


Permission Matrix

| Resource | create | read | update | delete | list | manage_members |

|--------------|-------------|---------------------|---------------------|---------------------|----------------------------|----------------------|

| Organization | (system) | Admin/Editor/Viewer | Admin | (system) | Admin/Editor/Viewer | Admin |

| Project | Admin | Admin/Editor/Viewer | Admin/Editor | Admin | Admin/Editor/Viewer | Admin |

| Document | Admin/Editor| Admin/Editor/Viewer | Admin/Editor | Admin/Editor (own)* | Admin/Editor/Viewer | N/A |

*An Editor can delete only documents they created. An Admin can delete any document in the project.


Database Schema

-- Tenants
CREATE TABLE organizations (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name        TEXT NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Projects belong to organizations
CREATE TABLE projects (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
  name            TEXT NOT NULL
);

-- Documents belong to projects
CREATE TABLE documents (
  id           UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  project_id   UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
  created_by   UUID NOT NULL REFERENCES users(id),
  title        TEXT NOT NULL,
  status       TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'archived'))
);

-- Roles scoped to an organization (RBAC)
CREATE TYPE org_role AS ENUM ('admin', 'editor', 'viewer');

CREATE TABLE organization_members (
  user_id         UUID NOT NULL REFERENCES users(id),
  organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
  role            org_role NOT NULL,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, organization_id)
);

-- Index for fast membership lookup
CREATE INDEX idx_org_members_user ON organization_members(user_id, organization_id);

Token Claims Design

{
  "sub": "usr_01HB5X2KJPQ3R4",
  "tid": "org_01HA3N7MKQP1T2",
  "email": "alice@acme.com",
  "roles": ["editor"],
  "scope": "api:access",
  "iat": 1700000000,
  "exp": 1700003600
}

The tid claim identifies the tenant. The roles array contains the user's role within that tenant. Fine-grained per-resource ownership is not embedded in the token -- it is evaluated at request time using the documents.created_by column.


Enforcement Architecture


Authorization Middleware (Node.js/Express)

// middleware/authorize.js
const { getUserOrgRole } = require('../services/authorizationService');
const { authCache } = require('../services/authCache');
const { createAuditLog } = require('../services/auditLog');

/**
 * Middleware factory: authorize(requiredPermission, options)
 * requiredPermission: e.g., 'project:create', 'document:read'
 * options.getOrgId: function(req) => orgId -- how to extract org from request
 */
function authorize(requiredPermission, options = {}) {
  return async (req, res, next) => {
    const principal = req.user; // set by JWT validation middleware upstream
    const orgId = options.getOrgId
      ? options.getOrgId(req)
      : req.params.orgId || req.body.organizationId;

    if (!orgId) {
      return res.status(400).json({ error: 'Organization context required' });
    }

    // Verify the org ID from the request matches the JWT tenant claim
    if (principal.tid !== orgId) {
      createAuditLog({
        principalId: principal.sub,
        resourceType: 'organization',
        resourceId: orgId,
        action: requiredPermission,
        decision: 'deny',
        reason: 'tenant_mismatch',
        policyVersion: '1.0.0',
      });
      return res.status(403).json({ error: 'forbidden' });
    }

    const cacheKey = `${principal.sub}:${orgId}:${requiredPermission}`;
    let allowed = authCache.get(cacheKey);

    if (allowed === undefined) {
      const role = await getUserOrgRole(principal.sub, orgId);
      allowed = roleHasPermission(role, requiredPermission);
      authCache.set(cacheKey, allowed, 45); // 45-second TTL
    }

    createAuditLog({
      principalId: principal.sub,
      resourceType: requiredPermission.split(':')[0],
      resourceId: orgId,
      action: requiredPermission,
      decision: allowed ? 'allow' : 'deny',
      policyVersion: '1.0.0',
    });

    if (!allowed) {
      return res.status(403).json({ error: 'forbidden' });
    }

    next();
  };
}

// Role-permission mapping -- single source of truth
const ROLE_PERMISSIONS = {
  admin: [
    'organization:read', 'organization:update', 'organization:manage_members',
    'project:create', 'project:read', 'project:update', 'project:delete', 'project:list',
    'document:create', 'document:read', 'document:update', 'document:delete', 'document:list',
  ],
  editor: [
    'organization:read',
    'project:read', 'project:update', 'project:list',
    'document:create', 'document:read', 'document:update', 'document:list',
  ],
  viewer: [
    'organization:read',
    'project:read', 'project:list',
    'document:read', 'document:list',
  ],
};

function roleHasPermission(role, permission) {
  if (!role) return false;
  return ROLE_PERMISSIONS[role]?.includes(permission) ?? false;
}

module.exports = { authorize, roleHasPermission };

Ownership Check for Editor Delete (Route Handler Pattern)

// routes/documents.js
router.delete('/:orgId/projects/:projectId/documents/:documentId',
  authenticate,
  authorize('document:delete', { getOrgId: req => req.params.orgId }),
  async (req, res) => {
    const { documentId } = req.params;
    const principal = req.user;

    // Fetch the document to verify it belongs to this project/org (prevents IDOR)
    const document = await db.query(
      `SELECT d.id, d.created_by, p.organization_id
       FROM documents d
       JOIN projects p ON d.project_id = p.id
       WHERE d.id = $1 AND d.project_id = $2 AND p.organization_id = $3`,
      [documentId, req.params.projectId, req.params.orgId]
    );

    if (!document.rows[0]) {
      // Use 404 here because the document genuinely doesn't exist in this context
      return res.status(404).json({ error: 'document not found' });
    }

    const isOwner = document.rows[0].created_by === principal.sub;
    const isAdmin = principal.roles.includes('admin');

    // Editors can only delete their own documents
    if (!isAdmin && !isOwner) {
      return res.status(403).json({ error: 'forbidden' });
    }

    await db.query('DELETE FROM documents WHERE id = $1', [documentId]);
    res.status(204).send();
  }
);

List Endpoint with Authorization-Aware Query

// Fetch documents the user is allowed to see -- never fetch all then filter
async function listDocuments(userId, orgId, projectId) {
  // Authorization is enforced at the join level -- no post-fetch filtering
  const result = await db.query(
    `SELECT d.id, d.title, d.status, d.created_by, d.created_at
     FROM documents d
     JOIN projects p ON d.project_id = p.id
     JOIN organization_members om
       ON om.organization_id = p.organization_id
      AND om.user_id = $1
     WHERE d.project_id = $2
       AND p.organization_id = $3
       AND om.role IN ('admin', 'editor', 'viewer')
       AND d.status = 'active'
     ORDER BY d.created_at DESC
     LIMIT 100`,
    [userId, projectId, orgId]
  );
  return result.rows;
}

The organization_members join ensures only users who are members of the organization receive results. The query never loads unauthorized documents into application memory.


Testing Checklist

Permission matrix tests:
[ ] admin can create/read/update/delete/list documents
[ ] editor can create/read/update/list documents
[ ] editor cannot delete another editor's document
[ ] editor can delete their own document
[ ] viewer can only read and list documents
[ ] viewer receives 403 on document:create
[ ] viewer receives 403 on document:update

Cross-tenant isolation tests:
[ ] user in org_A cannot read documents from org_B using a valid token
[ ] user in org_A with admin role cannot manage members of org_B
[ ] forged orgId in request body is rejected (tid mismatch check)

Principal state tests:
[ ] removed organization member's subsequent request returns 403
[ ] cache invalidation fires on role change and takes effect within 45 seconds

Privilege escalation tests:
[ ] editor cannot call manage_members endpoint
[ ] viewer cannot elevate to editor by modifying request body role field
[ ] JWT with tampered roles claim is rejected by signature validation

Audit log tests:
[ ] every allow decision generates an audit log entry
[ ] every deny decision generates an audit log entry
[ ] audit log contains principal_id, resource_id, action, decision, policy_version

Known Trade-offs and Risks

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.