mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 11:31:17 +08:00
## 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>
154 lines
5.9 KiB
Python
154 lines
5.9 KiB
Python
"""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
|