Microservice Security Architecture: Identity, Secrets, and Response
System DesignModel answerLast updated
Design an enterprise microservice security blueprint covering mTLS workload identity, dynamic secret management, zero-downtime rotation, and immediate secret compromise containment.
You are tasked with designing the end-to-end security architecture for a high-throughput transaction processing microservice that handles sensitive cardholder data and communicates with multiple internal services.
Requirements
-
Service-to-Service Authentication & Authorization:
- How does Service A verify the identity of Service B, and vice-versa, without relying purely on network perimeter defenses?
- How do you pass user identity context across internal boundaries without risking "confused deputy" attacks?
-
Secret Management & "Secret Zero":
- Where should long-lived credentials, API keys, and database passwords be stored?
- How do you resolve the "Secret Zero" problem (how a service proves its identity to the secret store at startup without embedding a hardcoded credential)?
-
Zero-Downtime Key Rotation:
- Outline a concrete, step-by-step mechanism for rotating database credentials or third-party API keys automatically without causing dropped connections or downtime.
-
Incident Response Protocol:
- A critical production API secret was accidentally pushed to a public GitHub repository. Detail the immediate containment, remediation, and post-incident steps you would take.
Hints
Hint 1
Think about how SPIFFE/SPIRE issues short-lived cryptographic identities based on node and workload attestation.
Hint 2
For zero-downtime rotation, consider dual-credential (A/B) states where old connections can gracefully drain while new ones use updated credentials.
Hint 3
During incident response, always contain first (revoke/rotate) before deep forensic analysis.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture Overview
To achieve zero-trust security in a modern microservice environment (e.g., Kubernetes), we move away from static credentials and perimeter-based security toward identity-driven access control, short-lived tokens, and automated key lifecycles.
+----------------------------------+
| Control Plane |
| SPIRE Server <-> Vault / KMS |
+----------------+-----------------+
|
Attestation / SVID | Dynamic Credentials
v
+------------------------------------------------------------------+
| K8s Worker Node |
| |
| +------------------------------------------------------------+ |
| | Pod: Payment Service | |
| | | |
| | [App Container] <---> [Envoy Sidecar] | |
| | | | | |
| | v | mTLS with SVIDs | |
| | tmpfs (/vault) v | |
| +---------+----------------------+---------------------------+ |
+------------|----------------------|------------------------------+
| |
v v
[PostgreSQL DB] [Target Service]
(Dynamic K8s/DB User) (Validates SPIFFE ID)
1. Service-to-Service Authentication & Authorization
Identity Verification via mTLS and SPIFFE/SPIRE
- Cryptographic Workload Identity: Every service instance is assigned a short-lived X.509 certificate (SVID) issued by a SPIRE (SPIFFE Runtime Environment) agent running on the node. The certificate Subject Alternative Name (SAN) contains a structured SPIFFE ID, such as
spiffe://prod.internal/ns/payments/sa/payment-service. - Mutual Verification: Communication between services is proxied by sidecars (e.g., Envoy). Envoy terminates mTLS, presenting Service A's SVID to Service B and verifying Service B's SVID against a shared trust bundle.
- Short Lifetime: SVID certificates have a brief TTL (e.g., 1 hour) and are automatically rotated in the background by the SPIRE agent at half-life. If an identity key is exfiltrated, its window of abuse is minimal.
- Authorization Enforcement: Authentication establishes identity; policy dictates access. An authorization engine (e.g., Open Policy Agent or Envoy RBAC) checks requests against fine-grained rules (e.g., "Only identity
spiffe://.../sa/payment-servicemay invokePOST /v1/settlements").
User Context Propagation (Preventing Confused Deputy)
- When a client request enters the system through the API Gateway, the gateway authenticates the user and generates an End-User Context JWT (short-lived, e.g., 5 minutes).
- This JWT is passed in HTTP headers across downstream service calls alongside mTLS.
- Downstream services check both the mTLS identity (confirming the immediate caller is authorized to invoke the endpoint) and the user JWT (confirming the end user has permission for that specific resource).
2. Secret Management & "Secret Zero"
Storing & Injecting Secrets
- Secrets (database passwords, external payment gateway API keys) must never be checked into version control, embedded in container images, or stored in unencrypted environment variables (which risk leakage via process dumps or diagnostic endpoints like
/proc). - Secrets reside in a centralized secret manager (e.g., HashiCorp Vault, AWS Secrets Manager) backed by a Hardware Security Module (HSM) or cloud KMS.
- Secrets are fetched at pod startup via a sidecar/init container (e.g., Vault Agent) and written to a dedicated, non-persistent
tmpfs(in-memory) volume, or consumed directly via SDKs.
Solving "Secret Zero" via Attestation
The "Secret Zero" problem asks: How does a container authenticate to the secret manager without already holding a password?
We solve this using layered platform attestation:
- Node Attestation: The SPIRE agent on a node proves its identity to the SPIRE server using the cloud provider's identity document (e.g., AWS EC2 Instance Identity Document or GCP Managed Instance Group token).
- Workload Attestation: When a new pod starts, the local SPIRE agent inspects the Linux kernel/kubelet state (PID, Cgroup, Namespace, K8s ServiceAccount name, Image digest).
- SVID Issuance: If the attestation matches a registered rule, SPIRE issues an SVID certificate to the pod.
- Vault Authentication: The pod presents its short-lived SVID or K8s ServiceAccount Token to Vault's
certorkubernetesauth backend. Vault validates the token against the K8s API or trust root and trades it for a short-lived Vault token scoped strictly to that service's policy.
3. Zero-Downtime Key Rotation
For database credentials or third-party keys, hard-restarting services during rotation introduces downtime. We use two primary patterns:
Pattern A: Dynamic Secrets (Preferred for Databases)
Instead of a static password shared across instances, Vault's database engine dynamically generates unique, ephemeral database users for each application pod with an explicit TTL (e.g., 4 hours).
- When a pod starts, Vault creates a temporary DB user:
v_app_payment_a8f912. - Vault periodically renews the lease. When the pod terminates, Vault drops the DB user automatically.
- Rotation is continuous and native; no global rotation event is needed.
Pattern B: Dual-Credential (A/B) Rotation (For Third-Party API Keys)
For external APIs that support multiple simultaneous keys:
Step 1: Active = Key_A, Pending = None
Step 2: Generate Key_B on Provider -> Active = Key_A, Pending = Key_B
Step 3: Update Secret Store with Key_B -> Apps pick up Key_B
Step 4: Drain / Verify metrics -> Zero requests using Key_A
Step 5: Revoke Key_A on Provider -> Active = Key_B
- Generate: Generate a new key (
Key_B) on the third-party provider whileKey_Aremains fully operational. - Publish: Push
Key_Bto the secret manager under a dual-version key structure ({ current: Key_B, previous: Key_A }). - Propagate & Dual-Read: The application sidecar fetches the updated secret bundle. The application attempts calls with
Key_B. IfKey_Bfails due to propagation delays, it falls back toKey_A. - Connection Pool Recovers: Existing HTTP connections or client pools naturally recycle according to their maximum connection TTL (e.g., 5 minutes).
- Verify & Revoke: Monitor API metrics. Once 100% of outbound requests are confirmed using
Key_B(or a safety window elapses), deactivate and deleteKey_A.
4. Incident Response: Exposed Production Secret
When a secret scanning system detects an active production credential pushed to a public repository, every minute counts.
Phase 1: Containment & Immediate Mitigation (T + 0 to 15 mins)
- Invalidate / Rotate Immediately: Do not spend time searching for the offender before revoking. Immediately trigger an emergency rotation or explicit revocation of the exposed credential in the secret manager or provider dashboard.
- Deploy Updated Credential: If using dual-key rotation, push the new key version to trigger immediate pod re-authentication/reloads.
- Block / Quarantine: If the credential cannot be instantly rotated without downtime, temporarily apply IP restrictions or rate-limits at the gateway for that key's actions, or invoke emergency feature flags to degrade non-critical endpoints safely.
Phase 2: Eradication & Verification (T + 15 to 60 mins)
- Purge Commit History: Remove the secret from Git history (e.g., using
git-filter-repoor BFG Repo-Cleaner) and force-push to clean the repository. Note that public forks or web caches may still contain it, which reinforces why credential revocation in Phase 1 is the primary line of defense. - Verify Invalidation: Run test queries using the revoked secret to confirm active connections fail with explicit 401/403 responses.
Phase 3: Forensics & Auditing (T + 1 hr to 24 hrs)
- Audit Log Inspection: Query SIEM and CloudTrail/Vault access logs for the window between commit time and revocation time. Look for access logs matching the compromised key ID or originating from unexpected IP addresses/user-agents.
- Scope Determination: Assess whether any cardholder data or sensitive entities were queried or exported during the exposure window.
Phase 4: Post-Mortem & Preventative Controls
- Root Cause Analysis (RCA): Identify why existing protections failed (e.g., developer disabled pre-commit hooks or bypassed local checks).
- Preventative Automation:
- Pre-commit / Pre-push Hooks: Mandate tools like
gitleaksortrufflehogin local developer workflows and CI pipelines. - Repository Guardrails: Enable platform-level secret scanning with automatic push-blocking enabled (e.g., GitHub Secret Scanning with Push Protection).
- Shift to Ephemeral Credentials: Accelerate transition away from long-lived static API keys to dynamic tokens or IAM roles, reducing the impact of code-based leaks to zero.
- Pre-commit / Pre-push Hooks: Mandate tools like