Automation

Azure Cosmos DB: validate key rotation before cutting off consumers

A production runbook for inventorying consumers, moving between primary and secondary keys, using recent-usage checks, and choosing rotation, hold or rollback without exposing secrets.

23 Oct 2026 azurecosmos-dbkey-rotationidentitykey-vaultsecurityautomationobservabilitycanaryrunbookrollbackproduction

An Azure Cosmos DB account key must be renewed after a security alert or during a planned rotation. The account has a primary and a secondary key, yet nobody can confidently say which one is used by the API, the nightly worker, the recovery pipeline and a rarely executed connector. Regenerating the wrong key can turn a security operation into a distributed authentication outage.

This runbook follows an application that still uses account keys while it migrates to Microsoft Entra ID. The goal is not to copy a new value everywhere. It is to prove the consumers, move traffic to a validated fallback key, wait until the old key is no longer used, then decide whether to regenerate it, hold the change or return to the previous contract.

Freeze the contract before touching either key

Name the account, the four possible key types and every known consumer. Never place a raw key or full connection string in this record, a ticket, a pipeline log or retained terminal output.

yaml cosmos-key-rotation-contract.yml
change: CHG-COSMOS-1023
account: cosmos-orders-prod
resource_group: rg-data-prod
api: NoSQL

consumers:
- name: orders-api
  credential_ref: kv-prod/cosmos-orders-active
  current_key_slot: primary
  reload_mode: rolling_restart
  owner: application
- name: reconciliation-job
  credential_ref: variable-group/cosmos-orders-active
  current_key_slot: primary
  reload_mode: next_run
  owner: finance-platform

rotation:
target_to_regenerate_first: secondary
observation_window: 12h minimum
canary_partition: rotation-canary
rollback_owner: on-call-data

forbidden_evidence:
- raw_account_key
- full_connection_string
- secret_value_in_pipeline_log

The inventory must cover applications, jobs, recovery scripts, SaaS integrations, pipeline variables, Key Vault secret versions and administrative workstations. A yearly dependency is still a dependency. The recent-usage check does not replace this inventory: it cannot prove that a dormant workload will not reuse the key next month.

Verify the safe-rotation capability

Azure Cosmos DB can evaluate account-key usage metadata before regenerating a key or disabling local authentication. Capture the account capabilities and disableLocalAuth state first, without listing keys.

bash 01-check-safe-rotation-capabilities.sh
set -euo pipefail

RG="rg-data-prod"
ACCOUNT="cosmos-orders-prod"

az cosmosdb show --resource-group "$RG" --name "$ACCOUNT" --query "{id:id,disableLocalAuth:disableLocalAuth,capabilities:capabilities[].name}" --output json > cosmos-rotation-capabilities.json

jq . cosmos-rotation-capabilities.json

If safe rotation needs enabling, treat the capability update as a reviewed, versioned platform change. Then confirm that EnableAccountKeysLastUsageCheckInDisableLocalAuth and EnableKeyCheckBeforeRegenerationPreview are present in the target environment. Capability names may retain historical preview wording; make the decision from the documentation and API available in your tenant, not from an assumption based on the name.

bash 02-enable-recent-usage-check.sh
az cosmosdb update --resource-group "$RG" --name "$ACCOUNT" --capabilities   EnableAccountKeysLastUsageCheckInDisableLocalAuth   EnableKeyCheckBeforeRegenerationPreview

az cosmosdb show --resource-group "$RG" --name "$ACCOUNT" --query "capabilities[].name" --output tsv

Do not run az cosmosdb keys list to create evidence: it returns secrets. Limit regeneration permission to the change identity, and retain only the operation identifier, actor, targeted key slot and result.

Prepare a fallback key that actually works

When every consumer uses the primary key, begin with the secondary. Regenerate the unused secondary key while the primary remains valid, place the new value in the approved secret manager, then test one canary consumer. The value must not travel through a visible command argument or a persistent working file.

text primary-secondary-cutover-sequence.txt
Phase 1 - prepare
Regenerate the unused secondary key
Publish a new version of the credential reference
Change no production consumer yet

Phase 2 - canary
Point one instance to the secondary key
Force an explicit configuration reload
Execute a read, write and confirmation read

Phase 3 - migrate
Move consumers in bounded batches
Monitor 401/403, availability and latency
Keep the primary key intact during the return window

Phase 4 - close
Wait at least for the recent-usage observation window
Exercise infrequent jobs scheduled within the window
Regenerate primary only when the evidence agrees

