Session Cookie Encryption & Key Rotation β Reference
Exact data, components, configuration, logs, errors, and test coverage. For the design, see the overview; for operational steps, see the runbook.
Cookie Detailsβ
| Attribute | Value |
|---|---|
| Name | __Host-wallet_session (Constants.WALLET_SESSION_COOKIE_NAME) |
HttpOnly | true |
Secure | true |
SameSite | Lax |
Path | / |
Max-Age | Time remaining until the checkout session's expiresAt |
| Value | Compact JWE (alg=dir, enc=A256GCM) of the JSON payload below |
The __Host- cookie name prefix is itself a browser-enforced security control: it requires Secure, forbids a
Domain attribute, and requires Path=/, so the cookie can never be set or overridden by a subdomain or a
non-HTTPS response.
Encrypted payload (SessionCookiePayload)β
{
"sessionId": "<checkout session UUID>",
"merchantId": "<merchant UUID>",
"customerId": "<customer UUID, nullable for guest>",
"issuedAt": "<ISO-8601 instant>",
"expiresAt": "<ISO-8601 instant>"
}
On every protected request, SessionCookieService.validateSessionCookie decrypts the cookie and checks:
expiresAthas not passed,customerId,sessionId, andmerchantIdclaims match the resolved checkout session/request context.
A decrypt failure (bad/disabled key version, tampered/malformed JWE) and a claim mismatch both surface as
AuthorizationException β HTTP 401, using the same legacy error messages as before this rework.
Libraries & Dependenciesβ
Resolved versions as declared/managed in wallet-auth-service's pom.xml (Spring Boot 4.1.0 parent BOM +
azure-sdk-bom 1.2.27):
| Library | Version | Used for |
|---|---|---|
com.nimbusds:nimbus-jose-jwt | 9.37.2 | JWE construction/parsing (JWEObject, JWEHeader) and the DIR/A256GCM encrypt/decrypt primitives (DirectEncrypter/DirectDecrypter) in CredentialService. |
com.azure:azure-security-keyvault-secrets | 4.8.6 | SecretClient β the actual Key Vault REST calls in AzureKeyVaultSecretClient (get/set/list/disable secret versions). |
com.azure:azure-identity | 1.12.2 | DefaultAzureCredentialBuilder with managed-identity client ID β how the pod authenticates to Key Vault (no client secret). |
com.azure:azure-messaging-eventgrid | 4.24.0 | EventGridEvent deserialization in KeyVaultSecretEventConsumer for the SecretNewVersionCreated webhook. |
com.github.ben-manes.caffeine:caffeine | 3.2.4 | The two bounded caches inside SessionCookieKeyCache (per-version key material, and the negative-result cache for invalid kids). |
org.postgresql:postgresql | 42.7.11 (runtime) | JDBC driver behind AdvisoryLockService's pg_try_advisory_lock/pg_advisory_unlock calls. |
io.projectreactor:reactor-core | 3.8.6 | The reactive (Mono) API CredentialService, SessionCookieKeyRotationService, and AdvisoryLockService expose, with blocking Key Vault/JDBC calls offloaded onto Schedulers.boundedElastic(). |
com.fasterxml.jackson.core:jackson-databind (via spring-boot-starter-webflux) | 2.21.4 | Serializes/deserializes the SessionCookiePayload JSON that gets encrypted into the cookie, and parses Event Grid event data. |
Key Componentsβ
| Class | Responsibility |
|---|---|
CredentialService | Encrypts/decrypts the compact JWE. Stamps the encrypting key's Key Vault version into kid; on decrypt, resolves the version from kid rather than trying a fixed set of keys. |
SessionCookieKeyCache | Per-pod cache: the "current version" pointer (TTL-refreshed) and per-version key material (cached forever, since Key Vault versions are immutable). Hardens getKeyForVersion against an attacker-controlled kid β format validation, a bounded/short-TTL negative-result cache, and bounded cache sizes. |
KeyVaultSecretClient (+ AzureKeyVaultSecretClient / LocalKeyVaultSecretClient) | Abstraction over Key Vault secret operations: get a version's value, get/create the current version, disable a version, list all versions. AzureKeyVaultSecretClient runs everywhere except the local profile; LocalKeyVaultSecretClient is an in-memory stand-in for local dev. |
SessionCookieKeyRotationService | Owns rotation: generates a new AES-256 key and pushes it as a new Key Vault version when due; disables previous versions once their grace period has elapsed; reacts to externally-detected rotations (Event Grid). |
SessionCookieKeyRotationScheduler | Two cron schedules: a rotation due-check and a grace-period expiry sweep (see Key Rotation). |
KeyVaultSecretEventConsumer | Handles Microsoft.KeyVault.SecretNewVersionCreated Event Grid notifications (plus the Event Grid subscription-validation handshake) for near-instant pickup of a rotation, instead of waiting on the poll/TTL. |
AdvisoryLockService | PostgreSQL pg_try_advisory_lock-based, cluster-wide, non-blocking lock. Serializes concurrent pods so only one pushes a new key version per rotation. Lock resource: auth-service:session-cookie-key-rotation. |
SessionCookieEncryptionSafetyValidator | Fails startup (all profiles except local) if grace-period is too short relative to latest-version-ttl + the longest-lived protected payload's TTL β see Key Rotation. |
SessionCookieDecryptCli (src/test, dev tooling only) | Decrypts a cookie/JWE outside a running instance for local debugging; never ships in the deployable jar. |
Key Vault Configurationβ
Vault URLs (by environment)β
| Environment | Key Vault URL |
|---|---|
| dev / test / stage / reg / perf | https://fcc-comn-chkt-kv-dev.vault.azure.net/ |
| prod | https://ccg-comn-chkt-kv-prod.vault.azure.net/ |
Configured via the CCG-AZURE-KEYVAULT-URL env var (per-environment values-*.yaml), bound to
ccg.azure.keyvault.url. AzureConfig builds the Key Vault SecretClient from this URL using
DefaultAzureCredentialBuilder with the pod's managed identity (ccg.azure.credential.managedidentity.clientid) β
no client secret involved.
Secrets / variablesβ
| Name | Type | Purpose |
|---|---|---|
HSID-JWE-SECRET | Key Vault secret (versioned) | The session cookie / OIDC state encryption key itself. Base64-encoded, exactly 32 bytes (256-bit) decoded. Bound as oidc.hsid.encryption.secret-name (a literal secret name, not an injected value β the app reads the key material directly from Key Vault via the SDK, not from an env var). |
HSID-JWE-SECRET-ROTATION-SECONDS | Key Vault secret, optional | Ops-editable override of the rotation cadence (oidc.hsid.encryption.rotation-interval-override-seconds), in seconds. Absent/blank/non-numeric/non-positive falls back to the configured rotation-interval (90 days) β a hand-edited typo must degrade safely, not crash-loop the pod. Read once at startup; a pod restart is required to pick up a change. |
HSID-JWE-LEGACY-VERSION | Key Vault secret, optional | One-time cutover value (oidc.hsid.encryption.legacy-version): the exact Key Vault version that was current immediately before this feature's rollout, used as a decrypt fallback for kid-less cookies issued by the predecessor implementation. Unset in every environment today β only ever set for the single cutover deploy, then unset again. |
CCG-AZURE-KEYVAULT-URL | Plain env var (per environment, in values-*.yaml) | Key Vault endpoint URL β see table above. |
Application properties (oidc.hsid.encryption.*, config/helm/application.yaml)β
| Property | Default | Meaning |
|---|---|---|
secret-name | HSID-JWE-SECRET | Key Vault secret name backing the key. |
latest-version-ttl | 1m | How long the cached "current version" pointer is trusted before re-checking Key Vault. Per-version key material itself is cached forever (versions are immutable). |
rotation-interval | 90d | Scheduled rotation cadence β a Duration (e.g. 90d, 15m, 30s), not day-only, so lower environments can exercise rotation on a short cycle. |
rotation-interval-override-seconds | unset β falls back to rotation-interval | Key Vault-backed override, see HSID-JWE-SECRET-ROTATION-SECONDS above. |
rotation-check-cron | 0 0 2,14 * * * (twice daily) | How often the rotation-due check runs. A sub-day rotation-interval only has effect if this is also shortened β dev overrides both (see below). |
grace-period | 16m | How long a superseded key version stays enabled/decryptable after being rotated away, so in-flight cookies/state remain valid. Must be β₯ latest-version-ttl + the longest-lived protected payload TTL (checkout session cookie or OIDC state, both 15m today) β enforced at startup by SessionCookieEncryptionSafetyValidator. |
grace-period-check-cron | 0 * * * * * (every minute) | How often the grace-period expiry sweep runs (disables any enabled, non-current version past its grace period). |
legacy-version | unset | See HSID-JWE-LEGACY-VERSION above. |
advisory-lock.max-lease-duration (default 20m) is a separate, safety-net timeout: if a rotation holding the
advisory lock hasn't finished within this window, the lock is force-released so a stuck pod can't block rotation on
every other pod indefinitely.
Dev-only cadence overrideβ
values-dev.yaml overrides OIDC_HSID_ENCRYPTION_ROTATION_CHECK_CRON to run every 10 minutes (was every minute
during initial live-rotation testing) as a standing config choice β not a one-off to revert β so the full
Key Vault/RBAC/Event Grid rotation path can be re-exercised on demand in dev without a redeploy. dev's
HSID-JWE-SECRET-ROTATION-SECONDS can then be set to a short value (e.g. a few minutes) to make a rotation actually
become "due" within a reasonable testing window.
Secret formatβ
The Key Vault secret value (every version) must be a Base64-encoded 256-bit (32-byte) AES key:
openssl rand -base64 32
SessionCookieKeyRotationService generates new versions this exact way (SecureRandom, 32 bytes, Base64) when it
rotates.
Local developmentβ
The local Spring profile uses LocalKeyVaultSecretClient, an in-memory stand-in with no real Key Vault access β
versions are just an incrementing local-v<N> counter, so the rotation scheduler can still be exercised end-to-end
locally.
| Env var | Purpose |
|---|---|
SESSION_COOKIE_ENCRYPTION_LOCAL_KEY_BASE64 | Base64-encoded 256-bit AES key seeded as the initial local key version. Generate with openssl rand -base64 32. |
Observability (Rotation Logs)β
Structured event= log keys emitted by this feature (key versions are masked to their last 8 characters in every
log line):
ROTATION_INTERVAL_RESOLVEDβ the effective rotation interval logged once at startup.ROTATION_INTERVAL_OVERRIDE_INVALIDβHSID-JWE-SECRET-ROTATION-SECONDSwas set but non-numeric/non-positive; fell back to the configured default.ROTATION_INTERVAL_SHORTER_THAN_GRACE_PERIODβ startup warning (not a failure) when the effective rotation interval is shorter than the grace period.KEY_ROTATION_STARTED/KEY_ROTATION_COMPLETEDβ a scheduled rotation actually pushed a new version.KEY_ROTATION_NOT_DUEβ scheduled check ran, but the current version hasn't aged out yet.KEY_ROTATION_SKIPPEDβ another pod already held the advisory lock.KEY_ROTATION_EXTERNAL_VERSION_DETECTEDβ an Event Grid notification refreshed this pod's cached current version.KEY_ROTATION_PREVIOUS_VERSION_DISABLED/KEY_ROTATION_PREVIOUS_VERSION_DISABLE_FAILEDβ grace-period sweep outcome for a specific version.KEY_ROTATION_GRACE_PERIOD_SWEEP_COMPLETEDβ a sweep disabled at least one version.KEY_VAULT_SECRET_VERSION_PUSHED/KEY_VAULT_SECRET_VERSION_DISABLEDβ raw Key Vault write operations (AzureKeyVaultSecretClient).LEGACY_KID_LESS_COOKIE_FALLBACK_ATTEMPTED/LEGACY_KID_LESS_COOKIE_REJECTEDβ akid-less cookie from before this feature was seen; expected only in a short window around the cutover deploy.ADVISORY_LOCK_ACQUIRED/ADVISORY_LOCK_BUSY/ADVISORY_LOCK_RELEASED/ADVISORY_LOCK_LEASE_EXPIREDβ advisory lock lifecycle.
Error Handlingβ
All encrypt/decrypt failures from CredentialService are wrapped in CredentialEncryptionException (unchecked).
SessionCookieService translates these into AuthorizationException (HTTP 401) with legacy messages:
| Cause | Result |
|---|---|
| No cookie / blank credential | AuthorizationException: "HSID POST Auth credential is required for IDP_REQUIRED sessions" |
| Decrypt failure (bad/disabled key version, tampered/malformed JWE) | AuthorizationException: "HSID POST Auth credential decryption failed" |
| Valid JWE, unexpected payload shape | AuthorizationException: "HSID POST Auth credential format is invalid" |
expiresAt has passed | AuthorizationException: "HSID POST Auth Session Cookie has expired" |
Claim mismatch (sessionId / merchantId / customerId) | AuthorizationException: "HSID POST Auth credential <field> does not match the request" |
kid version resolves to a Key Vault 4xx (not found / disabled) | SecretVersionUnavailableException, negative-cached for 5 minutes |
kid version resolves to a Key Vault 5xx or 429 (throttling) | Propagated as-is on every call, never negative-cached (a transient blip must not become a multi-minute outage) |
| Key material not valid Base64, or not exactly 32 bytes decoded | CredentialEncryptionException |
Testingβ
SessionCookieKeyRotationServiceTestβ rotation due/not-due boundaries, grace-period expiry boundaries, advisory-lock skip path.SessionCookieKeyRotationSchedulerTestβ cron-triggered calls into the rotation/sweep services, error swallowing.SessionCookieKeyRotationLifecycleTestβ end-to-end: a 90-day-old key β realrotate()β decrypt succeeds during the grace period β grace period elapses β version disabled β decrypt rejected, wiring the realCredentialService,SessionCookieKeyCache, andSessionCookieKeyRotationServiceagainst an in-memory Key Vault stand-in (no mocking of the classes under test).AzureKeyVaultSecretClientTestβ real Azure SDKSecretClientagainst a WireMock stub of the Key Vault REST API, verifying the actual get/push/disable/list-versions HTTP contract.KeyVaultSecretEventConsumerTest/EventGridKeyVaultWebhookIntegrationTestβ Event Grid payload handling, including real JSON deserialization through the actual controller route.SessionCookieDecryptCliTestβ the local debugging CLI.