# Managed credential cache

**Last updated:** 2026-11-22T06:50:00-03:00 (UTC-3)

The optional managed credential cache reduces repeated authentication lookups for previously verified managed bearer keys. It keeps bounded private snapshots in the running gateway process. It does not cache prompts, model responses, administrative sessions or cleartext API keys, and needs no additional cache service.

The default is unchanged: `features.managed_key_cache: false`, fresh TTL `0s` and stale-on-database-error window `0s`. Valid managed credentials are checked against PostgreSQL on each request by default; the existing short negative cache for unusable credentials remains separate.

## Configure the profile

```yaml
features:
  managed_key_cache: true
security:
  managed_key_cache:
    ttl: 5s
    stale_on_database_error: 0s
    max_entries: 4096
    max_bytes_mib: 8
```

This example enables a five-second fresh authentication cache. Stale acceptance remains off. An operator may explicitly select a bounded stale window, for example `30s`, when the limited availability profile below is appropriate. A flag enables behavior; it never grants routes, models, a team, a role or a plan right.

| Parameter | Default | Accepted values |
| --- | --- | --- |
| `features.managed_key_cache` | `false` | Operator control; YAML, feature API and **Settings & sources** |
| `security.managed_key_cache.ttl` | `0s` | Go duration 0–60s, in whole milliseconds; empty means 0s |
| `security.managed_key_cache.stale_on_database_error` | `0s` | Go duration 0–5m, in whole milliseconds; empty means 0s |
| `security.managed_key_cache.max_entries` | `4096` | Effective 1–65536; omitted/raw 0 selects 4096 |
| `security.managed_key_cache.max_bytes_mib` | `8` | Effective 1–64 MiB; omitted/raw 0 selects 8 |

Unknown/duplicate/wrong-case/null fields and fractional or nondecimal capacity inputs are refused. YAML uses a natural mapping with typed values. PUT replaces the complete four-field policy; it is not a partial patch. Effective durations are normalized. Cache byte accounting bounds retained snapshots; it is not a measurement of the process's resident memory.

## Which lookups are eligible

The profile applies to **new plain managed-bearer authentication lookups** with a PostgreSQL-produced credential deadline proof. It never invents an identity for an unknown key. Readers that do not supply the required proof remain live. Declared YAML keys keep their existing behavior; JWT mapping, ephemeral realtime issuing-key validation and administrative sessions keep their live checks.

Positive caching is bypassed whenever any feature below is on, even if a particular key appears to have no requirements or owner:

- `attribution_requirements`: key/team attribution rules must stay authoritative so a new end-user requirement cannot be missed.
- `identity_ownership`: financial ownership must stay authoritative so a rebind cannot charge an old owner or miss a new owner's budget.
- `mcp_user_oauth`: selecting a user's OAuth credential must use the current key owner, including when financial ownership is off.
- `source_ip_controls`: a newly tightened managed-key source ceiling must be read from the authoritative lookup; an older unrestricted cache entry cannot grant admission.

The normal team, organization, RPM, quota and plan checks also remain live. If they need PostgreSQL and it is unavailable, the request still fails closed even when authentication used a cached snapshot. Enabling the cache therefore does not promise that every inference survives a database outage. The safe policy panel explains each bypass reason.

## Freshness, failures and revocation

A successful lookup anchors both windows at the **start of that lookup**. Fresh hits may use that snapshot before its TTL ends. Afterward, a stale snapshot may be used only after an actual permitted transient database/network failure or internal database lookup timeout, and only while the original request is still active. With TTL 0 and a positive stale window, healthy requests keep refreshing storage; there is no fresh-hit window.

For example, a five-second TTL plus 30s stale allowance permits at most 35s of cache-induced age from that successful lookup's start. A credential that expires or retires earlier wins: the cache never extends its deadline. The proof uses the same credential SQL's earliest expiry/retirement and database observed time, combined with local elapsed/wall deadlines. Slow reads, hits, retries, failed refreshes, ordinary host suspend or wall-clock changes cannot renew acceptance.

Authoritative absence/revocation, caller cancellation, exhausted lookup admission and nontransient SQL authorization/schema failures never authorize stale fallback. An expired proof is unusable. A successful refresh replaces the snapshot; a failed refresh does not move either deadline forward. Database recovery returns requests to normal authoritative lookup/refresh.

The replica handling a successful authentication-affecting key/team/owner mutation invalidates its local state and fences older in-flight fills. Other replicas may retain a previously verified snapshot until its explicit cache window and credential deadline expire; there is no immediate cross-replica revocation guarantee for this opt-in profile. The bound concerns this cache, not replication lag in an independently configured database. Use the authoritative PostgreSQL endpoint for identity decisions.

Snapshots and results are deep-cloned. Digests, private proof metadata and mutable caller fields cannot leak through shared returned objects. Plaintext bearers are never retained, logged, exported or persisted by the cache. Restart loses every positive entry; a cold process cannot authenticate an uncached managed key during a database outage. PostgreSQL remains mandatory at startup and for the platform's persistent state.

