# Key expiry, tags and lifecycle policy

**Last updated:** 2026-11-21T10:44:38-03:00 (UTC-3)

A key can have **no expiration**, an explicitly selected duration or an absolute UTC deadline. Creation and rotation default to **Never**. An operator policy can limit a duration the user explicitly selects; it never makes a nonexpiring choice expire. There is no automatic90-day default or mandatory1-year rotation ceiling.

## Choose an expiry

For managed creation or immediate rotation, send at most one of:

| Choice | Request |
| --- | --- |
| Never | Omit both expiry fields, or send one as `null` |
| Relative duration | `"expires_in": "7d"` |
| Absolute date | `"expires_at": "2030-04-20T15:30:00Z"` |

`expires_in` accepts a positive integer followed by `s`, `m`, `h`, `d` or `w`, within the published signed-duration representation bound. Empty strings, zero, negative, fractional and overflowing durations are rejected. Both field names together are rejected even when one is null. Absolute dates must be valid RFC3339 timestamps after the database clock; timezone offsets are compared as UTC instants. Responses may carry a valid RFC3339 offset; compare the instant rather than a string prefix. The API supports fractional precision; the console preserves an existing timestamp when it is untouched rather than silently rounding it.

Relative time uses PostgreSQL time after the mutation locks, not the browser or gateway host clock. A configured finite maximum rejects an excessive selected expiry; it does not clamp it or inject an expiry into Never. With no maximum, there is no configured lifetime ceiling; a syntactically representable future absolute date remains a user choice.

**In Virtual keys:** choose Never, Duration or Date in the creation/rotation form. The date field is explicitly UTC. Switching to Never clears the other choice; a hidden stale field cannot quietly keep an expiry active.

