Checking access…

Skip to main content
Audience: CCG Platform Engineers

Session Cookie Encryption & Key Rotation

Platform engineers understanding the encryption and rotation design. For exact fields and configuration, see the reference. For rotation and incident procedures, see the runbook. See PayeeConfig Encryption for the related encryption pattern.

Overview​

auth-service (wallet-auth-service) issues a browser session credential β€” the __Host-wallet_session cookie β€” after a successful HSID (OIDC) authentication or guest checkout handshake. The cookie's value carries the checkout session ID, merchant ID, customer ID, and issue/expiry timestamps, so it is encrypted (not just signed) before it ever reaches the browser. The same encryption is reused for the short-lived OIDC state parameter.

Encryption is AES-256-GCM, wrapped as a compact JWE (alg=dir, enc=A256GCM) via nimbus-jose-jwt. The key lives in Azure Key Vault (never in source code or static app config) as the secret HSID-JWE-SECRET. Every JWE stamps the exact Key Vault secret version used to encrypt it into its kid header, so decryption always resolves the precise key version from the token itself β€” this is what makes zero-downtime key rotation possible: auth-service can start encrypting new cookies with a new key version while old, still-valid cookies encrypted with the previous version keep decrypting correctly until that version is retired.

This replaced an earlier design that used two static, config-injected secrets (jwe-secret / previous-jwe-secret) and guessed which of the two applied on decrypt. Implemented under ticket CC-27017.

Architecture​

+----------------------------------------------------------------------------------+
| auth-service |
| |
| Issue / validate path (per-request) |
| SessionCookieService.buildEncryptedSessionCookie / validateSessionCookie |
| -> CredentialService.encrypt / decrypt (Mono, offloaded to boundedElastic) |
| -> SessionCookieKeyCache |
| - currentVersion(): TTL-cached "latest version" pointer (1m default) |
| - getKeyForVersion(kid): per-version key material, cached forever |
| -> KeyVaultSecretClient (Azure or Local, by Spring profile) |
| |
| Rotation path |
| SessionCookieKeyRotationScheduler |
| - checkAndRotate() [twice-daily cron] |
| -> SessionCookieKeyRotationService.rotate("SCHEDULER") |
| -> AdvisoryLockService (Postgres advisory lock, cluster-wide singleton)|
| -> KeyVaultSecretClient.pushNewSecretVersion |
| - checkAndDisableExpiredVersions() [every-minute cron, no lock needed] |
| -> SessionCookieKeyRotationService.disableExpiredPreviousVersions |
| -> KeyVaultSecretClient.listVersions / disableSecretVersion |
| -> SessionCookieKeyCache.invalidateVersion |
| |
| External rotation path (Security-triggered emergency rotation) |
| Security pushes a new HSID-JWE-SECRET version directly in Key Vault |
| -> Azure Event Grid: Microsoft.KeyVault.SecretNewVersionCreated |
| -> KeyVaultSecretEventConsumer.handle |
| -> SessionCookieKeyRotationService.onExternalVersionDetected |
| -> SessionCookieKeyCache.refresh() |
+----------------------------------------------------------------------------------+

There is no in-app "force rotation" endpoint. An early version of this feature added POST /v1/session/encryption/key-rotation, but it was removed in review because this service's own public Ingress routes every path (config/helm/templates/ingress.yaml), so the endpoint could not actually be restricted to cluster-internal callers as intended. Emergency rotation is Security pushing a new secret version straight to Key Vault β€” auth-service already owns the RBAC/network wiring to react to that via Event Grid, so no new application-level attack surface was needed.

Pushing a new version is not the same as revoking the old one β€” see Incident Response: Revoking a Compromised Key below, which is the part of the emergency path that actually matters under compromise pressure.

Key Rotation​

Scheduled rotation​

SessionCookieKeyRotationScheduler.checkAndRotate() runs on rotation-check-cron (twice daily by default) and calls SessionCookieKeyRotationService.rotate("SCHEDULER"):

  1. Acquires the auth-service:session-cookie-key-rotation Postgres advisory lock (non-blocking; if another pod already holds it, this pod logs KEY_ROTATION_SKIPPED and does nothing further).
  2. Refreshes the cached current version and checks its age against the effective rotation interval (rotation-interval-override-seconds if set and valid, else rotation-interval).
  3. If due, generates a new 256-bit AES key and pushes it as a brand-new Key Vault secret version (pushNewSecretVersion), then refreshes the local cache.

There is no forced/emergency variant inside this service β€” see Rotation Triggers above for how an emergency rotation actually happens (Security pushing directly to Key Vault).

Grace-period sweep​

