fix(proxy): keep upstream credentials out of manifests, env and TOIN (#4866)

## Description

Proxy secrets (upstream API keys, proxy token, licence) were stored or
passed in clear:

- Bench manifests and `ProxyDeploymentPlan.to_dict()` serialized the
full `ProxyConfig`, keys included.
- With `--workers N`, the whole config, keys included, went to each
worker in the `HEADROOM_PROXY_CONFIG_JSON` env var, which other
processes of the same user can read (`ps eww`, `/proc/<pid>/environ`).
- TOIN stored query field names in clear, although its module docstring
says field names are hashed; the text before a `:` can be a credential
(`<token>:x-oauth-basic`).

Closes #

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/models.py`: `PROXY_CONFIG_SECRET_FIELDS` (one list)
and `redact_proxy_config_secrets`.
- `headroom/testing/harness.py`, `ProxyDeploymentPlan.to_dict()`:
serialize the redacted config; the in-memory plan keeps real values.
- `headroom/proxy/server.py` (`--workers N`): secrets go to a 0600 temp
file named by `HEADROOM_PROXY_CONFIG_SECRETS_FILE`; workers read it, the
env JSON carries the config without them, and the file is removed when
the server stops. A worker that cannot read the file raises
`ConfigurationError` instead of falling back to env defaults (which
could drop the proxy token).
- `headroom/telemetry/toin.py`: query patterns hash field names; stored
patterns with raw field names are dropped on load and the store is
rewritten at once (a private `_import_patterns` reports whether anything
was dropped).
- Tests: `tests/test_proxy_config_secrets_at_rest.py` (manifest,
`to_dict`, worker env carry no secret; workers still get the real
values); `tests/test_toin_retention.py` expectations updated to hashed
field names.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ pytest -q tests/test_proxy_config_secrets_at_rest.py tests/test_toin_retention.py tests/test_stateless_toin.py tests/test_toin_*.py ...
125 passed

# new tests against origin/main
tests/test_proxy_config_secrets_at_rest.py: 3 failed (+1 for the fail-closed worker, which fails on the first commit too)
test_legacy_raw_query_keys_are_removed_on_load: fails without the load-time rewrite

# every test file importing the changed modules (73 files), this branch
2 failed, 1504 passed: tests/test_read_maturation_handler_nobust.py, both also failing on origin/main
(an earlier run on the first commit also hit tests/test_proxy_health.py failures that fail the same way on origin/main,
and one tests/test_proxy_ccr.py timing failure that main showed in a sibling test; that file passes 3/3 alone on both)

ruff check / format --check: clean; mypy: no new errors (same 8 pre-existing as origin/main)
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, the real `headroom proxy --workers 2
--stateless --no-telemetry` CLI, isolated `HOME`/`TMPDIR`,
`--openai-api-url` pointed at a local HTTP server that prints the
`x-gateway-auth` header it receives, `--openai-extra-headers
'{"x-gateway-auth":"FAKE-GATEWAY-0123"}'`.
- Exact command / steps: start the proxy, run `ps eww` on each worker
process, list `$TMPDIR`, POST `/v1/chat/completions`, stop the proxy
with SIGTERM.
- Observed result:
- origin/main: both worker processes' environments contain
`FAKE-GATEWAY-0123` (via `HEADROOM_PROXY_CONFIG_JSON`).
- this branch: neither worker's environment contains it; `$TMPDIR` holds
one `headroom-proxy-config-*.json` with mode `-rw-------`; the upstream
still receives `x-gateway-auth: FAKE-GATEWAY-0123` (workers load it from
the file); after SIGTERM the file is gone.
- On both, the parent's own command line holds the value because the
test passed it as a CLI flag; that is outside this change.
- Not tested: SIGKILL of the parent (the file stays in `$TMPDIR`).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: manifests and `to_dict()` show
secrets redacted; TOIN query-pattern keys are hashed and old raw-name
keys are dropped once on load (learned query statistics for those keys
restart).
- Kill switch / disable path: none.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-14 10:46:55 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent dffc4dcc57
commit 2e4ff6f9c7
7 changed files with 366 additions and 81 deletions
+31
View File
@@ -634,3 +634,34 @@ class ProxyConfig:
cloudcode=self.cloudcode_api_url,
vertex=self.vertex_api_url,
)
# ProxyConfig fields that hold a credential. Whatever serialises a config into
# a file, a manifest or another process's environment masks or moves these.
PROXY_CONFIG_SECRET_FIELDS: frozenset[str] = frozenset(
{
"memory_qdrant_api_key",
"memory_neo4j_password",
"license_key",
"proxy_token",
"anthropic_extra_headers",
"openai_extra_headers",
}
)
PROXY_CONFIG_REDACTED = "[REDACTED]"
def redact_proxy_config_secrets(payload: dict[str, Any]) -> dict[str, Any]:
"""Return a copy of a serialised ProxyConfig with every credential masked.
Header maps keep their header names so a manifest still shows which
headers are configured.
"""
out = dict(payload)
for name in PROXY_CONFIG_SECRET_FIELDS:
value = out.get(name)
if isinstance(value, dict):
out[name] = dict.fromkeys(value, PROXY_CONFIG_REDACTED)
elif value:
out[name] = PROXY_CONFIG_REDACTED
return out
+128 -57
View File
@@ -36,6 +36,7 @@ import math
import os
import signal
import sys
import tempfile
import threading
import time
from collections import OrderedDict
@@ -88,6 +89,7 @@ from headroom.config import (
resolve_omlx_target_api_url,
)
from headroom.dashboard import get_dashboard_html
from headroom.exceptions import ConfigurationError
from headroom.log_safety import describe_exception, safe_id
from headroom.observability import (
LangfuseTracingConfig,
@@ -166,6 +168,7 @@ from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler
# Data models (extracted to headroom/proxy/models.py for maintainability)
from headroom.proxy.model_router import ModelRouter, ModelRouterConfig
from headroom.proxy.models import (
PROXY_CONFIG_SECRET_FIELDS,
ProxyConfig,
default_periodic_malloc_trim,
)
@@ -604,6 +607,9 @@ class CompressionQuarantinedError(asyncio.TimeoutError):
_MULTI_WORKER_CONFIG_ENV = "HEADROOM_PROXY_CONFIG_JSON"
# The workers' copy of the config's credentials travels in an owner-only file,
# not in the environment every child process inherits; this names the file.
_MULTI_WORKER_SECRETS_ENV = "HEADROOM_PROXY_CONFIG_SECRETS_FILE"
def _save_prefix_state_on_exit_signal(store: Any, path: str) -> Callable[[], None]:
@@ -6828,13 +6834,55 @@ def _settings_runtime_values(config: ProxyConfig) -> dict[str, Any]:
return values
def _write_worker_secrets(payload: dict[str, Any]) -> Path | None:
"""Move the credential fields out of ``payload`` into an owner-only file.
Returns the file's path, or None when the config holds no credential.
"""
secrets = {name: payload.pop(name) for name in PROXY_CONFIG_SECRET_FIELDS if payload.get(name)}
if not secrets:
return None
# mkstemp creates the file with mode 0600.
fd, raw_path = tempfile.mkstemp(prefix="headroom-proxy-config-", suffix=".json")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(secrets, fh)
return Path(raw_path)
def _read_worker_secrets() -> dict[str, Any]:
"""Read the credentials the parent wrote for this worker.
Raises instead of returning nothing when the file is named but unreadable:
a worker that fell back to env defaults would come up without the proxy
token while still bound to the parent's host.
"""
path = os.environ.get(_MULTI_WORKER_SECRETS_ENV)
if not path:
return {}
try:
with open(path, encoding="utf-8") as fh:
values = json.load(fh)
except (OSError, ValueError) as exc:
raise ConfigurationError(
f"Worker cannot read its credentials file {path!r} ({type(exc).__name__}). "
"The parent proxy writes it at startup and removes it on exit; restart the proxy."
) from exc
if not isinstance(values, dict):
raise ConfigurationError(
f"Worker credentials file {path!r} does not hold a JSON object; restart the proxy."
)
return values
def _proxy_config_from_env() -> ProxyConfig:
raw_config = os.environ.get(_MULTI_WORKER_CONFIG_ENV)
if raw_config:
worker_secrets = _read_worker_secrets()
try:
values = json.loads(raw_config)
if not isinstance(values, dict):
raise TypeError("proxy config JSON must be an object")
values.update(worker_secrets)
if "_rollout_snapshot" in values:
rollout_value = values.pop("_rollout_snapshot")
from headroom.rollout import RolloutSnapshot
@@ -7108,67 +7156,82 @@ def run_server(
app_target: Any
uvicorn_kwargs: dict[str, Any] = {}
worker_secrets_path: Path | None = None
# Worker hand-off variables as they were before this run, restored on exit
# so a later run in the same process starts from the same state.
prior_worker_env = {
name: os.environ.get(name) for name in (_MULTI_WORKER_CONFIG_ENV, _MULTI_WORKER_SECRETS_ENV)
}
if sys.platform == "win32":
_configure_windows_uvicorn_loop(uvicorn_kwargs)
if workers > 1:
# CompressionCache and PrefixTracker are always per-worker instance vars.
# Python CompressionStore defaults to InMemoryBackend (per-process), so
# CCR markers written on worker A are invisible to worker B unless a
# cross-worker backend is configured via HEADROOM_CCR_BACKEND.
# See RUST_DEV.md -> "Multi-worker deployment -- CCR fragmentation".
if os.environ.get("HEADROOM_CCR_BACKEND", "").strip():
logger.warning(
"Headroom is running with workers=%d. Compression cache, "
"prefix tracker, TOIN state, and CostTracker are all per-process; "
"multi-worker deployments produce avoidable cache busts and an "
"unstable dashboard 'Proxy $ Saved' hero tile (each /stats poll "
"hits a different worker's partial total) when sessions land on "
"different workers. Run --workers 1 or place a sticky-session load "
"balancer in front of multiple --workers 1 processes. "
"See RUST_DEV.md -> 'Multi-worker deployment -- CCR fragmentation'.",
workers,
)
else:
logger.warning(
"Headroom is running with workers=%d. The in-memory CCR store, "
"compression cache (incl. off-path background compression), prefix "
"tracker, TOIN state, and CostTracker are all "
"per-process; multi-worker deployments produce silent CCR retrieval "
"failures, avoidable cache busts, and an unstable dashboard 'Proxy $ Saved' "
"hero tile (each /stats poll hits a different worker's partial total) when "
"sessions land on different workers. Set HEADROOM_CCR_BACKEND=sqlite for a "
"persistent cross-worker CCR store, run --workers 1, or place a "
"sticky-session load balancer in front of multiple --workers 1 processes. "
"See RUST_DEV.md -> 'Multi-worker deployment -- CCR fragmentation'.",
workers,
)
os.environ[_MULTI_WORKER_CONFIG_ENV] = json.dumps(_proxy_config_payload(config))
app_target = "headroom.proxy.server:create_app_from_env"
uvicorn_kwargs["factory"] = True
else:
app_target = create_app(config)
# "warning" keeps the default terminal quiet (uvicorn's access log is one line
# per request). It was previously hardcoded, which left deployed proxies with
# no way to turn request logging on: operators diagnosing a production
# incident could not see uvicorn's view of the traffic at all, with no env var
# and no CLI flag to change it. Overridable now; the default is unchanged.
uvicorn_log_level = _resolve_uvicorn_log_level()
# Bind target: a Unix socket when one is configured, otherwise host:port.
# uvicorn treats `uds` and `host`/`port` as alternatives, so they are built
# here rather than passed together.
bind_kwargs: dict[str, Any]
uds_path: Path | None = None
if config.uds:
from headroom.proxy.uds import prepare_uds_path
uds_path = prepare_uds_path(config.uds)
bind_kwargs = {"uds": str(uds_path)}
else:
bind_kwargs = {"host": config.host, "port": config.port}
# Everything from here runs under the cleanup below: once the worker
# secrets file exists, any startup failure (a bad --uds path, for
# example) must still delete it and restore the hand-off variables.
try:
if workers > 1:
# CompressionCache and PrefixTracker are always per-worker instance vars.
# Python CompressionStore defaults to InMemoryBackend (per-process), so
# CCR markers written on worker A are invisible to worker B unless a
# cross-worker backend is configured via HEADROOM_CCR_BACKEND.
# See RUST_DEV.md -> "Multi-worker deployment -- CCR fragmentation".
if os.environ.get("HEADROOM_CCR_BACKEND", "").strip():
logger.warning(
"Headroom is running with workers=%d. Compression cache, "
"prefix tracker, TOIN state, and CostTracker are all per-process; "
"multi-worker deployments produce avoidable cache busts and an "
"unstable dashboard 'Proxy $ Saved' hero tile (each /stats poll "
"hits a different worker's partial total) when sessions land on "
"different workers. Run --workers 1 or place a sticky-session load "
"balancer in front of multiple --workers 1 processes. "
"See RUST_DEV.md -> 'Multi-worker deployment -- CCR fragmentation'.",
workers,
)
else:
logger.warning(
"Headroom is running with workers=%d. The in-memory CCR store, "
"compression cache (incl. off-path background compression), prefix "
"tracker, TOIN state, and CostTracker are all "
"per-process; multi-worker deployments produce silent CCR retrieval "
"failures, avoidable cache busts, and an unstable dashboard 'Proxy $ Saved' "
"hero tile (each /stats poll hits a different worker's partial total) when "
"sessions land on different workers. Set HEADROOM_CCR_BACKEND=sqlite for a "
"persistent cross-worker CCR store, run --workers 1, or place a "
"sticky-session load balancer in front of multiple --workers 1 processes. "
"See RUST_DEV.md -> 'Multi-worker deployment -- CCR fragmentation'.",
workers,
)
worker_config = _proxy_config_payload(config)
worker_secrets_path = _write_worker_secrets(worker_config)
# A path left by an earlier run in this process names a deleted file.
os.environ.pop(_MULTI_WORKER_SECRETS_ENV, None)
if worker_secrets_path is not None:
os.environ[_MULTI_WORKER_SECRETS_ENV] = str(worker_secrets_path)
os.environ[_MULTI_WORKER_CONFIG_ENV] = json.dumps(worker_config)
app_target = "headroom.proxy.server:create_app_from_env"
uvicorn_kwargs["factory"] = True
else:
app_target = create_app(config)
# "warning" keeps the default terminal quiet (uvicorn's access log is one line
# per request). It was previously hardcoded, which left deployed proxies with
# no way to turn request logging on: operators diagnosing a production
# incident could not see uvicorn's view of the traffic at all, with no env var
# and no CLI flag to change it. Overridable now; the default is unchanged.
uvicorn_log_level = _resolve_uvicorn_log_level()
# Bind target: a Unix socket when one is configured, otherwise host:port.
# uvicorn treats `uds` and `host`/`port` as alternatives, so they are built
# here rather than passed together.
bind_kwargs: dict[str, Any]
if config.uds:
from headroom.proxy.uds import prepare_uds_path
uds_path = prepare_uds_path(config.uds)
bind_kwargs = {"uds": str(uds_path)}
else:
bind_kwargs = {"host": config.host, "port": config.port}
_run_uvicorn(
app_target,
bind_kwargs,
@@ -7182,6 +7245,14 @@ def run_server(
from headroom.proxy.uds import remove_uds_path
remove_uds_path(uds_path)
if worker_secrets_path is not None:
worker_secrets_path.unlink(missing_ok=True)
if workers > 1:
for name, value in prior_worker_env.items():
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
def _run_uvicorn(
+22 -13
View File
@@ -951,10 +951,10 @@ class ToolIntelligenceNetwork:
)
def _sanitize_loaded_pattern(self, pattern: ToolPattern) -> bool:
"""Remove legacy raw query keys from a loaded pattern."""
"""Remove legacy query keys (raw text or unhashed field names) from a loaded pattern."""
import re
safe_pattern = re.compile(r"(?:\w+:\*)(?:\s+\w+:\*)*")
safe_pattern = re.compile(r"[0-9a-f]{8}:\*(?:\s+[0-9a-f]{8}:\*)*")
changed = False
frequencies: dict[str, int] = {}
for raw_key, count in pattern.query_pattern_frequency.items():
@@ -1249,8 +1249,10 @@ class ToolIntelligenceNetwork:
def _anonymize_query_pattern(self, query: str) -> str | None:
"""Extract anonymized pattern from a query.
Keeps structural patterns, removes specific values.
E.g., "status:error AND user:john" -> "status:* AND user:*"
Keeps the shape of field/value predicates and drops the values. Field
names are hashed like every other TOIN field name: the text before a
``:`` can itself be a credential (``<token>:x-oauth-basic``).
E.g., "status:error AND user:john" -> "<hash(status)>:* <hash(user)>:*"
"""
if not query:
return None
@@ -1267,7 +1269,7 @@ class ToolIntelligenceNetwork:
# Preserve useful field shape while dropping operators, values, and
# all unrelated text (which may contain arbitrary prompt data).
pattern = " ".join(f"{field}:*" for field in matches)
pattern = " ".join(f"{self._hash_field_name(field)}:*" for field in matches)
# Remove if it's just generic
if not pattern or len(pattern) > MAX_QUERY_PATTERN_LENGTH:
@@ -1431,9 +1433,14 @@ class ToolIntelligenceNetwork:
Args:
data: Exported pattern data.
"""
if not self._config.enabled:
return
self._import_patterns(data)
def _import_patterns(self, data: dict[str, Any]) -> bool:
"""Body of ``import_patterns``; True when a legacy query key was dropped."""
if not self._config.enabled:
return False
sanitized = False
patterns_data = data.get("patterns", {})
source_instance = data.get("instance_id", "unknown")
@@ -1448,7 +1455,7 @@ class ToolIntelligenceNetwork:
try:
key = _deserialize_pattern_key(serialized_key)
imported = ToolPattern.from_dict(pattern_dict)
self._sanitize_loaded_pattern(imported)
sanitized = self._sanitize_loaded_pattern(imported) or sanitized
# Make sure dataclass fields agree with the dict key — pre-F3
# dumps don't carry tenant_key on the pattern, and pre-B5
# dumps don't carry auth_mode/model_family either; promote
@@ -1495,6 +1502,7 @@ class ToolIntelligenceNetwork:
"error": str(first_error),
},
)
return sanitized
def _merge_patterns(self, existing: ToolPattern, imported: ToolPattern) -> None:
"""Merge imported pattern into existing."""
@@ -1721,15 +1729,12 @@ class ToolIntelligenceNetwork:
if self._backend is None:
return
changed = False
try:
data = self._backend.load()
if data:
self.import_patterns(data)
changed = self._import_patterns(data)
with self._lock:
changed = any(
self._sanitize_loaded_pattern(pattern)
for pattern in self._patterns.values()
)
before = len(self._patterns)
self._prune_patterns_locked()
changed = changed or len(self._patterns) != before
@@ -1744,6 +1749,10 @@ class ToolIntelligenceNetwork:
"error": str(e),
},
)
if changed:
# Rewrite at once: a dropped legacy query key can hold a credential,
# and waiting for the next observation would leave it on disk.
self.save()
def _maybe_auto_save(self) -> None:
"""Auto-save if enough time has passed.
+11 -4
View File
@@ -27,7 +27,7 @@ from typing import Any, Literal, cast
from headroom._subprocess import run as subprocess_run
from headroom.config import HeadroomConfig, HeadroomMode
from headroom.proxy.models import ProxyConfig
from headroom.proxy.models import ProxyConfig, redact_proxy_config_secrets
ConfigCallback = Callable[["Configurator"], None]
ProxyCallback = Callable[[ProxyConfig], None]
@@ -380,10 +380,17 @@ class ProxyDeploymentPlan:
config_env_var: str = "HEADROOM_PROXY_CONFIG_JSON"
def to_dict(self) -> dict[str, Any]:
"""Serialise for a manifest. Credentials stay in the live plan only."""
config_payload = redact_proxy_config_secrets(self.config_payload)
env = dict(self.env)
if self.config_env_var in env:
env[self.config_env_var] = json.dumps(
config_payload, sort_keys=True, separators=(",", ":")
)
return {
"command": list(self.command),
"env": dict(self.env),
"config_payload": dict(self.config_payload),
"env": env,
"config_payload": config_payload,
"config_env_var": self.config_env_var,
}
@@ -1206,7 +1213,7 @@ class HarnessScenario:
provider=self.provider.value,
platform=self.platform.value,
arms=self.bench_arms(provider=provider),
proxy_config=_public_dataclass_dict(self.proxy_config),
proxy_config=redact_proxy_config_secrets(_public_dataclass_dict(self.proxy_config)),
headroom_config=_public_dataclass_dict(self.headroom_config),
env=self.env(),
deployment_plan=deployment_plan.to_dict(),
+153
View File
@@ -0,0 +1,153 @@
"""ProxyConfig credentials stay out of manifests, the worker environment and TOIN."""
from __future__ import annotations
import dataclasses
import json
import os
import stat
from pathlib import Path
from unittest.mock import patch
import pytest
pytest.importorskip("fastapi")
from headroom.proxy.models import ProxyConfig # noqa: E402
from headroom.telemetry.toin import TOINConfig, ToolIntelligenceNetwork # noqa: E402
from headroom.testing import Headroom # noqa: E402
SECRETS = {
"memory_qdrant_api_key": "FAKE-QDRANT",
"memory_neo4j_password": "FAKE-NEO4J",
"license_key": "FAKE-LICENSE",
"proxy_token": "FAKE-PROXYTOKEN",
"openai_extra_headers": {"x-gateway-auth": "FAKE-GATEWAY"},
}
SECRET_VALUES = ("FAKE-QDRANT", "FAKE-NEO4J", "FAKE-LICENSE", "FAKE-PROXYTOKEN", "FAKE-GATEWAY")
def test_bench_manifest_does_not_serialise_proxy_secrets(tmp_path: Path) -> None:
scenario = Headroom.WithBedrock(region="us-east-2", profile="bench").Build()
scenario = dataclasses.replace(scenario, proxy_config=ProxyConfig(**SECRETS))
text = scenario.write_manifest_fragment(tmp_path / "manifest.json").read_text(encoding="utf-8")
for value in SECRET_VALUES:
assert value not in text
payload = json.loads(text)
assert payload["proxy_config"]["license_key"] == "[REDACTED]"
assert payload["proxy_config"]["openai_extra_headers"] == {"x-gateway-auth": "[REDACTED]"}
# The live plan still carries the real values for the runner.
plan = scenario.deployment_plan(port=18888)
assert json.loads(plan.env["HEADROOM_PROXY_CONFIG_JSON"])["proxy_token"] == "FAKE-PROXYTOKEN"
def test_multi_worker_config_keeps_secrets_out_of_the_environment(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from headroom.proxy import server
# setenv first so monkeypatch restores both after run_server sets them.
for name in ("HEADROOM_PROXY_CONFIG_JSON", "HEADROOM_PROXY_CONFIG_SECRETS_FILE"):
monkeypatch.setenv(name, "")
monkeypatch.delenv(name)
seen: dict[str, object] = {}
def fake_run_uvicorn(*_args: object) -> None:
env_json = os.environ["HEADROOM_PROXY_CONFIG_JSON"]
secrets_file = Path(os.environ["HEADROOM_PROXY_CONFIG_SECRETS_FILE"])
seen["env_json"] = env_json
seen["file_mode"] = stat.S_IMODE(secrets_file.stat().st_mode)
seen["secrets_file"] = secrets_file
# What a worker rebuilds from the environment and the file.
seen["worker_config"] = server._proxy_config_from_env()
with patch.object(server, "_run_uvicorn", side_effect=fake_run_uvicorn):
server.run_server(ProxyConfig(**SECRETS), workers=2, print_banner=False)
for value in SECRET_VALUES:
assert value not in seen["env_json"]
assert seen["file_mode"] == 0o600
worker_config = seen["worker_config"]
assert isinstance(worker_config, ProxyConfig)
assert worker_config.proxy_token == "FAKE-PROXYTOKEN"
assert worker_config.openai_extra_headers == {"x-gateway-auth": "FAKE-GATEWAY"}
assert not Path(seen["secrets_file"]).exists() # removed when the server stops
def test_credential_free_restart_after_a_credentialed_run_still_starts(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from headroom.proxy import server
for name in ("HEADROOM_PROXY_CONFIG_JSON", "HEADROOM_PROXY_CONFIG_SECRETS_FILE"):
monkeypatch.setenv(name, "")
monkeypatch.delenv(name)
configs: list[ProxyConfig] = []
def fake_run_uvicorn(*_args: object) -> None:
configs.append(server._proxy_config_from_env())
with patch.object(server, "_run_uvicorn", side_effect=fake_run_uvicorn):
server.run_server(ProxyConfig(**SECRETS), workers=2, print_banner=False)
# The worker hand-off variables are back to their pre-run state (unset).
assert "HEADROOM_PROXY_CONFIG_SECRETS_FILE" not in os.environ
assert "HEADROOM_PROXY_CONFIG_JSON" not in os.environ
server.run_server(ProxyConfig(), workers=2, print_banner=False)
assert configs[0].proxy_token == "FAKE-PROXYTOKEN"
assert configs[1].proxy_token is None
@pytest.mark.skipif(os.name == "nt", reason="Unix sockets")
def test_failed_startup_removes_the_secrets_file_and_restores_the_environment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
import tempfile
from headroom.proxy import server
from headroom.proxy.uds import UdsError
secrets_dir = tmp_path / "tmp"
secrets_dir.mkdir()
monkeypatch.setattr(tempfile, "tempdir", str(secrets_dir))
monkeypatch.setenv("HEADROOM_PROXY_CONFIG_JSON", "prior-value")
monkeypatch.delenv("HEADROOM_PROXY_CONFIG_SECRETS_FILE", raising=False)
not_a_socket = tmp_path / "proxy.sock"
not_a_socket.write_text("regular file", encoding="utf-8")
with pytest.raises(UdsError):
server.run_server(
ProxyConfig(proxy_token="FAKE-PROXYTOKEN", uds=str(not_a_socket)),
workers=2,
print_banner=False,
)
assert list(secrets_dir.iterdir()) == []
assert os.environ["HEADROOM_PROXY_CONFIG_JSON"] == "prior-value"
assert "HEADROOM_PROXY_CONFIG_SECRETS_FILE" not in os.environ
def test_worker_without_its_secrets_file_refuses_to_start(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
from headroom.exceptions import ConfigurationError
from headroom.proxy import server
# Falling back to env defaults here would drop the proxy token.
monkeypatch.setenv("HEADROOM_PROXY_CONFIG_JSON", json.dumps({"host": "0.0.0.0"}))
monkeypatch.setenv("HEADROOM_PROXY_CONFIG_SECRETS_FILE", str(tmp_path / "gone.json"))
with pytest.raises(ConfigurationError, match="restart the proxy"):
server._proxy_config_from_env()
def test_toin_query_pattern_does_not_keep_the_text_before_a_colon() -> None:
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=""))
pattern = toin._anonymize_query_pattern("AKIAABCDEFGHIJKLMNOP:secretvalue")
assert pattern is not None
assert "AKIA" not in pattern
assert "secretvalue" not in pattern
+5 -1
View File
@@ -265,6 +265,9 @@ class TestWorkerConfiguration:
def fake_run(app, **kwargs):
captured["app"] = app
captured["kwargs"] = kwargs
# Read while the workers would: run_server restores the variable
# to its pre-run state when it returns.
captured["config_json"] = os.environ[_MULTI_WORKER_CONFIG_ENV]
monkeypatch.delenv(_MULTI_WORKER_CONFIG_ENV, raising=False)
@@ -276,12 +279,13 @@ class TestWorkerConfiguration:
assert captured["kwargs"]["workers"] == 4
assert captured["kwargs"]["limit_concurrency"] == 250
assert captured["kwargs"]["factory"] is True
payload = json.loads(os.environ[_MULTI_WORKER_CONFIG_ENV])
payload = json.loads(captured["config_json"])
assert payload["host"] == "0.0.0.0"
assert payload["port"] == 8787
assert payload["worker_processes"] == 4
assert payload["max_connections"] == 200
assert payload["http_proxy"] == "http://proxy.local:8080"
assert _MULTI_WORKER_CONFIG_ENV not in os.environ
finally:
# run_server sets this via raw os.environ. Pop it directly rather
# than via monkeypatch.delenv: delenv records the current (JSON)
+16 -6
View File
@@ -140,7 +140,9 @@ def test_free_form_queries_are_not_persisted() -> None:
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=""))
assert toin._anonymize_query_pattern("show me the contents of /private/secret.txt") is None
assert toin._anonymize_query_pattern("status:error AND user:john") == "status:* user:*"
assert toin._anonymize_query_pattern("status:error AND user:john") == (
f"{toin._hash_field_name('status')}:* {toin._hash_field_name('user')}:*"
)
toin.record_retrieval(
"signature",
@@ -155,7 +157,9 @@ def test_free_form_queries_are_not_persisted() -> None:
def test_query_pattern_length_is_bounded() -> None:
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=""))
assert toin._anonymize_query_pattern("field:" + "x" * 1000) == "field:*"
assert toin._anonymize_query_pattern("field:" + "x" * 1000) == (
f"{toin._hash_field_name('field')}:*"
)
assert toin._anonymize_query_pattern(" ".join(f"field{i}:x" for i in range(200))) is None
@@ -188,11 +192,13 @@ def test_legacy_raw_query_keys_are_removed_on_load(tmp_path) -> None:
"tool_signature_hash": "abc",
"query_pattern_frequency": {
"raw prompt containing secret source code": 4,
"status:* user:*": 2,
"status:* user:*": 3,
"1a2b3c4d:* 5e6f7a8b:*": 2,
},
"common_query_patterns": [
"raw prompt containing secret source code",
"status:* user:*",
"1a2b3c4d:* 5e6f7a8b:*",
],
}
},
@@ -202,8 +208,12 @@ def test_legacy_raw_query_keys_are_removed_on_load(tmp_path) -> None:
toin = ToolIntelligenceNetwork(TOINConfig(storage_path=str(path)))
pattern = next(iter(toin._patterns.values()))
assert pattern.query_pattern_frequency == {"status:* user:*": 2}
assert pattern.common_query_patterns == ["status:* user:*"]
assert pattern.query_pattern_frequency == {"1a2b3c4d:* 5e6f7a8b:*": 2}
assert pattern.common_query_patterns == ["1a2b3c4d:* 5e6f7a8b:*"]
# Rewritten at load, not on the next observation.
on_disk = path.read_text(encoding="utf-8")
assert "raw prompt containing secret source code" not in on_disk
assert "status:* user:*" not in on_disk
def _record(toin: ToolIntelligenceNetwork, index: int) -> None:
@@ -235,7 +245,7 @@ def _skip_warnings(caplog) -> list[logging.LogRecord]:
lambda entry: {k: v for k, v in entry.items() if k != "tool_signature_hash"},
lambda entry: {**entry, "field_semantics": {"field_1": "not a dict"}},
lambda entry: {**entry, "query_pattern_frequency": "not a dict"},
lambda entry: {**entry, "query_pattern_frequency": {"status:*": "many"}},
lambda entry: {**entry, "query_pattern_frequency": {"1a2b3c4d:*": "many"}},
lambda entry: {**entry, "seen_instance_hashes": "bad"},
lambda entry: {**entry, "commonly_retrieved_fields": "abc"},
lambda entry: {**entry, "sample_size": "x"},