Design and operational practices for authentication and authorization across systems and applications. Covers identity models, provisioning and deprovisioning, role based access control and roles and permission design, policy enforcement, segregation of duties, and principle of least privilege. Includes service to service authentication and infrastructure access patterns, database authentication modes and database roles, audit trails for access and authorization changes, methods for granting and revoking permissions, and techniques to detect and investigate unauthorized access. Also addresses scaling identity and access control for large organizations, single sign on, federation, and integration with external identity providers.
HardSystem Design
59 practiced
Design a Continuous Access Evaluation (CAE) system that enables near-immediate revocation of access when credentials are compromised or roles change. Describe how change events are detected, how they are securely propagated to enforcement points (API gateways, microservices, mobile clients), options for push vs pull invalidation, securing the propagation channel, and methods to minimize latency while scaling to tens of thousands of active sessions.
Sample Answer
**Clarify requirements & constraints**- Near-immediate revocation (<1–5s ideal), support API gateways/microservices/mobile, scale to 10k–100k active sessions, minimize operator complexity and false positives.**High-level architecture**- Change detector → CAE Policy Decision Point (PDP) → Pub/sub event bus → Policy Enforcement Points (PEPs: API gateways, services, mobile clients) with local PDP cache/engine.**Change event detection**- Sources: IAM events (role change, disable), credential telemetry (leaked password, suspicious MFA), threat intel, HR/ERP.- Ingest via CDC + audit events (Kafka or event stream). Enrich with context (user, session id, device, risk score).**Propagation: push vs pull**- Push (preferred for low latency): pub/sub fanout (Kafka, NATS, or AWS SNS+Lambda). PEPs subscribe via persistent connections (gRPC streams, WebSockets, or SSE) for gateways/services. Mobile: APNs/FCM for user-facing; in-app gRPC/SSE for managed clients.- Pull (fallback/resilience): short polling + token introspection endpoint; sidecar caches poll if stream fails.- Hybrid: push primary, periodic pull to reconcile missed events.**Secure propagation channel**- Mutual TLS between PDP/event broker and PEPs; enforce mTLS, TLS1.3, client cert rotation.- Sign events (JWT with key ID) and include sequence numbers/timestamps to prevent replay; validate signatures and freshness.- Encrypt payloads at rest and in transit; restrict broker ACLs and use VPC/private networking.**Enforcement & local caching**- PEP stores per-session state/versioned tokens (session_id, revocation_version). On event, publish delta: {session_id, new_version, action}.- Local PDP evaluates quickly against cached policies and revocation_version. For gateways, reject/force token refresh or introspect.- Use short-lived access tokens (e.g., 1–5m) + opaque session handles for granular revocation.**Minimize latency at scale**- Fanout via tiered brokers: central stream → regionally sharded brokers → edge PEPs to reduce hops.- Keep event payloads small (deltas), use batching for bursts but prioritize high-risk events for immediate delivery.- Use sticky connections and connection pooling; autoscale subscription workers.- Circuit-breakers + eventual-consistency windows: urgent events force immediate push; noncritical updates use best-effort.**Reliability & observability**- Exactly-once or at-least-once semantics with idempotent processing and ordering by session_id.- Metrics: delivery latency, ack rates, missed events; alert on stream lag.- Replay store for reconciling dropped connections.**Example flow**1. HR disables user → IAM emits event to Kafka.2. CAE PDP enriches event (active sessions list) → publishes delta to topic.3. Regional broker pushes to API gateway via gRPC stream; gateway validates signature and immediate revokes session token and returns 401 for subsequent requests.4. Mobile app receives FCM silent push to logout or triggers in-app introspection.Trade-offs: push minimizes latency but requires persistent connections and more infra; hybrid provides resilience. Implement short token lifetimes and fast push to balance UX and security.
MediumSystem Design
44 practiced
Design a system for issuing, rotating, and revoking API keys used by services and external partners. The system must support automated rotation without downtime, bind keys to service identities and scopes, provide audit trails, integrate with CI/CD and secret managers, and support emergency revocation. Describe issuance flows, rotation strategies (rolling, short-lived), migration for consumers, and how to deprecate long-lived keys in favor of ephemeral tokens.
Sample Answer
**Clarify requirements**- Keys must be bound to service identity + scopes, support automated zero-downtime rotation, audit logging, CI/CD & secret-manager integration, emergency revocation, migration path from long-lived to ephemeral.**High-level architecture**- Central Key Management Service (KMS-web) + backend Key Store (HSM/KMS), Audit DB (immutable), Revocation List/CRL service, Connector services to Secret Managers (Vault, AWS Secrets Manager), CI/CD plugin, Service Identity Provider (mTLS/JWT/Workload Identity).**Issuance flow**1. Developer/partner requests key via API/portal with identity proof (OIDC) and requested scopes.2. KMS validates identity, policy engine issues key record with metadata, stores secret in HSM, pushes copy into requested secret manager path.3. KMS returns key reference (not raw secret) to client or populates CI/CD secret; full audit entry created.**Rotation strategies**- Rolling: KMS issues new key version, pushes to secret manager, notifies consumers via webhook; consumers fetch secondary key and dual accept for grace window; KMS marks old key deprecated then revoked after success.- Short-lived/ephemeral: Prefer OAuth-like ephemeral tokens minted with service identity using client certs or JWT—no manual distribution. Use token broker to exchange long-lived credential for short-lived token.**Migration**- Dual-write/dual-accept: require consumers to accept both old and new keys during window. Provide SDK/plugin to fetch current active keys from secret manager and auto-retry on auth failure.- Phased deprecation: measure usage via audit logs, extend windows for critical partners.**Revocation & emergency**- Immediate: KMS marks key revoked, adds to CRL and pushes notifications; gateway/auth layer checks CRL/real-time introspection to block usage; rotate service credentials and revoke pushed secrets.- Emergency automation: playbooks to rotate dependent keys, invalidate tokens, and notify stakeholders.**Auditing & Monitoring**- Immutable audit trail with who/when/why, alerts on abnormal rotation/revocation, integrate SIEM, and provide access logs for downstream services.**CI/CD & Secret Manager integration**- CI/CD plugin authenticates with KMS via OIDC to fetch ephemeral tokens or secrets; secrets never stored in plaintext in pipelines—use short-lived injected secrets.**Deprecating long-lived keys**- Enforce policy: create timeline to ban new long-lived keys, offer token-broker for ephemeral tokens, implement gateway policy to reject long-lived credential usage after cutoff, and run audits with automated revocation for remaining keys.Why this works: binds identity → policy → secrets lifecycle, minimizes blast radius with short-lived tokens, provides zero-downtime rotations, and enforces visibility and control for security operations.
HardSystem Design
41 practiced
Edge services must perform millions of authorization checks per second while minimizing calls to central PDPs. Design an authorization caching architecture that provides low-latency decisions, supports policy and permission changes, and guarantees eventual consistency. Discuss cache keys, TTL strategies, invalidation via events, negative caching, fallback to live PDP on cache miss, and measures to avoid stale allow decisions.
Sample Answer
**Clarifying goals**Low-latency auth decisions at edge (millions/s), minimal PDP calls, support policy/permission changes, eventual consistency, and avoid stale "allow" decisions that create security risk.**High-level architecture**- Edge cache (local in-process LRU + shared regional Redis/Hot cache) → fallback to regional PDP → central PDP for writes/policy changes.- Event bus (Kafka/CDC) pushes invalidation/change events to regions; edges subscribe.**Cache keys**- Key = subject:id | resource:id | action | context-hash (e.g., tenant, environment, resource-version, attributes digest)- Include policy-version or permission-bitmap version in key to enable coarse-grained invalidation.**TTL strategy**- Hierarchical TTLs: - Short TTL (seconds) for high-risk allowable ops. - Medium TTL (minutes) for stable read-only perms. - Long TTL for immutable system roles.- Use adaptive TTL: shorter after a recent change event.**Invalidation via events**- Central PDP emits policy/permission change events with affected keys, affected principals, resource IDs, and new policy-version.- Regional invalidators translate to cache-key invalidations and broadcast to edges.- Support wildcard/topic-based invalidation for large blasts (e.g., tenant-wide revoke).**Negative caching**- Cache "deny" results with short TTL and include source timestamp and policy-version.- Record reasons (e.g., missing entitlement) to speed common denials.**Fallback to live PDP**- On cache miss or stale-version detection, edge synchronously queries regional PDP with request context; cache result.- Use async refresh to pre-warm.**Avoiding stale allow decisions**- Never cache positive allow longer than risk-tuned max TTL.- On any policy-change event affecting a key, immediately invalidate cached allows.- Use cryptographic policy-version signatures so edges can quickly detect version drift.- For high-sensitivity actions, require short TTLs or online PDP validation (fail-closed on uncertain state).**Consistency & observability**- Eventual consistency: provide audit logs, metrics for cache hit/miss, invalidations, and PDP latency.- Rate-limit PDP fallback and circuit-break with graceful degrade (deny-open only with explicit policy).- Test via chaos-invalidation and breach simulations.This design balances latency and security by combining versioned keys, event-driven invalidation, conservative positive caching, and live PDP fallback for correctness.
HardSystem Design
41 practiced
Design a CI/CD pipeline access model where build agents and deployment jobs have just enough privileges for each pipeline stage. Explain how to provision ephemeral credentials per job, inject secrets securely at runtime (without storing them in plain text in logs), sign and verify build artifacts, and prevent credential leakage. Describe integration with secret managers, workload identity federation, and artifact attestation.
Sample Answer
**Clarify goals (brief)** Provide least-privilege access to build agents and deployment jobs, issue ephemeral credentials per job, inject secrets at runtime without leaking to logs, cryptographically sign and attest artifacts, and integrate with secret managers + workload identity federation.**High-level approach**- Treat each pipeline job as a short-lived workload with its own identity and scoped permissions.- Use OIDC workload identity federation between CI/CD platform and cloud IAM to mint short-lived tokens (no long-lived creds).- Store secrets in a central secret manager (KMS-backed) and deliver to jobs only when needed via ephemeral sessions.**Provisioning ephemeral credentials**- Configure CI system (e.g., GitHub Actions, GitLab, Jenkins) to request OIDC token with constrained audience and job-specific claims (repo, job-id, run-id).- Cloud IAM maps those claims to a temporary role via trust policy; role issues STS credentials (vended for e.g., 5–15 mins) scoped to required APIs (e.g., access to secret-manager:get, artifact-storage:write).- Enforce MFA/approval for high-risk stages (canary, prod) via human-in-the-loop.**Secure secret injection (no plain-text logs)**- Secrets stored encrypted in Secret Manager (KMS). Jobs request secrets via authenticated ephemeral token.- Inject secrets at runtime using: - Secret CSI drivers or secret-sidecar that mounts secrets into in-memory tmpfs files with 0600 perms, or - Memory-only process (stdin) or OS keyring APIs — never as persistent files or logged env vars.- Configure CI runner to: - Mask secrets in logs (native masking + regex redaction). - Drop environment variables from step-level log context. - Run untrusted build steps inside isolated containers with no logging of /proc for memory.- Use ephemeral credential caching and automatic revocation at job end.**Signing & verifying build artifacts**- Adopt keyless or hardware-backed signing: - Use Sigstore (cosign + Rekor + Fulcio) to sign artifacts; signing keys are ephemeral and issued via OIDC-bound certificates. Or use HSM/KMS-managed asymmetric keys with short-lived signing grants.- After build, create signed provenance (in-toto or SLSA provenance) and publish to an immutable transparency log (Rekor).- Enforce verification in deployment: deployment jobs verify artifact signature + provenance before promoting.**Artifact attestation & policy**- Generate attestation statements (SLSA 3/4) containing build inputs, builder identity (OIDC claims), git commit, SBOM, test results.- Store attestations alongside artifacts in artifact registry.- Enforce policy via Policy Engine (OPA/Gatekeeper) that validates signatures, provenance, and SBOM before allowing deploy to sensitive environments.**Preventing credential leakage**- Short-lived tokens + automatic rotation and revocation.- Network egress controls from build agents; restrict external outbound to only approved artifact registries and secret-manager endpoints.- Prevent shelling out to network via container seccomp/apparmor, and run builds with minimal capabilities.- Audit and monitoring: log token issuance, secret access events, signature operations to SIEM. Alert on anomalous patterns.- Continuous scanning for secrets in artefacts/logs (preventive DLP).- Harden runners: immutable images, regular patching, ephemeral runner pools that are destroyed each job.**Integration summary**- Secret Manager + KMS: store encrypted secrets; grant short-lived access via IAM roles minted through OIDC.- Workload Identity Federation: CI -> OIDC -> cloud IAM to mint scoped STS credentials or certs.- Signing & Attestation: cosign/Fulcio/Rekor or KMS/HSM signing + in-toto/SLSA attestations stored with artifacts.- Policy enforcement: OPA/CI gates validate signatures, attestations, SBOM and deny deploys on failures.**Example flow (concise)**1. Job starts; CI requests OIDC token with job claims. 2. Cloud IAM issues temporary role credentials scoped to secrets/artifact write. 3. Job fetches secrets via Secret Manager; secret driver mounts into tmpfs; secrets masked. 4. Build produces artifact; cosign signs via short-lived cert; attestation (SLSA) generated and uploaded. 5. Deployment job verifies signature + attestation via policy engine; if valid, proceeds with ephemeral deploy creds.This model enforces least privilege, reduces blast radius via ephemeral creds, prevents leakage with in-memory mounts and log masking, and establishes cryptographic chain-of-custody for artifacts.
MediumSystem Design
42 practiced
Design the identity and authorization architecture for a multi-tenant SaaS platform that must support per-tenant SSO (multiple external IdPs per tenant), strict tenant isolation, delegated tenant administrators, and shared services (billing, support). Describe identity model (user vs tenant identities), token design (claims like tenant_id, audience), tenancy-aware PDP behavior, role modeling, and how to enforce isolation at compute and data layers.
Sample Answer
**Clarify goals & constraints**- Multi-tenant SaaS, per-tenant SSO (multiple external IdPs), strict isolation, delegated tenant admins, shared services (billing/support). Threat model: cross-tenant access, token replay, privilege escalation.**Identity model**- Two identity types: - Tenant identities: tenant record (tenant_id, config, allowed IdPs, org policy). - User identities: canonical internal user objects mapped to external IdP subjects. Each user has (user_id, tenant_id, external_idp, external_sub, email, roles, status).- Link external SSO accounts to internal user_id; support multiple external accounts per user.**Token design**- Short-lived JWTs for access; refresh tokens rotated/stored securely.- Key claims: - tenant_id (string) — authoritative tenant context - sub (user_id) - external_idp (idp_id) - aud (service name) — audience restricted per-service - scope / roles (minimal coarse-grained) - token_type, iat, exp, jti- Use mTLS or token binding for sensitive service-to-service tokens. Validate issuer per tenant mapping.**PDP / Authorization behavior**- Centralized PDP service (authorization microservice) that is tenancy-aware: - Input: token claims, resource identifier (resource_id with tenant_id), action. - Resolve tenant from token. If tenant_id absent or mismatched with resource -> deny. - Evaluate: tenant-level policies (ABAC), role assignments, resource ACLs. - Cache decisions short-term; log decisions for audit.- Support delegated tenant admins: admin users have scoped admin roles (admin:tenant:manage:tenant_id) and constraints enforced by PDP.**Role modeling**- Role hierarchy per tenant: - System roles (global): billing_read, support_read limited to shared services and authorized tenants. - Tenant roles: owner, admin (delegated), developer, reader.- Roles expressed as concrete claims and stored both on user record and PDP policy store to support revocation.**Enforcing isolation**- Compute isolation: - Namespace-level separation (Kubernetes namespaces with PSPs/PodSecurity for tenant workloads) or tenant-specific service instances for high-risk tenants. - Network policies and sidecars to enforce egress/ingress filtering; mTLS and mutual auth between services with tenant-scoped certs.- Data isolation: - Logical isolation via tenant_id column + strong DB row-level security (RLS) policies that enforce tenant_id = current_token. For sensitive tenants use separate schemas or DBs. - Encrypt tenant data with tenant-specific keys (envelope encryption). Key management per tenant in KMS; rotate keys on tenant offboarding.- Access control enforcement layers: - API gateway validates tokens (aud, issuer, tenant_id) and rejects mismatches. - Service-level middleware calls PDP for fine-grained checks before data access. - DB-level RLS as last line of defense.**Operational controls**- Audit trails: immutable logs with tenant_id, user_id, jti, action.- Provisioning: automated onboarding to register IdPs per tenant, metadata validation (SAML/OpenID metadata).- Revocation: immediate token revocation via token blacklist or short lifetimes + refresh token revocation; revoke keys in KMS on compromise.- Tests: regular tenant-isolation penetration tests and CI checks to validate RLS and PDP enforcement.This architecture minimizes blast radius, enforces defense-in-depth (gateway → PDP → service → DB), supports multiple IdPs per tenant, and gives delegated admins scoped power without jeopardizing cross-tenant security.
Unlock Full Question Bank
Get access to hundreds of Identity and Access Management interview questions and detailed answers.