SessionCookieKeyRotationScheduler.checkAndDisableExpiredVersions() runs on grace-period-check-cron (every minute by default) and calls disableExpiredPreviousVersions(). This needs no lock β€” disabling an already-expired version is idempotent β€” and runs independently on every pod:

  • Lists every version of the secret from Key Vault (Key Vault never deletes old versions on its own).
  • For each enabled, non-current version, derives when it was superseded (the creation time of the next-newer version β€” not the version's own age) and disables it once that supersession age reaches grace-period.
  • Any version already disabled β€” by this pod's own earlier sweep, another pod, or Security disabling it directly β€” is unconditionally evicted from this pod's local cache, so every pod converges within one sweep interval.

Grace is measured from supersession time, not creation time, specifically because the primary 90-day scheduled rotation would otherwise disable the outgoing version almost immediately (it's already 90 days old the instant it stops being current) β€” defeating the whole point of the grace period.

Cross-pod convergence​

  • A rotation pushed by any means (scheduled push, or Security's emergency push) fires a Microsoft.KeyVault.SecretNewVersionCreated Event Grid event, picked up by every pod's KeyVaultSecretEventConsumer for near-instant currentVersion() refresh.
  • A pod that misses that notification (webhook misconfigured/down) still self-heals within latest-version-ttl (default 1 minute), since SessionCookieKeyCache.currentVersion() re-checks Key Vault once its TTL expires.

Session Continuity During Key Rotation β€” Scenario Matrix​

The core requirement this whole design exists to satisfy: a session/state encrypted before a rotation must keep decrypting correctly for its full remaining lifetime, regardless of how many rotations happen while it's alive, or which pod happens to serve the request. Every scenario below is exercised by an actual test β€” this is not aspirational.

#ScenarioWhat happensWhy it's safeVerified by
1A session is encrypted with the current version; no rotation happens before it expires.Decrypts normally for its full TTL.Trivial baseline β€” no version change involved.SessionCookieServiceCryptoRoundTripTest
2A session is encrypted with V1; V1 is scheduled-rotated to V2 shortly after; the session is still within its TTL.Decrypts successfully throughout the grace period, using the exact kid stamped at encrypt time.kid-based resolution means decrypt never has to "guess" between current/previous β€” it asks Key Vault for the exact version, which is still enabled.SessionCookieKeyRotationLifecycleTest (full rotate β†’ decrypt-during-grace β†’ disable β†’ reject cycle)
3A pod's cached currentVersion() pointer is stale (a rotation happened elsewhere, but this pod hasn't refreshed) β€” it keeps encrypting new sessions with the soon-to-be-superseded V1 for up to latest-version-ttl (1m) after V2 became current.The resulting session, encrypted with V1 at the worst possible moment, must still be decryptable for its entire TTL (15m) after that.grace-period (16m) is sized as latest-version-ttl + max(payload TTLs) (1m + 15m = 16m) β€” exactly covers this worst case with zero slack today. Enforced by a startup check, not a runtime one.SessionCookieEncryptionSafetyValidator + SessionCookieEncryptionSafetyValidatorTest (fails startup if the margin is violated)
4The grace period for V1 elapses; V1 is disabled in Key Vault.New decrypt attempts for V1 fail with SecretVersionUnavailableException β†’ 401. Any session still relying on V1 at this point has, by construction, already exceeded its own maximum possible TTL.Grace is measured from supersession time (when V2 appeared), not V1's own age β€” critical since the real 90-day rotation means V1 is already ~90 days old the instant it's replaced.disableExpiredPreviousVersions_doesNotDisable_justRotatedVersion_evenThoughItIsNinetyDaysOld, boundary-parameterized tests at 0/1/5/14 vs. 15/16/30/90 minutes
5Several rotations happen back-to-back (dev short interval, or an emergency rotation landing right after a scheduled one) before earlier versions' grace periods elapse.Each version still gets its own full, independent grace period.Grace is anchored to each version's immediate successor, not to whatever is "current" right now β€” a chain of N rotations doesn't compress any earlier version's window.disableExpiredPreviousVersions_disablesMultipleExpiredVersions_inOnePass
6A pod runs its grace-period sweep while its own currentVersion() pointer is stale (points at an old version, not the true newest).The sweep can still never disable the actual newest version by createdAt, regardless of what the pod's stale pointer claims is "current".The newest-by-timestamp version always has no successor in the sort, independent of the currentVersion string used only for the skip check.disableExpiredPreviousVersions_neverDisablesTheNewestVersion_evenWhenCurrentVersionPointerIsStale
7Two versions are created within the same second (Key Vault createdOn has 1-second resolution) β€” e.g. two emergency rotations moments apart.The predecessor still gets a correctly-ordered successor and a real grace deadline, instead of never expiring.Sort ties are broken by placing the pod's believed-current version last.disableExpiredPreviousVersions_disablesVersion_whenItTiesOnTimestampWithTheCurrentVersion
8A version is disabled by a different pod, or by Security directly in Key Vault (not by this pod's own sweep).This pod's local cache still forgets it within one of this pod's own sweep intervals (≀1 minute), converging without needing to be the one that performed the disable.The "already disabled β†’ invalidate" check is unconditional on every sweep, independent of who disabled it.disableExpiredPreviousVersions_invalidatesCache_forAVersionAlreadyDisabledByAnotherPod
9A version's disable call fails (Key Vault error, e.g. throttling).The version stays enabled and stays in the local cache β€” not evicted β€” and is retried on the next sweep.Only a confirmed disable should evict; a failed API call must not pretend the version is gone.disableExpiredPreviousVersions_doesNotEvictFromKeyCache_whenDisableCallFails, _continuesProcessingOtherVersions_whenOneDisableCallFails
10A kid-less cookie shows up (issued by the pre-CC-27017 static-secret implementation) shortly after this feature's cutover deploy.Falls back to the ops-configured legacy-version for one cookie/state lifetime, then the fallback path stops being exercised as those old cookies expire.Explicit, ops-verified fallback rather than an auto-detected heuristic that could misresolve.CredentialService legacy-kid tests; LEGACY_KID_LESS_COOKIE_* log events

Known limitations​

  • Zero-slack margin today. With current defaults, grace-period (16m) exactly equals the required minimum (latest-version-ttl 1m + checkout-session/OIDC-state TTL 15m) in every environment β€” there is no extra buffer. This is intentional (see the code comment history on this value), and it's fail-safe: SessionCookieEncryptionSafetyValidator fails startup if AUTH_CHECKOUT_SESSION_EXPIRY_IN_MINUTES or the OIDC state TTL is ever increased without a matching grace-period increase. But it means any change to those TTLs must be paired with a grace-period change in the same PR, not left to a later cleanup.
  • Per-pod convergence, not instantaneous. A pod's own disablement/invalidation depends on that pod's own grace-period-check-cron continuing to fire. In practice this is extremely reliable (Spring's @Scheduled keeps firing on schedule even if a single execution throws, and every relevant method here already catches and logs its own exceptions), but it's worth knowing that the "converges within one sweep interval" guarantee is per pod, not a single global event.
  • Pushing a new key version does not, by itself, revoke the old one within any bounded time better than the configured grace period. See the next section β€” this is the one gap worth internalizing before relying on "emergency rotation" as an incident-response tool.

Sequences​

HSID callback / guest checkout -> SessionCookieService.buildEncryptedSessionCookie(session)
-> serialize SessionCookiePayload to JSON
-> CredentialService.encrypt(bytes)
-> SessionCookieKeyCache.currentVersion() [Key Vault on TTL miss]
-> SessionCookieKeyCache.getKeyForVersion(version) [Key Vault on cache miss]
-> JWEObject(header{kid=version}, payload).encrypt(DirectEncrypter)
-> ResponseCookie(__Host-wallet_session, jwe, HttpOnly, Secure, SameSite=Lax, MaxAge=session TTL)
Protected request -> SessionCookieService.validateSessionCookie(cookie, session, merchantId, customerId)
-> CredentialService.decrypt(jwe)
-> parse kid from JWE header (fallback to legacy-version if absent)
-> SessionCookieKeyCache.getKeyForVersion(kid) [rejects malformed kid before any lookup]
-> JWEObject.decrypt(DirectDecrypter)
-> parse SessionCookiePayload JSON
-> check expiresAt, sessionId, merchantId, customerId claims

Sequence: Scheduled rotation​

SessionCookieKeyRotationScheduler.checkAndRotate() [cron: rotation-check-cron]
-> AdvisoryLockService.tryLockAndExecute("auth-service:session-cookie-key-rotation")
lock busy -> KEY_ROTATION_SKIPPED, done
lock acquired ->
-> SessionCookieKeyCache.refresh() -> current version + createdAt
-> age >= effective rotation-interval ?
no -> KEY_ROTATION_NOT_DUE
yes -> generate 256-bit AES key
-> KeyVaultSecretClient.pushNewSecretVersion(HSID-JWE-SECRET, newKey)
-> SessionCookieKeyCache.refresh()
-> KEY_ROTATION_COMPLETED
-> release advisory lock

Sequence: Emergency rotation (Security-triggered, routine β€” new key, old key not compromised)​

Security -> az keyvault secret set --name HSID-JWE-SECRET --value <new base64 key>
-> Azure Event Grid: Microsoft.KeyVault.SecretNewVersionCreated
-> every pod's KeyVaultSecretEventConsumer.handle
-> SessionCookieKeyRotationService.onExternalVersionDetected("HSID-JWE-SECRET")
-> SessionCookieKeyCache.refresh() [new version becomes "current" immediately]
-> next grace-period sweep disables the old version once its grace period elapses [~16m default]

Sequence: Key compromise (Security-triggered, old key must be revoked immediately)​

Security -> az keyvault secret set --name HSID-JWE-SECRET --value <new base64 key>
-> (as above: every pod adopts the new version as current near-instantly)

Security -> az keyvault secret set-attributes --name HSID-JWE-SECRET --version <compromised-version> --enabled false
-> No Event Grid event fires (no new version was created)
-> Every pod's own next grace-period-check-cron tick [~1m default]:
-> disableExpiredPreviousVersions() lists versions, sees compromised-version.enabled=false
-> SessionCookieKeyCache.invalidateVersion(compromised-version) [unconditional, before any grace-period math]
-> Any session still encrypted with the compromised version is now rejected on every pod within ~1 minute,
not the full 16-minute grace period β€” see Incident Response above.