mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
## Why On a proxy shared by several callers, the semantic response cache was keyed only by request content and upstream (#3349). A second caller who sent the identical request with a different provider key was served the completion generated for the first caller, under the first caller's key, and never reached the upstream. That discloses completions across tenants (finding 01-F15). ## What changes - `compute_cache_partition()` in `headroom/proxy/semantic_cache_key_policy.py`: an HMAC-SHA256 under a per-process random key over the caller's credential and account-selector headers plus the authenticated principal. Headers counted: every header the shared credential-header rule (`internal_header_policy.is_credential_header`) matches, which covers `authorization`, `proxy-authorization`, `cookie` and `x-api-key`, and any header whose name ends in `api-key`, `key`, `token`, `secret`, `account`, `account-id`, `organization` or `project` (so `x-api-key`, `api-key`, `x-goog-api-key`, `chatgpt-account-id`, `openai-organization`, `openai-project` and so on). Matching by name shape keeps new providers partitioned by default. Cookie is used as a whole value; it is only ever HMAC input. `x-headroom-*` headers (including the proxy's own token, which the security gate has already removed) and idempotency keys are excluded. A request with no credential and no principal gets the shared `anon` partition. - The partition is an HMAC, not a plain hash, so it cannot be used to confirm a guessed credential. - `identity.resolve_authenticated_principal()` returns a principal only when an identity resolver is installed (`set_identity_resolver`). The OSS default identity is the same for every network caller and can be chosen by header on loopback, so it is not treated as a principal. - If an installed identity resolver raises or returns no principal, the request fails closed (`resolve_authenticated_principal()` raises `UnresolvedPrincipalError` for an empty result): `compute_request_cache_partition()` logs a warning and returns `None`, and both handlers skip the response cache for that request (no lookup, no store). It never falls back to the credential-only partition, which tenants on one operator key would share. With no resolver installed, the credential-only partition is unchanged. - Both handlers compute the partition only when the response cache can be used (cache enabled and non-streaming), so streaming and cache-disabled requests do not call the identity resolver. - `partition` is a required keyword on `SemanticCache.get`, `set` and `_compute_key`, and on `compute_semantic_cache_key`. A future call site that forgets it fails immediately instead of silently sharing. - The `/v1/messages` and `/v1/chat/completions` handlers compute the partition once, next to the existing cache-key snapshot, and reuse it at store time so lookup and store agree. Other caches in the request path are not changed. The OpenAI Responses unit cache and the CCR retrieval store are content-addressed, so a hit requires already holding the content. CCR entries are not bound to a caller; that is a separate issue. The `/v1/compress` pipeline cache holds no user content, and the SDK `SemanticCache` is in-process for one caller. ## Behaviour change The proxy response cache no longer shares entries between callers that present different provider credentials or, with an identity resolver installed, different principals. - One developer with one key: same hit rate. - Deployments where callers send no provider credential and the proxy supplies the operator's key: same hit rate; they share the `anon` partition. - Shared proxy with per-caller keys: entries are no longer shared between keys. That is the fix. - Compatible upstream gateways that authenticate by `Cookie` or `Proxy-Authorization`: entries are no longer shared between sessions. - Callers whose only credential is a proxy-token `Authorization` header, or deployments using oauth2, share one partition unless an identity resolver is installed, because core cannot tell them apart. ## Tests `tests/test_proxy_response_cache_partition.py`: - The partition function: differs per credential and is stable for one credential; every credential and account header shape partitions; other headers do not fragment the cache; no credential and no principal gives the shared partition; it is keyed, not a plain hash; a principal separates callers sharing one credential. - `SemanticCache` refuses a call without a partition and keeps partitions apart. - End to end through the real Anthropic and OpenAI handlers: a second caller is never served the first caller's cached response, whether the credential is `x-api-key`/`Authorization`, `Cookie` or `Proxy-Authorization`. The `Cookie` and `Proxy-Authorization` cases fail without the latest change. With an identity resolver installed, callers on one operator key are partitioned. These end-to-end tests fail on `main`. - A resolver that raises, or returns an empty principal, yields no partition, and end to end (both handlers) callers on one operator key never share a cached response and nothing is stored. These fail without the fail-closed change. With no resolver installed, the partition is the credential-only one. - With the response cache disabled, neither handler calls the identity resolver. Existing cache tests now pass a fixed partition. The buffered-stream CCR test derives the same partition the handler computes. Manual run: two callers send the identical `/v1/messages` request with different `x-api-key` values through a proxy in front of a capture upstream. On `main` the second caller gets the first caller's answer and only the first key reaches the upstream. On this branch each caller gets its own answer, and a repeat by the first caller is still a cache hit. Not tested: multi-worker deployments (the cache and its key are per process, as before). ## Merge order / conflicts Part of a set. Suggested order: #3852 → #3891 → #3849 → #3860 → #3862 → #3863. Textual conflict: #3860 adds an import next to the one this PR adds in `handlers/anthropic.py` and `handlers/openai.py`. Whichever merges second keeps both imports. Revised 2026-10-04 after review: forwarded `Cookie` and `Proxy-Authorization` headers are now partition input (via the shared credential-header rule), so cookie-authenticated callers no longer share the anonymous partition. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3862" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
81 lines
2.4 KiB
Python
81 lines
2.4 KiB
Python
"""Tests for pure proxy semantic cache key policy."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from headroom.proxy.semantic_cache import SemanticCache
|
|
from headroom.proxy.semantic_cache_key_policy import (
|
|
compute_semantic_cache_key,
|
|
strip_cache_control,
|
|
)
|
|
|
|
MESSAGES = [{"role": "user", "content": "hello"}]
|
|
MODEL = "claude-haiku-4-5"
|
|
|
|
|
|
def test_strip_cache_control_recurses_through_dicts_and_lists() -> None:
|
|
payload = {
|
|
"system": [
|
|
{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}},
|
|
{"nested": {"cache_control": "drop", "value": 1}},
|
|
],
|
|
"cache_control": "drop-root",
|
|
}
|
|
assert strip_cache_control(payload) == {
|
|
"system": [
|
|
{"type": "text", "text": "sys"},
|
|
{"nested": {"value": 1}},
|
|
]
|
|
}
|
|
|
|
|
|
def test_compute_semantic_cache_key_is_stable_for_identical_inputs() -> None:
|
|
kwargs = {"system": "sys", "tools": [{"name": "read"}], "temperature": 0.2}
|
|
assert compute_semantic_cache_key(
|
|
MESSAGES, MODEL, partition="p_test", **kwargs
|
|
) == compute_semantic_cache_key(
|
|
MESSAGES,
|
|
MODEL,
|
|
partition="p_test",
|
|
**kwargs,
|
|
)
|
|
|
|
|
|
def test_compute_semantic_cache_key_distinguishes_response_shaping_fields() -> None:
|
|
assert compute_semantic_cache_key(
|
|
MESSAGES, MODEL, partition="p_test", temperature=0.0
|
|
) != compute_semantic_cache_key(
|
|
MESSAGES,
|
|
MODEL,
|
|
partition="p_test",
|
|
temperature=1.0,
|
|
)
|
|
|
|
|
|
def test_compute_semantic_cache_key_ignores_moved_cache_control_breakpoints() -> None:
|
|
with_breakpoint = [{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}}]
|
|
without_breakpoint = [{"type": "text", "text": "sys"}]
|
|
assert compute_semantic_cache_key(
|
|
MESSAGES,
|
|
MODEL,
|
|
partition="p_test",
|
|
system=with_breakpoint,
|
|
) == compute_semantic_cache_key(
|
|
MESSAGES,
|
|
MODEL,
|
|
partition="p_test",
|
|
system=without_breakpoint,
|
|
)
|
|
|
|
|
|
def test_semantic_cache_private_key_wrapper_delegates_to_policy() -> None:
|
|
cache = SemanticCache()
|
|
kwargs = {"system": "sys", "tools": [{"name": "read"}], "temperature": 0.2}
|
|
assert cache._compute_key(
|
|
MESSAGES, MODEL, partition="p_test", **kwargs
|
|
) == compute_semantic_cache_key(
|
|
MESSAGES,
|
|
MODEL,
|
|
partition="p_test",
|
|
**kwargs,
|
|
)
|