A new secret version does not prove that the process loaded it. Record the version actually resolved by the canary, or a non-reversible fingerprint produced inside a trusted component. Also prove the reload mechanism: rolling restart, configuration refresh, new pod or the job’s next execution.

Canary a bounded data-plane effect

The canary must use the real SDK path and application identity. A TCP probe or endpoint lookup does not validate authentication. Use a dedicated container and partition, an expiring synthetic document and a unique correlation identifier.

yaml cosmos-key-canary-evidence.yml
canary_id: cosmos-key-rotate-1023-a
consumer: orders-api-canary
credential_slot: secondary
secret_version: <non-secret-version-id>
operations:
- create_item_in_rotation_canary_partition
- read_item_by_partition_key
- delete_item
expected:
http_status: [200, 201, 204]
unauthorized_count: 0
duplicate_items: 0
production_business_write: false
evidence:
- application_trace_id
- cosmos_request_charge
- secret_version_id
- deployment_revision

Run a negative-path control as well: an instance still using primary must remain healthy during migration. If both paths are not healthy at the same time, the rotation does not yet have a credible rollback window.

Observe the cutover without logging the secret

Build one timeline from deployments, restarts, authentication failures and Azure control-plane operations. Application traces may carry the logical key slot and secret version, never the value.

kusto 03-track-authentication-failures.kql
let Start = datetime(2026-10-23T06:00:00Z);
let End = datetime(2026-10-23T20:00:00Z);
union isfuzzy=true requests, dependencies, exceptions, traces
| where timestamp between (Start .. End)
| where cloud_RoleName startswith "orders-"
| extend CredentialSlot = tostring(customDimensions["CredentialSlot"]),
       SecretVersion = tostring(customDimensions["SecretVersion"])
| where resultCode in ("401", "403")
  or message has_any ("Unauthorized", "Forbidden")
| summarize Failures=count(), Instances=dcount(cloud_RoleInstance)
  by bin(timestamp, 5m), cloud_RoleName, CredentialSlot, SecretVersion
| order by timestamp asc

Correlate this view with AzureActivity to identify who requested regeneration and when the resource operation completed. Regeneration can take time; do not start a second operation merely because the first change is not immediately visible to the application.

Respect the twelve-hour gate

When safe rotation finds that the targeted key was used in the previous twelve hours, regeneration is blocked and the existing key remains valid. That refusal is useful evidence, not an error to bypass. Find the lagging consumer, move it to secondary, then restart the observation period.

The option that skips this check is not a maintenance shortcut. In production, using it requires a separate emergency procedure, independent evidence that no consumer depends on the key and explicit risk acceptance. Without those controls, wait.

Decide: rotate, hold or roll back

text cosmos-key-rotation-decision-gate.txt
Regenerate primary
Every inventoried consumer uses secondary
The read/write canary is healthy under secondary
No new 401 or 403 appears in the observation window
The recent-usage check permits the operation
Infrequent jobs covered by the window were exercised

Hold
A consumer or secret version remains unknown
Primary still appears as recently used
A dormant job cannot be tested
Telemetry cannot distinguish key slots

Roll back before primary regeneration
Move affected batches back to the still-valid primary
Restore the previous credential reference version
Prove recovery, then repair the secondary path

Contain after primary regeneration
Do not try to restore the old value: it is invalid
Keep consumers on the valid secondary
Cancel deployments that still reference the old primary
Distribute the new primary only after a fresh canary

After primary is regenerated, run a fresh canary with a new identifier. Do not immediately regenerate secondary: it is still the stable path. The rotation is complete only after the new primary has been validated, the fleet can return to it in batches, and the previous secret has been revoked from distribution systems.

Plan the exit from shared keys

Safe rotation reduces outage risk, but it does not turn a shared account key into a traceable identity. For Azure Cosmos DB for NoSQL, move compatible applications toward Microsoft Entra ID and minimum data-plane roles. Disable local authentication in a separate change only after proving that no key consumer remains.

Conclusion

A Cosmos DB rotation is safe when the team knows who consumes each slot, can exercise the fallback key through the real application path and treats a recent-usage refusal as a gate. Until primary is regenerated, it remains a rollback. After regeneration, secondary becomes the anchor and the former primary value cannot be recovered.

The final decision must therefore be explicit: regenerate on converging evidence, hold while finding a consumer, or return to the still-valid key before the irreversible step.