## Manage through the console or API

**Settings & sources → Managed credential cache** shows the configured/effective policy, source, reviewed base, eligibility and process-local counters. A global administrator may stage a policy while the operational flag is off. Global viewers and operators get the safe read-only panel; operators do not gain access to unrelated configuration panels or private values. Conflicts preserve the originally reviewed version/fingerprint until explicit reload and review. Loss of authority discards pending edits and rejects late replies.

| Method | Endpoint | Purpose |
| --- | --- | --- |
| `GET` | `/api/v1/admin/security/managed-key-cache` | Safe effective policy, source, eligibility and local counters |
| `PUT` | Same | Replace all four fields with global version and current YAML semantic fingerprint |
| `DELETE` | Same | Revert the policy to YAML/defaults with both guards |

Writes require global administrator `features:manage`, the existing same-origin session and CSRF controls. Successful PUT/DELETE returns 204; fetch GET afterward for the new version/state. A scoped inference key does not authorize these administrative routes.

GET returns `version`, `base_fingerprint`, `stored_base_fingerprint`, `base_mismatch`, `source` (`default`, `yaml`, `console`), `override` (policy or null), normalized `effective` (`ttl`, `stale_on_database_error`, `max_entries`, `max_bytes_mib`; the console shows the capacity as **Effective capacity**), `enabled`, `active`, `bypass_reasons`, `restart_required: false`, `applies_to: new_managed_bearer_lookups` and `cache`. Here `enabled` is the operational flag and `active` means policy eligibility, not healthy storage, a valid current credential or a permission grant. Finite bypass reasons are `feature_disabled`, `zero_windows`, `attribution_requirements`, `identity_ownership`, `mcp_user_oauth`, `source_ip_controls` and `base_mismatch`.

`cache` contains `entries`, accounted `bytes`, `hits`, `misses`, `stale_hits` and `evictions` for the serving replica/cache instance. A stale authentication hit is not proof that subsequent policy checks or inference succeeded. Counters contain no key IDs, digests, tokens or tenant inventory and do not aggregate other replicas.

### Complete policy update example

Use your existing authenticated console cookie file and CSRF token. The snapshot contains safe policy metadata only; both guards come from that exact read.

```sh
BASE_URL='http://localhost:8080'
: "${COOKIE_JAR:?Set the authenticated console cookie file}"
: "${CSRF_TOKEN:?Set the session CSRF token}"
SNAPSHOT=$(mktemp)
trap 'rm -f "$SNAPSHOT"' EXIT
curl --fail-with-body -sS -b "$COOKIE_JAR" \
  "$BASE_URL/api/v1/admin/security/managed-key-cache" > "$SNAPSHOT"
python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); json.dump({"version":s["version"],"expected_base_fingerprint":s["base_fingerprint"],"managed_key_cache":{"ttl":"5s","stale_on_database_error":"0s","max_entries":4096,"max_bytes_mib":8}},sys.stdout)' "$SNAPSHOT" | \
  curl --fail-with-body -sS -b "$COOKIE_JAR" -X PUT \
    -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \
    --data-binary @- "$BASE_URL/api/v1/admin/security/managed-key-cache"
```

Review the policy before executing it. It does not enable the flag. For DELETE, submit only `version` and `expected_base_fingerprint` from the current GET. Authentication/CSRF/permission failures retain their usual 4xx; version or base mismatch returns 409; invalid policy is refused; storage/control refresh failure returns 503. No secret is part of this policy API.

## Policy changes and recovery

A policy publication flushes local positive state, including an explicit identical PUT. Other replicas apply the new control version through the existing refresh loop. Requests with older captured configuration cannot reconfigure the shared cache backward. New policies apply to new lookups without a restart; existing admitted requests retain their normal operation semantics.

A semantic YAML base change does not silently preserve a broader console override: `base_mismatch` disables positive cache use/fill and shows the desired override for review. Explicitly review/save against the current fingerprint, or DELETE to revert. Flags, sensitive-feature bypasses and credential proof remain separate gates.

Migration 117 adds only the dedicated typed policy override. Use the normal backup/migration procedure before the new release when automatic migration is off. Upgrade all replicas before enabling the feature. No cache entries, bearer secrets or deadline proofs are stored in that table. Older binaries do not understand the new configuration/schema; use the established pre-upgrade backup/configuration rollback procedure. Real local PostgreSQL and controlled gateway/provider fixtures validate this boundary; they do not certify an external provider account or a managed-cloud deployment.

## 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/security/managed-key-cache` | Replaces the managed key cache policy at the current version |
| `DELETE /api/v1/admin/security/managed-key-cache` | Reverts the cache policy to the YAML and drops this replica's cached positive answers |

## See also

- [Access control](/docs/features/access-control/) and [credential rotation](/docs/features/key-rotation/).
- [Financial ownership](/docs/features/identity-ownership/) and [attribution/budget controls](/docs/features/quota-governance/).
- [Response cache](/docs/features/feature-cache/), a separate feature.
