Checking access…

Skip to main content
Audience: CCG Platform Engineers

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.

AttributeValue
Name__Host-wallet_session (Constants.WALLET_SESSION_COOKIE_NAME)
HttpOnlytrue
Securetrue
SameSiteLax
Path/
Max-AgeTime remaining until the checkout session's expiresAt
ValueCompact 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:

  • expiresAt has not passed,
  • customerId, sessionId, and merchantId claims 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):

LibraryVersionUsed for
com.nimbusds:nimbus-jose-jwt9.37.2JWE construction/parsing (JWEObject, JWEHeader) and the DIR/A256GCM encrypt/decrypt primitives (DirectEncrypter/DirectDecrypter) in CredentialService.
com.azure:azure-security-keyvault-secrets4.8.6SecretClient β€” the actual Key Vault REST calls in AzureKeyVaultSecretClient (get/set/list/disable secret versions).
com.azure:azure-identity1.12.2DefaultAzureCredentialBuilder with managed-identity client ID β€” how the pod authenticates to Key Vault (no client secret).
com.azure:azure-messaging-eventgrid4.24.0EventGridEvent deserialization in KeyVaultSecretEventConsumer for the SecretNewVersionCreated webhook.
com.github.ben-manes.caffeine:caffeine3.2.4The two bounded caches inside SessionCookieKeyCache (per-version key material, and the negative-result cache for invalid kids).
org.postgresql:postgresql42.7.11 (runtime)JDBC driver behind AdvisoryLockService's pg_try_advisory_lock/pg_advisory_unlock calls.
io.projectreactor:reactor-core3.8.6The 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.4Serializes/deserializes the SessionCookiePayload JSON that gets encrypted into the cookie, and parses Event Grid event data.

Key Components​

ClassResponsibility
CredentialServiceEncrypts/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.
SessionCookieKeyCachePer-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.
SessionCookieKeyRotationServiceOwns 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).
SessionCookieKeyRotationSchedulerTwo cron schedules: a rotation due-check and a grace-period expiry sweep (see Key Rotation).
KeyVaultSecretEventConsumerHandles 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.
AdvisoryLockServicePostgreSQL 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.
SessionCookieEncryptionSafetyValidatorFails 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)​

EnvironmentKey Vault URL
dev / test / stage / reg / perfhttps://fcc-comn-chkt-kv-dev.vault.azure.net/
prodhttps://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​

NameTypePurpose
HSID-JWE-SECRETKey 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-SECONDSKey Vault secret, optionalOps-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-VERSIONKey Vault secret, optionalOne-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-URLPlain env var (per environment, in values-*.yaml)Key Vault endpoint URL β€” see table above.

Application properties (oidc.hsid.encryption.*, config/helm/application.yaml)​

PropertyDefaultMeaning
secret-nameHSID-JWE-SECRETKey Vault secret name backing the key.
latest-version-ttl1mHow 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-interval90dScheduled 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-secondsunset β†’ falls back to rotation-intervalKey Vault-backed override, see HSID-JWE-SECRET-ROTATION-SECONDS above.
rotation-check-cron0 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-period16mHow 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-cron0 * * * * * (every minute)How often the grace-period expiry sweep runs (disables any enabled, non-current version past its grace period).
legacy-versionunsetSee 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 varPurpose
SESSION_COOKIE_ENCRYPTION_LOCAL_KEY_BASE64Base64-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-SECONDS was 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 β€” a kid-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:

CauseResult
No cookie / blank credentialAuthorizationException: "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 shapeAuthorizationException: "HSID POST Auth credential format is invalid"
expiresAt has passedAuthorizationException: "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 decodedCredentialEncryptionException

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 β†’ real rotate() β†’ decrypt succeeds during the grace period β†’ grace period elapses β†’ version disabled β†’ decrypt rejected, wiring the real CredentialService, SessionCookieKeyCache, and SessionCookieKeyRotationService against an in-memory Key Vault stand-in (no mocking of the classes under test).
  • AzureKeyVaultSecretClientTest β€” real Azure SDK SecretClient against 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.