For [scheduled rotation](/docs/features/key-rotation/#scheduled-activation), a relative duration begins at **actual activation**. An absolute date stays fixed; an activation delayed beyond that date is blocked without retiring the old credential.

## Declarative defaults

```yaml
features:
  key_policies: false
  key_metadata_tags: false
  scheduled_key_rotation: false
  key_expiry_warnings: false
security:
  key_policy:
    max_expiring_lifetime: 0s
    require_owner: false
    required_tags: []
  key_lifecycle:
    interval: 30s
    state_timeout: 5s
    batch_size: 100
    warning_before: [168h, 24h, 0s]
```

The four flags default off. Policy and warning processing are operator controls; metadata tags and scheduling also require applicable tenant/organization plan rights and the action's live permissions. A flag grants no permission. Scheduling requires the existing `key_rotation` feature; creation still uses `identity_management`.

The compiled defaults work without declaring these blocks. An explicit YAML value wins over its default; a versioned console/API override wins over the YAML until reverted. File edits need rollout; the managed override applies through normal replica refresh. New operations capture the effective policy. The console shows effective values, defaults, source and override/base conflicts; metadata never proves a worker or notification succeeded.

## Governance policy

Keys of the `security.key_policy` block:

| Setting | Default | Meaning |
| --- | --- | --- |
| `security.key_policy.max_expiring_lifetime` | `0s` | No finite maximum. A nonzero single-unit duration constrains only an explicitly expiring managed issuance |
| `security.key_policy.require_owner` | `false` | Optional prospective requirement for an active authorized owner |
| `security.key_policy.required_tags` | `[]` | Optional required static key-tag names; at most16 unique valid names |

This is a global policy. It does not add another team-policy override system. Existing team model/scope limits remain cumulative and unchanged.

Full governance is checked on managed creation, immediate rotation and scheduled activation. Enabling a requirement does not silently revoke existing traffic. A legacy key missing both owner and tags can be repaired one field at a time: owner changes check the owner requirement; tag changes check tag requirements. Untouched legacy drift remains visible until repaired. A required valid owner/tag cannot be removed, and full issuance/rotation waits until all requirements are satisfied.

Owner assignment retains its existing global-administrator authority. Static tag edits use the existing scoped `keys:rotate` authority, plus the metadata feature and applicable plan/license ceilings; this grants no model, route, team membership or console role. Operators retain their established lack of key-management authority.

A required-tag policy can be staged with `key_policies` off. Activating it requires `key_metadata_tags`; whole-configuration validation prevents turning off that feature beneath an active requirement. The same applies to the existing ownership feature when requiring an owner. Existing tag metadata is preserved when controls are off. Explicit tag writes and clears remain guarded; omission in unrelated actions preserves authoritative metadata.

## Static key tags

Tags are administrative metadata on the key, such as:

```json
{"app":"support-api","environment":"production"}
```

At most16 name/value pairs are accepted, each using the published64-byte token grammar. Keep secrets out of tags. These are separate from client-supplied `X-Gateway-Tags`, request attribution requirements, routing conditions and spend tracking; the gateway never copies them into those surfaces or telemetry.

`GET /api/v1/admin/keys/{id}/tags` returns the key ID, tags, current `version` and a safe write capability. `PUT` replaces the map with that captured version. A conflicting edit returns409; it never overwrites an unseen change. Team access is checked before returning metadata, and IDs from other teams remain404.

## Policy API and console

The global editor lives in **Virtual keys**. Authorized administrators edit; global readers inspect. Scoped users receive only safe applicable policy/action notices, never the global override or lifecycle administration.

| Endpoint | Action |
| --- | --- |
| `GET /api/v1/admin/security/key-policy` | Effective policy/lifecycle, defaults, sources, base fingerprints and safe edit rights |
| `PUT /api/v1/admin/security/key-policy` | Save an override with current `version` and `expected_base_fingerprint` |
| `DELETE /api/v1/admin/security/key-policy` | Revert to YAML/defaults with the same guards |

Writes retain live role/license checks, global CAS, same-origin session/CSRF and audit. Equivalent duration units have the same baseline identity; a real YAML policy change requires explicit review of a stale override. A draft never silently rebases after409 or survives known permission loss. Reload after restoring access.

## Expiry notifications

Keys of the `security.key_lifecycle` block:

| Lifecycle setting | Default | Bounds |
| --- | --- | --- |
| `security.key_lifecycle.interval` | `30s` | 1s–1h |
| `security.key_lifecycle.state_timeout` | `5s` | 100ms–1m, whole milliseconds; one state operation |
| `security.key_lifecycle.batch_size` | `100` | 1–1000 |
| `security.key_lifecycle.warning_before` | `[168h,24h,0s]` | At most8 unique thresholds,0–8760h; empty disables notices |

With `key_expiry_warnings`, the worker records durable notices for the current explicitly expiring managed credential. Never produces no expiry event. The zero threshold is an expired notice, so a missed earlier window can still produce an accurate event after recovery.

Events are deduplicated by key, credential generation, actual expiry and threshold, then delivered through existing [alert channels](/docs/features/alerting/). Payloads contain identifiers/deadlines and request/trace correlation, never a secret, confirmation nonce, arbitrary tag value or inference content. External channels require their existing flags, policy and configuration; generating an event does not certify delivery. The console/audit/delivery state makes these stages distinct.

Disabled processing pauses future evaluation; it never changes a credential's chosen deadline or revocation. Existing notification retry/delivery semantics apply; a transport retry does not create another expiry event.

## YAML bootstrap keys

Static keys can declare an optional fixed deadline:

```yaml
keys:
  - id: local-app
    principal: example-app
    team: platform
    kind: service_account
    sha256_env: GATEWAY_CLIENT_KEY_SHA256
    allowed_models: [chat-default]
    scopes: [route:chat]
    expires_at: 2030-04-20T15:30:00Z
```

Omit it for no expiration. A static deadline is startup-owned and read-only in the console; edit YAML and roll out. There is no relative boot duration that renews on restart. Managed secret issuance and confirmation remain authenticated API/console actions; YAML does not execute a secret issuer or bypass possession confirmation.

## Upgrade and recovery

Upgrade all replicas before using the new flags/fields, back up PostgreSQL and apply the new key-lifecycle migration through the existing [procedure](/docs/operate/operations/). Earlier binaries cannot enforce or interpret the new schema/profile; use the pre-upgrade backup/configuration procedure for rollback.

Authentication still applies credential expiry, parent/team revocation, ownership, route/model rights and existing cache visibility. Pending prepared credentials never authenticate. No policy makes an expired or revoked credential valid again. See [rotation](/docs/features/key-rotation/) for lost-response recovery, cancellation and the safe handoff sequence.

## Admin API routes

Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/).

| Route | What it does |
| --- | --- |
| `PUT /api/v1/admin/keys/{id}/tags` | Replaces a key's static metadata tags; `{}` clears them |
