In distributed cloud-native microservices and autonomous AI Agent ecosystems, the security perimeter has fundamentally shifted from physical network topology to an identity-centric dynamic trust boundary. From initial user credential verification to machine-to-machine mutual TLS and AI agents acting autonomously on behalf of humans, Authentication (AuthN) and Authorization (AuthZ) span the entire software architecture lifecycle.
Anchored on industry standards of Defense-in-Depth and Zero Trust (Never Trust, Always Verify), this cheat sheet systematically organizes a 12-layer technical evolution architecture from core cryptographic credentials to top-tier agent governance. It provides protocol mechanics, algorithmic selection matrices, common vulnerability remediations, and engineering benchmarks as an authoritative desktop reference for backend developers, architects, and security engineers.
🔗 Related Cheat Sheets: Network Security Protocols & Defense Systems Cheat Sheet · Cryptography & Encryption Algorithms Cheat Sheet · HTTP Status Codes Cheat Sheet · AI Agent Harness Architecture Cheat Sheet · AI Agent Skills System Cheat Sheet
0. Mental Models & 12-Layer Architecture Topology
The Three Core Dimensions (Who vs What vs Who-on-behalf)
| Core Dimension | Technical Term | Core Question Answered | Primary Vehicle / Representative Spec | Typical Failures & Security Risks |
|---|---|---|---|---|
| Authentication (AuthN) | Authentication | Who are you? (Identity Verification) | Passwords, Passkey (FIDO2), TOTP, OIDC id_token |
Identity spoofing, credential stuffing, phishing, session hijacking |
| Authorization (AuthZ) | Authorization | What are you allowed to do? (Access Permission) | RBAC roles, ABAC policies, ACL, OAuth 2.0 access_token |
Broken Object Level Auth (BOLA/IDOR), Privilege Escalation (BFLA), privilege creep |
| Delegation | Delegation | Who can act on your behalf? (Acting on Behalf) | OAuth 2.0 Authorization Code, Token Exchange (RFC 8693), Capability Tokens | Unrestricted delegation abuse, impersonation fraud, lack of non-repudiation audit |
4 Abstract Tiers & 12-Layer Architecture Matrix
┌────────────────────────────────────────────────────────────────────────┐
│ Unified Observability & Continuous Security: Audit Logs | Metrics | Alerts | SIEM | Threat Response │
└────────────────────────────────────┬───────────────────────────────────┘
│
┌───────────────────────────────┐ │ ┌───────────────────────────────┐
│ L4: Machine & Agent Identity │ │ │ L4: Machine & Agent Identity │
│ Layer 10: API & Machine mTLS │ │ │ Layer 11: AI Agent Delegation │
│ Layer 12: Security Testing │ │ │ │
├───────────────────────────────┤ │ ├───────────────────────────────┤
│ L3: Authorization & Governance│ │ │ L3: Authorization & Governance│
│ Layer 08: Policy Engines (PDP)│◄───┼───►│ Layer 07: AuthZ Models (RBAC)│
│ │ │ │ Layer 09: Enterprise SSO/SCIM │
├───────────────────────────────┤ │ ├───────────────────────────────┤
│ L2: Modern Auth Protocols │ │ │ L2: Modern Auth Protocols │
│ Layer 06: MFA & Passkeys │ │ │ Layer 05: OAuth 2.0 & OIDC │
├───────────────────────────────┤ │ ├───────────────────────────────┤
│ L1: Foundation & Credentials │ │ │ L1: Foundation & Credentials │
│ Layer 02: Password Hashing │ │ │ Layer 03: Server Sessions/HTTP│
│ Layer 01: Trust & Lifecycle │ │ │ Layer 04: Tokens & JWT State │
└───────────────────────────────┘ │ └───────────────────────────────┘
▼
Users · Applications · Microservices · Autonomous AI Agents
1. Foundation & Credential Security (L1: Identity Foundation)
Layer 01: Identity & Security Foundations
Establishing identity infrastructure begins with rigorous trust models and structured lifecycle states:
- Subjects: Entities that can be identified and assigned permissions: human users (workforce / consumers), machine workloads (background daemons / microservice containers), and software agents (autonomous AI entities).
- Identity Lifecycle: Provision $\to$ Manage / Update $\to$ Suspend $\to$ Revoke / Deprovision. Gaps anywhere lead to orphaned accounts or lingering dormant privileges.
- Trust Boundaries: Never assume trust on untrusted boundaries (such as frontend clients or external API callers). Boundary crossings must enforce explicit identity verification and access evaluation.
- Principle of Least Privilege (PoLP): Entities must be granted strictly the minimal permissions necessary to perform their current task, with time decay and scope restriction.
- Defense-in-Depth: Avoid single points of failure. Internal network isolation is not enough; internal microservices must enforce strong mutual authentication and authorization.
Layer 02: Password & Credential Security
Passwords remain widely used and require modern cryptographic storage and handling:
| Password Hash Algorithm | Memory Cost | CPU/GPU Resistance | Industry Recommendation | Recommended Baseline (Production) | Use Cases & Notes |
|---|---|---|---|---|---|
| Argon2id | Very High (Tunable) | Strongest (Resists ASIC/GPU parallelism) | Modern First Choice (PHC Winner) | Memory: 64MB, Iterations: 3, Parallelism: 4 (RFC 9106) | First choice for all modern systems; balances side-channel resistance with brute-force defense |
| bcrypt | Medium (4KB) | Strong (Resists GPU via memory latency) | Industry Standard (Battle-tested) | Work factor cost=12 or 13 (approx. 200–300ms) |
Default in most legacy frameworks; truncates input at 72 bytes |
| scrypt | High (Tunable) | Strong (Excellent hardware resistance) | Good | $N=32768, r=8, p=1$ | Monitor memory consumption in resource-constrained environments to prevent OOM |
| PBKDF2 | Very Low | Weak (Vulnerable to custom GPU rigs) | Compliance / Legacy Only | With SHA-256: at least 600,000 iterations (OWASP 2023+) | Only use when strict FIPS compliance mandates it and Argon2id cannot be used |
| MD5 / SHA-256 | Zero (Nanoseconds) | Extremely Weak (Zero compute cost) | Strictly Forbidden | Cannot be salvaged by any parameter | Vulnerable to instant rainbow table attacks; strictly prohibited for password storage |
Four Golden Practices for Password Defense
- Salting & Peppering:
- Salt: Globally unique per user, generated by a cryptographically secure pseudo-random number generator (CSPRNG, $\ge 16$ bytes), stored alongside the hash in plaintext to eliminate multi-account rainbow table attacks.
- Pepper: Globally shared secret key (HMAC key), managed outside the database in KMS/HSM or environment secrets, preventing offline cracking even if database dumps are compromised.
- NIST SP 800-63B Modern Password Guidelines:
- Eliminate mandatory 90-day expiration and complex composition rules (e.g. mandatory symbols/mixed case), which induce predictable patterns.
- Enforce minimum length ($\ge 8$–12 characters) and encourage memorable passphrases.
- Screen against breached password dictionaries (e.g. Have I Been Pwned / top 100,000 common passwords).
- Rate Limiting & Credential Stuffing Defense:
- Apply sliding window rate limits (Token Bucket / Leaky Bucket) scoped by IP, device fingerprint, and account ID.
- Implement progressive exponential backoff and frictionless challenges (Cloudflare Turnstile / reCAPTCHA v3).
- Secure Account Recovery Flow:
- Issue cryptographically secure, single-use, short-lived tokens (TTL $\le 15$ minutes) stored in the database as salted hashes.
- Maintain uniform timing and messaging to eliminate user enumeration ("If an account exists for this email, a reset link has been dispatched").
Layer 03: Server-Side Sessions & Cookie Governance
Stateful web architectures rely on server-side sessions and secure cookies:
| Security Property / Mechanism | Setting / Strategy | Target Attack Vector | Engineering Implementation Standards |
|---|---|---|---|
HttpOnly |
HttpOnly=true |
XSS Cookie Theft | Prevents client-side JavaScript (document.cookie) from accessing session tokens |
Secure |
Secure=true |
MitM / Plaintext Eavesdropping | Restricts cookie transmission exclusively over encrypted HTTPS connections |
SameSite |
Strict / Lax / None |
Cross-Site Request Forgery (CSRF) | • Strict: Blocked on all cross-site requests;• Lax: Sent with top-level safe navigations (Default Recommended);• None: Requires Secure=true |
| Session ID Rotation | Rotate upon privilege change | Session Fixation | Invalidate the existing session and issue a fresh session identifier immediately upon login or permission escalation |
| CSRF Defense-in-Depth | Anti-CSRF Tokens / Double Cookie | Forged cross-site state mutations | In addition to SameSite=Lax, validate custom request headers or anti-CSRF tokens for mutating actions (POST/PUT/DELETE) |
| Timeouts & Binding | Idle + Absolute Timeout & Binding | Dormant sessions & hijacked reuse | Enforce absolute lifetimes (e.g. 12 hours) and idle timeouts (e.g. 30 minutes); verify User-Agent and subnet heuristics |
Layer 04: Tokens, JWT & Stateless Session Management
Modern distributed architectures favor stateless or hybrid token-based authentication:
JWT Structure & Common Pitfalls
JSON Web Tokens (JWT) consist of three dot-separated components: Header.Payload.Signature.
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYiLCJleHAiOjE3MDAwMDAwMDB9.iG8j2...
└───────────────┬───────────────────┘ └──────────────────┬──────────────────────┘ └────┬────┘
Header (Metadata & Algorithm) Payload (Claims Data) Signature (Verification)
- Prevent
alg: noneVulnerabilities: Verification logic must hardcode the expected signing algorithm (e.g. enforceRS256), never allowing the unverified token header'salgvalue to dictate the verification routine. - Algorithm Selection: Use
HS256(symmetric shared secret) only within single closed-perimeter systems. In microservices, distributed setups, or federated architectures, use asymmetric signing (RS256,ES256, orEd25519/EdDSA), allowing downstream services to verify claims using public keys only.
Token Storage & Architecture Trade-off Matrix
| Dimension | Opaque / Reference Token | Self-Contained JWT (By-Value) |
|---|---|---|
| Mechanism | High-entropy random string; state stored in central Redis | Signed claims string; independently verifiable without database lookup |
| Performance | Incurs one network I/O lookup to a central store per request | Zero-database lookups; verified locally via cached public keys |
| Immediate Revocation | Trivial (DEL key in Redis immediately revokes access globally) |
Complex (Valid until expiration; requires distributed blocklists) |
| Payload Size | Minimal (32–64 bytes) | Larger (typically 500B – 2KB, impacts HTTP header overhead) |
| Data Privacy | Opaque to clients; payload never leaves backend infrastructure | Base64Url encoded only; not encrypted, never store confidential secrets |
Refresh Token Rotation (RTR) & Reuse Detection Flow
sequenceDiagram
autonumber
actor Client as Client App
participant Auth as Authorization Server
participant Res as Resource Server
Client->>Auth: Authenticate (Credentials / MFA)
Auth-->>Client: Issue Short-lived Access Token (5-15m) + Long-lived Refresh Token (7-30d)
Client->>Res: Fetch data (Bearer Access Token)
Res-->>Client: Verify & Return data
Note over Client,Res: 15 minutes elapse; Access Token expires
Client->>Res: Fetch data (Expired Access Token)
Res-->>Client: 401 Unauthorized (Token Expired)
Client->>Auth: Exchange Refresh Token for fresh tokens
Note over Auth: Invalidate old Refresh Token; issue fresh pair
Auth-->>Client: Issue New Access Token + New Refresh Token
Note over Client,Auth: Anomaly Defense: If the revoked Refresh Token is re-submitted
Auth->>Auth: Detect Token Family Reuse Breach
Auth-->>Client: 400 Bad Request: Invalidate entire token family immediately & alert
2. Modern Authentication Protocols (L2: Authentication Protocols)
Layer 05: OAuth 2.0 & OpenID Connect (OIDC)
- OAuth 2.0 (RFC 6749): Governs delegated authorization ("grant an application permission to access protected resources").
- OpenID Connect (OIDC 1.0): Identity authentication layer built on top of OAuth 2.0. Standardizes identity assertions via digitally signed
id_token(JWT format) and the/userinfoendpoint to answer "who is the user?".
OAuth 2.0 Core Grant Types Comparison
| Grant Type | Client Type | Client Secret Required | Critical Security Settings | Typical Production Use Cases |
|---|---|---|---|---|
| Authorization Code + PKCE | SPAs (React/Vue), Mobile Apps, Server-Rendered Web | No for public clients (Recommended for confidential) |
Mandatory code_challenge / code_verifier (S256); mitigates code interception attacks |
Universal gold standard for all frontend and mobile applications (Fully replaces deprecated Implicit Flow) |
| Client Credentials | Backend daemons, cron jobs, CLI tooling | Yes (Strictly confidential) | Scoped strictly to service identity; enforce tight IP allowlists and granular scopes | Microservice inter-service communication, automated ETL pipelines |
| Device Authorization Code | Smart TVs, CLI tools, constrained input devices | No | Directs user to complete authentication on a secondary browser-capable device via short pairing code | CLI tools (gh auth login), streaming devices, smart appliances |
| Refresh Token | Applications requiring long-term persistent sessions | Dependent on client | Enforce Refresh Token Rotation (RTR) and token family breach invalidation | Native mobile apps avoiding frequent credential re-prompting |
| Token Exchange (RFC 8693) | Service meshes, cross-domain delegation | Dependent on trust boundary | Downscopes inbound tokens into fine-grained, target-service-specific capability tokens | Microservice pass-through calls, zero-trust delegation, AI Agent acting on behalf of users |
Layer 06: Multi-Factor Authentication (MFA), Passkeys & Passwordless
NIST and the FIDO Alliance categorize authentication factors into three classes:
- Knowledge Factor (Something you know): Passwords, PINs, security questions.
- Possession Factor (Something you have): Hardware security keys (YubiKey), mobile authenticators (TOTP apps), smartcards.
- Inherence Factor (Something you are): Fingerprint, Face ID, iris biometric scans.
MFA Mechanisms & Phishing-Resistance Matrix
| Mechanism | Factor Category | Underlying Standard | Phishing Resistance (MitM) | Implementation & Hardware Cost | Production Recommendation |
|---|---|---|---|---|---|
| Passkeys / WebAuthn | Possession + Biometric | FIDO2 / W3C WebAuthn | Phishing-Proof (Origin Bound) | Low (Leverages built-in device TPM/Secure Enclave) | Modern Gold Standard: Preferred passwordless solution; completely neutralizes adversary-in-the-middle phishing |
| Hardware Security Keys | Physical Possession | FIDO2 / CTAP2 (YubiKey) | Phishing-Proof | High (Requires dedicated physical token procurement) | Mandated for high-privilege admins, financial infrastructure, and critical cloud consoles |
| TOTP Authenticator | Dynamic Possession | RFC 6238 (Time-based HMAC) | Vulnerable (Phishing proxies can relay codes in real-time) | Very Low (Free authenticator apps) | Balanced cost-to-security default MFA for mainstream consumer web applications |
| SMS / Email OTP | Out-of-band Channel | Telephony SMS / SMTP | Extremely Weak (SIM swapping, SS7 interception, inbox compromise) | Low to Medium (SMS carrier fees) | Discouraged for high-security environments; acceptable only as fallback onboarding |
| Backup Recovery Codes | Static Knowledge/Possession | Cryptographic hashes stored at rest | Vulnerable to offline theft if mishandled | Zero | Essential safety net: Issue 8–10 single-use salted hashes during MFA setup |
Passkeys (FIDO2) Challenge-Response Flow
[Browser / Authenticator Device] [Relying Party (Auth Server)]
│ │
│─── 1. Initiate Login Request ────────────────────────►│
│◄── 2. Return Random Challenge + RP ID (Origin) ───────│
│ │
┌─────┴─────────────────────────┐ │
│ Hardware Security Enclave/TPM │ │
│ • Match Origin with RP ID │ │
│ • Prompt biometric / PIN │ │
│ • Sign challenge with private key │
└─────┬─────────────────────────┘ │
│ │
│─── 3. Submit Signature (ClientDataJSON, Signature) ──►│
│ │
│ ┌────────┴────────┐
│ │ Verify signature│
│ │ using stored │
│ │ public key │
│ └────────┬────────┘
│ │
│◄── 4. Verification successful: Issue Session / JWT ───│
3. Authorization Models & Policy Governance (L3: Authorization & Governance)
Layer 07: Authorization Models
Once identity is authenticated, the system must evaluate whether the entity has permission to perform specific actions:
| Model | Core Concept | Decision Logic | Target Application Architecture | Constraints & Bottlenecks |
|---|---|---|---|---|
| ACL (Access Control List) |
Direct mapping of users to resources | Resource -> [Users: Permissions] |
File systems, direct document ownership | Difficult to manage at scale; high operational churn on employee offboarding |
| RBAC (Role-Based Access Control) |
Permissions assigned to roles, roles assigned to users | User -> Role -> Permissions |
Enterprise ERP/CRM, SaaS tenant tiers (Admin, Viewer, Billing) | Role Explosion: Cannot easily express fine-grained dynamic constraints (e.g. "access only during working hours in branch X") |
| ABAC (Attribute-Based Access Control) |
Dynamic evaluation across subject, resource, action, and environment | f(Subject, Resource, Action, Environment) -> Allow / Deny |
Financial fraud screening, DLP systems, risk-based access | Complex policy rules; heavy computational overhead when indexing list queries |
| ReBAC (Relationship-Based Access Control) |
Graph-based reachability along relationship chains (e.g. Zanzibar) | Subject -[relation]-> Object(Parent orgs, nested teams) |
Collaborative tools (Google Docs, Notion, Figma: "Org contains Team, Team owns Doc") | Requires dedicated distributed graph storage and caching to maintain low latency |
| PBAC / CapBAC (Capability-Based Access Control) |
Cryptographically signed capability tokens grant direct access | Token acts as an unforgeable key; no central database lookup needed | Microservice edge delegation, decentralized compute, AI Agent task handoffs | Immediate token revocation and mid-stream downscoping require careful design |
Layer 08: Policy Decision & Enforcement Engines
In large-scale architectures, Policy-as-Code and Decoupled Decision/Enforcement represent the industry standard.
The Decoupled Authorization Model (XACML / NIST)
- PAP (Policy Administration Point): Where policies are authored, versioned, and distributed (e.g. GitOps repositories).
- PDP (Policy Decision Point): The engine that evaluates loaded policies against input contexts to produce an
AlloworDenyverdict. - PEP (Policy Enforcement Point): The interceptor enforcing PDP decisions (API gateways, service mesh sidecars, middleware).
- PIP (Policy Information Point): Supplies dynamic runtime attributes to the PDP (e.g. looking up resource ownership in databases or risk scores in Redis).
Modern Declarative Policy Engines Comparison
| Engine | Origin / Maintainer | Policy Language | Runtime Architecture | Core Strengths & Best Fit |
|---|---|---|---|---|
| OPA (Open Policy Agent) | CNCF Graduated | Rego (Declarative query language) | Sidecar daemon / host process / WebAssembly (WASM) | Cloud-native & Kubernetes admission standard; widespread microservice HTTP API support |
| Cedar | AWS Open Source | Cedar (Strongly typed language) | Rust-based high-performance library / WASM / CLI | Purpose-built for granular application authz; automated formal verification prevents logical contradictions |
| OpenFGA / Ory Keto | CNCF / Auth0 / Ory | Zanzibar tuple relationship definitions | Distributed service cluster backed by relational datastores | First choice for ReBAC; optimized for nested group memberships and deeply nested resource graphs |
Layer 09: Enterprise Identity & Single Sign-On (SSO)
SAML 2.0 vs OIDC for Enterprise Federation
| Dimension | SAML 2.0 (Security Assertion Markup Language) | OIDC (OpenID Connect 1.0) |
|---|---|---|
| Data Payload | Heavy XML structure containing XML-DSig digital signatures and encryption | Lightweight JSON / JWT, Base64Url encoded following JWS/JWE standards |
| Transport Binding | Heavily dependent on browser HTTP POST redirects to transmit assertions | Supports both browser redirects and direct RESTful HTTP API exchange across any client |
| Client Ecosystem | Built for legacy desktop browser web portals; cumbersome in mobile apps and SPAs | Native support across mobile apps, SPAs, microservices, and IoT devices |
| Best-Fit Scenarios | Legacy enterprise procurement, government systems, on-prem AD integrations (Okta / ADFS) | Modern SaaS platforms, public cloud infrastructure, modern cross-platform applications |
Supporting Standards & IdP Selection
- SCIM 2.0 (RFC 7643/7644): System for Cross-domain Identity Management. Standardizes RESTful APIs for IdPs (e.g. Okta, Microsoft Entra ID) to automatically provision and deprovision users in SaaS apps, preventing orphaned accounts.
- Enterprise IdP Selection Matrix:
- Keycloak: Leading open-source standard by Red Hat. Comprehensive feature set (SAML/OIDC/Kerberos/User Federation); ideal for self-hosted sovereign deployments.
- Auth0 / Okta: Leading commercial cloud IdP. Turnkey enterprise SSO integrations, compliance certifications, and global edge reliability.
- Clerk / Logto / Zitadel: Developer-first modern identity platforms designed for Next.js, React, and multi-tenant B2B SaaS.
4. Machine & AI Agent Identity (L4: Machine & Agent Identity)
Layer 10: API & Machine-to-Machine Identity (M2M)
In zero-trust microservice meshes, the assumption of network perimeter trust is discarded. Both east-west internal traffic and north-south API requests must verify machine identity:
| Mechanism | Core Implementation | Security Advantages | Production Implementation Standards |
|---|---|---|---|
| API Keys | Static high-entropy random strings with prefixes (e.g. sk-live_xxx) |
Lightweight and easy to integrate for third parties | • Never store in plaintext; store salted SHA-256 hashes; • Enforce IP allowlists and granular scopes; • Support zero-downtime dual-key rotation |
| HMAC Request Signing | Shared secret used to sign Method + URL + Timestamp + Body |
Tamper-proof; prevents eavesdropping and replay attacks | Enforce millisecond timestamps ($\le 5$ min tolerance) and cryptographic nonces |
| mTLS (Mutual TLS) | Both client and server exchange X.509 certificates to authenticate during TLS handshake | Mandatory cryptographic encryption; immune to transport tampering | Service meshes (Istio/Linkerd) automate sidecar certificate rotation transparently |
| SPIFFE / SPIRE | Universal workload identity standard: uses attestation (TPM/K8s) to issue short-lived X.509 SVIDs | Eliminates hardcoded credentials and static secrets across multi-cloud clusters | Workloads receive cryptographically verifiable SPIFFE IDs (spiffe://example.org/ns/prod/sa/order-service) |
Layer 11: AI Agent Identity, Autonomous Delegation & Guardrails
As AI Agents autonomously invoke tools, query datastores, and execute tasks across systems, traditional static human or server identity models fall short. A specialized identity framework with provenance, bounded delegation, dynamic privilege contraction, and human circuit breakers is required:
[Human User]
│ 1. Delegates high-level objective ("Book travel to SF and file expense")
▼
[AI Orchestrator Agent]
│
│─── 2. Request Token Exchange (RFC 8693) from Auth Server
│ • Passes User Access Token as Actor Token
│ • Constrains Scope: ["travel:book", "expense:create"]
│ • Enforces short TTL: 10 minutes
│
├───► [Auth Server] ──► Issues downscoped Capability Token
│
│─── 3. Invokes Travel API autonomously (Bearing Capability Token)
▼
┌────────────────────────────────────────────────────────┐
│ Agent Runtime Guardrails & Human-in-the-Loop (HITL) │
│ • Financial threshold exceeded (> $1,000) pauses task │
│ • Triggers push notification for Human Confirmation │
│ • Records tamper-proof execution audit trail (Trace ID)│
└────────────────────────────────────────────────────────┘
Core Pillars of AI Agent Governance
- Agent Identity & Cryptographic Attestation:
- Each agent possesses its own workload identity (SPIFFE ID or asymmetric keypair), recording its underlying model version, prompt template hash, and human custodian.
- Delegated Token Exchange (RFC 8693):
- When an agent acts on behalf of a human user, it executes an OAuth 2.0 Token Exchange to convert the user's broad credential into a strictly scoped, short-lived (TTL $\le 10$m) capability token, preventing prompt injection attacks from hijacking broader account permissions.
- Runtime Guardrails & Human-in-the-Loop (HITL):
- Deterministic API Allowlisting: Agents can only invoke endpoints verified against explicit OpenAPI schemas.
- Human Confirmation for High-Risk Actions: Actions crossing financial, destructive, or access thresholds pause execution pending human approval.
- Non-Repudiation Audit Trails & Emergency Kill-Switches:
- Immutable logging of prompt inputs, decision metadata, tool invocations, and response hashes.
- Immediate kill-switch mechanisms capable of revoking all active agent capability tokens globally within seconds.
5. Continuous Testing, Observability & Architecture Selection (L4 & Practices)
Layer 12: Security Testing, Auditing & Threat Monitoring
OWASP Top 10 API Security Risks & Target Defenses
| OWASP Vulnerability | Vulnerability Description | Root Cause | Production Remediation Strategy |
|---|---|---|---|
| BOLA / IDOR (API1:2023) |
Broken Object Level Authorization (Insecure Direct Object Reference) |
Code verifies that the user is logged in, but fails to check whether the user owns the specific object id |
Mandatory tenant & ownership filters in the data access layer: e.g., enforce WHERE id = ? AND tenant_id = ? AND user_id = ? or validate at PDP |
| BFLA (API5:2023) |
Broken Function Level Authorization (Privilege Escalation) |
Administrative endpoints (e.g. /api/admin/users/delete) only hide buttons in UI without backend route checks |
Enforce Default Deny on API gateways; route middlewares validate required roles/scopes explicitly |
| Broken Auth (API2:2023) |
Broken Authentication | Weak password hashing, lack of rate limiting, flawed token signing, or exposing tokens in URL queries | Mandate Argon2id, enforce global rate limits, prohibit tokens in query strings, enable FIDO2 Passkeys |
| SSRF | Server-Side Request Forgery | Server blindly requests user-supplied URLs (e.g. webhooks), exposing internal cloud metadata endpoints | Enforce strict egress allowlists, block private subnet IP ranges, isolate outbound network calls |
The Four-Step Observability & Continuous Auditing Loop
- Structured Audit Logging: Record tamper-proof security events (
actor,action,resource,timestamp,ip,user_agent,status,decision_reason). - Telemetry Metrics: Monitor authentication failure rates, token refresh spikes, and 401/403 anomaly distributions.
- SIEM / User and Entity Behavior Analytics (UEBA): Ingest audit events into SIEM pipelines; trigger heuristics for "impossible travel", credential stuffing, and unusual bulk export patterns.
- Automated Incident Response: High-risk threat detection triggers immediate IdP session invalidation, terminating tokens and enforcing step-up biometric MFA on subsequent requests.
Production Architecture Selection Matrix (8 Core Scenarios)
| Business Scenario | Recommended Core AuthN | Recommended AuthZ Model | Key Protocols & Infrastructure Selection |
|---|---|---|---|
| 1. Modern Web & Mobile Apps | Passkeys (FIDO2) + Short-lived JWT + Rotated Refresh Token | RBAC + Data Layer Ownership Checks | OAuth 2.0 Auth Code + PKCE, HttpOnly Cookies, Argon2id |
| 2. API & Microservices Mesh | Edge API gateway OIDC validation; internal mutual TLS | Decoupled Policy Engine (PDP) | SPIFFE/SPIRE Workload Identity, OPA/Cedar, Envoy Gateway |
| 3. Enterprise Workforce Portal | Enterprise SSO (OIDC / SAML 2.0) + Hardware YubiKey MFA | Tiered RBAC | SCIM 2.0 automated provisioning, Keycloak / Okta |
| 4. Multi-Tenant SaaS Cloud | Passwordless Magic Links / Social Federation (Google/GitHub) | Multi-Tenant Isolation + ReBAC | OpenFGA / Cedar, dynamic organization trees, Stripe Billing |
| 5. Open Banking & Fintech | Strong Customer Auth (SCA / FIDO2) + Device Binding | Real-Time Dynamic Risk ABAC | FAPI (Financial-grade API), mTLS, JARM (JWT Response Encryption) |
| 6. Autonomous AI Agent Systems | Agent Workload Certificate + RFC 8693 Token Exchange | Fine-Grained CapBAC + Guardrails | Scoped short-lived capability tokens, OpenAPI schemas, HITL alerts |
| 7. DevOps & CI/CD Pipelines | Zero Static Secrets: OIDC Workload Identity Federation | Minimal Repository-Scoped Roles | GitHub Actions OIDC $\to$ AWS IAM / GCP Workload Identity Federation |
| 8. IoT & Edge Computing | Hardware Secure Element Private Key (ECC Certificates) | Lightweight ACL / Pre-allocated rules | MQTT over TLS, EST (Enrollment over Secure Transport) |