Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(packaging): rename the sandbox extra to lean and correct SECURITY.md claims (#3727)

Tejas Chopra09b7e8c1e417
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dbdb55636..fa6b398af 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -268,11 +268,11 @@ jobs:
run: |
python -m pip install --upgrade pip maturin
maturin build --profile ci --out dist --interpreter python3.14
- - name: Install headroom-ai[sandbox] from prebuilt wheels only
+ - name: Install headroom-ai[lean] from prebuilt wheels only
run: |
python -m pip install --upgrade pip
WHEEL="$(ls dist/*.whl)"
- python -m pip install --only-binary=:all: "${WHEEL}[sandbox]"
+ python -m pip install --only-binary=:all: "${WHEEL}[lean]"
- name: Proxy dependencies and LiteLLM pricing are available
working-directory: ${{ runner.temp }}
run: |
diff --git a/SECURITY.md b/SECURITY.md
index ba5f902b6..8defcde14 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -74,9 +74,9 @@ it necessarily handles both your traffic and your credentials. The
full — what is written to disk, with what permissions and retention, what leaves the
host, and what the local admin surface does and does not allow. The summary:
-- **Provider API keys are forwarded, not persisted.** Keys supplied via environment
+- **Interactive provider API keys are forwarded.** Keys supplied via environment
variables or request headers are used to authenticate the upstream call and are not
- written to disk or emitted to logs. The one exception is deliberate: the
+ written to disk or emitted to logs. Settings can also persist keys: the
`ANTHROPIC_TARGET_API_HEADERS` / `OPENAI_TARGET_API_HEADERS` header maps, if you set
them through the dashboard settings GUI, are persisted to `~/.headroom/settings.json`
in plaintext — and a header map is where a gateway key typically goes.
@@ -84,6 +84,29 @@ host, and what the local admin surface does and does not allow. The summary:
GitHub Copilot OAuth refresh token to `~/.headroom/copilot_auth.json` (relocatable via
`$HEADROOM_COPILOT_AUTH_FILE`). It is plaintext JSON, written with `0600` permissions
on a best-effort basis.
+- **Persistent installs store supplied environment values.** Every value passed
+ to `headroom install --env KEY=VALUE` is stored verbatim and in cleartext. Supervisors (launchd, systemd, Task
+ Scheduler, cron) start the proxy from a bare environment, so `--env` is the
+ only channel by which a provider API key reaches a supervised proxy — and
+ if you pass one, it is written to
+ `~/.headroom/deploy/<profile>/manifest.json` (mode `0600`) and `export`ed in
+ cleartext by the generated runner scripts `run-headroom.sh` /
+ `ensure-headroom.sh` (mode `0700`) in the same directory (mode `0700`).
+ The installer sets those modes and then reads them back: where the
+ platform enforces POSIX permission bits it refuses to leave behind a runner
+ script it could not restrict, and warns if the profile directory could not
+ be narrowed. On Windows the bits are advisory — access is governed by ACLs —
+ so the modes above are requested but not enforced there, and protection
+ comes from the account's own profile directory instead. Where they do hold,
+ the files are owner-only, not encrypted: anything that can read the account
+ — the user themself, root, a home-directory backup or sync — can read the
+ key, and rotating it requires re-running `headroom install apply`.
+ With the Docker runtime the same values are additionally passed as `docker
+ run --env NAME=VALUE`, which places them in the container process's command
+ line and so in `ps` output for other users on the host. Prefer a
+ supervisor-native secret facility (systemd `LoadCredential=` /
+ `EnvironmentFile=` on an owner-only file, a macOS keychain helper) over
+ `--env` for long-lived provider keys.
- **Cached request content is written to disk.** CCR stores pre-compression originals —
tool outputs, file contents, retrieved chunks — in a local SQLite database
(`~/.headroom/ccr_store.db`, `0600`) so they can be retrieved after compression. Entries
diff --git a/docs/content/docs/installation.mdx b/docs/content/docs/installation.mdx
index 4f82b3bdd..3bbab4056 100644
--- a/docs/content/docs/installation.mdx
+++ b/docs/content/docs/installation.mdx
@@ -121,7 +121,7 @@ pip install "headroom-ai[all]"
| `pytorch-mps` | Apple-GPU (MPS) memory-embedder offload — **macOS only**, not in `[all]` (torch + sentence-transformers); opt in with `HEADROOM_EMBEDDER_RUNTIME=pytorch_mps` | `pip install "headroom-ai[pytorch-mps]"` |
| `html` | HTML main-content extraction with trafilatura | `pip install "headroom-ai[html]"` |
| `spreadsheet` | `.xlsx` / `.xls` ingestion with openpyxl and xlrd | `pip install "headroom-ai[spreadsheet]"` |
-| `sandbox` | Torch-free proxy bundle for constrained environments | `pip install "headroom-ai[sandbox]"` |
+| `lean` | Torch-free proxy bundle for constrained environments (a dependency profile; it provides no isolation). `sandbox` is a deprecated alias | `pip install "headroom-ai[lean]"` |
| `all` | Runtime bundle: `proxy,code,ml,memory,relevance,image,reports,otel,evals,voice,html,mcp,spreadsheet` | `pip install "headroom-ai[all]"` |
`[all]` is the full built-in runtime bundle, not every integration or optional
diff --git a/headroom/cli/install.py b/headroom/cli/install.py
index 659e11182..64ca1c662 100644
--- a/headroom/cli/install.py
+++ b/headroom/cli/install.py
@@ -943,7 +943,10 @@ def _echo_installed(manifest: DeploymentManifest, *, prefix: str = "Installed pe
"--env HEADROOM_WORKSPACE_DIR=/path. Supervisors (launchd, systemd, cron) "
"start with a bare environment and do not inherit the interactive shell's "
"exports, so anything the runtime needs beyond the flags above must be set "
- "here. Repeatable."
+ "here. Repeatable. Values are stored in cleartext in the profile's "
+ "manifest and runner scripts under ~/.headroom/deploy/<profile>/ "
+ "(owner-only, not encrypted); see SECURITY.md before passing a provider "
+ "API key this way."
),
)
def install_apply(
diff --git a/headroom/install/paths.py b/headroom/install/paths.py
index 8ef6992a0..19331632e 100644
--- a/headroom/install/paths.py
+++ b/headroom/install/paths.py
@@ -2,8 +2,10 @@
from __future__ import annotations
+import logging
import os
import re
+import stat
import sys
from pathlib import Path
@@ -11,8 +13,88 @@ import click
from headroom import paths as _paths
+logger = logging.getLogger(__name__)
+
_PROFILE_RE = re.compile(r"^[A-Za-z0-9._-]+$")
+# A deployment profile directory holds secrets. `headroom install --env
+# KEY=VALUE` is the supported way to give a supervised proxy a provider API key
+# — supervisors (launchd, systemd, Task Scheduler, cron) start from a bare
+# environment, so nothing else reaches the process — and every such value is
+# persisted verbatim, both into `manifest.json` and into the generated runner
+# scripts that `export` it before the exec. Those files are therefore written
+# owner-only rather than at the process umask (which leaves them world-readable
+# at the common 022). The supervisor always runs them as the installing user
+# (user scope) or as root (system scope), and neither needs the group/other
+# bits, so this is not a functional restriction.
+#
+# SECURITY.md documents these modes; `tests/test_packaging_extras_and_security_docs.py`
+# reads the octal values back out of that document and compares them with what
+# an install actually writes, so the policy and the code cannot drift apart.
+# Named for what they ARE -- a permission mode -- not for what the files they
+# protect contain. The previous SECRET_* spelling read as a credential to
+# CodeQL's sensitive-data heuristic, so `logger.warning("... 0o%o", mode)`
+# tripped py/clear-text-logging-sensitive-data on a diagnostic that logs a
+# permission bitmask and no secret at all.
+OWNER_ONLY_FILE_MODE = 0o600
+OWNER_ONLY_SCRIPT_MODE = 0o700
+OWNER_ONLY_DIR_MODE = 0o700
+
+
+#: Whether this platform actually enforces POSIX permission bits. On Windows
+#: access is governed by ACLs and ``chmod`` only toggles the read-only flag, so
+#: it SUCCEEDS without establishing the requested mode — which is why the check
+#: below reads the mode back rather than trusting the call not to raise.
+POSIX_MODES_ENFORCED = os.name == "posix"
+
+
+def chmod_owner_only(path: Path, mode: int) -> bool:
+ """Narrow ``path`` to an owner-only ``mode``. Returns whether that took.
+
+ This used to swallow every ``OSError`` and return nothing, so a caller had
+ no way to tell a restricted file from an unrestricted one and continued as
+ if the documented mode had been established. That is the wrong default for
+ the two places it matters, because both NARROW A PRE-EXISTING INODE rather
+ than create one: a profile directory made before these modes existed is
+ 0755, and a runner script rewritten through ``O_TRUNC`` keeps whatever mode
+ it already had. In both cases this chmod is the only thing standing between
+ a provider API key and every local user, and a silent failure left the
+ caller asserting a guarantee it did not have.
+
+ The result is verified with ``stat`` instead of inferred from ``chmod`` not
+ raising, because on Windows it does not raise and does not work either.
+
+ Returns ``True`` only when the mode is now exactly ``mode``. A caller
+ holding secret-bearing content must act on ``False``; see
+ :func:`headroom.install.supervisors._write_private_text`, which refuses to
+ leave the file behind.
+ """
+ try:
+ path.chmod(mode)
+ actual = stat.S_IMODE(path.stat().st_mode)
+ except OSError as exc:
+ logger.warning(
+ "Could not restrict %s to mode 0o%o (%s); it may be readable by other local users.",
+ path,
+ mode,
+ exc,
+ )
+ return False
+ if actual != mode:
+ # Expected on Windows, where the bits are advisory -- noise there, a
+ # real finding on POSIX.
+ logger.log(
+ logging.WARNING if POSIX_MODES_ENFORCED else logging.DEBUG,
+ "%s is mode 0o%o after asking for 0o%o; this platform does not "
+ "enforce POSIX permission bits, so the file's protection comes "
+ "from its directory and the system ACLs instead.",
+ path,
+ actual,
+ mode,
+ )
+ return False
+ return True
+
def validate_profile_name(profile: str) -> str:
"""Validate and normalize a deployment profile name."""
diff --git a/headroom/install/state.py b/headroom/install/state.py
index 9102dc74c..e757902b4 100644
--- a/headroom/install/state.py
+++ b/headroom/install/state.py
@@ -12,7 +12,16 @@ from pathlib import Path
from typing import Any
from .models import ArtifactRecord, DeploymentManifest, ManagedMutation, iso_utc_now
-from .paths import deploy_root, manifest_path, profile_root, recovery_manifest_path
+from .paths import (
+ OWNER_ONLY_DIR_MODE,
+ OWNER_ONLY_FILE_MODE,
+ POSIX_MODES_ENFORCED,
+ chmod_owner_only,
+ deploy_root,
+ manifest_path,
+ profile_root,
+ recovery_manifest_path,
+)
logger = logging.getLogger(__name__)
@@ -29,6 +38,15 @@ def _atomic_write_text(path: Path, data: str) -> None:
both POSIX and Windows). A crash between truncate and full write therefore
leaves either the previous file or the complete new one on disk, never a
truncated manifest.
+
+ The file is owner-only. ``manifest.base_env`` holds whatever
+ ``headroom install --env KEY=VALUE`` was given, and that is the supported
+ way to hand a provider API key to a supervised proxy (supervisors start
+ from a bare environment), so the manifest must be assumed to contain
+ secrets. :func:`tempfile.mkstemp` already creates the temporary file 0600
+ and :func:`os.replace` carries that mode across, but the chmod is explicit
+ so the guarantee survives a future rewrite of this function and is pinned
+ by a test rather than inherited by accident.
"""
directory = path.parent
fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=f".{path.name}.", suffix=".tmp")
@@ -38,6 +56,7 @@ def _atomic_write_text(path: Path, data: str) -> None:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
+ chmod_owner_only(tmp_path, OWNER_ONLY_FILE_MODE)
os.replace(tmp_path, path)
except BaseException:
tmp_path.unlink(missing_ok=True)
@@ -48,9 +67,39 @@ def _manifest_json(manifest: DeploymentManifest) -> str:
return json.dumps(asdict(manifest), indent=2) + "\n"
-def _save_manifest_at(path: Path, manifest: DeploymentManifest, *, strict: bool) -> None:
+def _narrow_profile_root(root: Path) -> None:
+ """Make a deployment profile directory owner-only.
+
+ ``exist_ok=True`` leaves a pre-existing directory's mode alone, and a
+ profile created before owner-only modes is 0755, so narrow it on every save
+ rather than only at creation.
+
+ Not fatal, unlike the runner script: the manifest itself is created through
+ ``mkstemp``, which is 0600 from birth, so a directory that could not be
+ narrowed weakens the outer layer without exposing the file. Warn rather
+ than abandon a deployment over it.
+ """
+ if not chmod_owner_only(root, OWNER_ONLY_DIR_MODE) and POSIX_MODES_ENFORCED:
+ logger.warning(
+ "Deployment profile directory %s is not owner-only; the "
+ "manifest inside it is still 0o%o, but other local users can "
+ "list the directory.",
+ root,
+ OWNER_ONLY_FILE_MODE,
+ )
+
+
+def _save_manifest_at(
+ path: Path,
+ manifest: DeploymentManifest,
+ *,
+ strict: bool,
+ owner_only_dir: bool = False,
+) -> None:
root = path.parent
root.mkdir(parents=True, exist_ok=True)
+ if owner_only_dir:
+ _narrow_profile_root(root)
manifest.updated_at = iso_utc_now()
try:
_atomic_write_text(path, _manifest_json(manifest))
@@ -66,9 +115,16 @@ def save_manifest(manifest: DeploymentManifest) -> None:
The write is atomic so an interrupted save (SIGKILL, system restart, OOM)
cannot leave a truncated ``manifest.json`` behind. Gracefully handles
read-only filesystems by logging a warning instead of crashing.
+
+ The profile directory and the manifest are owner-only: ``base_env`` carries
+ whatever ``headroom install --env`` was given, which is the supported way to
+ hand a provider API key to a supervised proxy. See
+ :data:`headroom.install.paths.OWNER_ONLY_DIR_MODE`.
"""
try:
- _save_manifest_at(manifest_path(manifest.profile), manifest, strict=False)
+ _save_manifest_at(
+ manifest_path(manifest.profile), manifest, strict=False, owner_only_dir=True
+ )
except OSError as e:
logger.warning("Cannot save deployment manifest: %s — continuing without persistence", e)
@@ -76,7 +132,7 @@ def save_manifest(manifest: DeploymentManifest) -> None:
def save_manifest_strict(manifest: DeploymentManifest) -> None:
"""Persist a manifest and propagate errors when recovery depends on it."""
- _save_manifest_at(manifest_path(manifest.profile), manifest, strict=True)
+ _save_manifest_at(manifest_path(manifest.profile), manifest, strict=True, owner_only_dir=True)
def save_recovery_manifest(manifest: DeploymentManifest) -> None:
diff --git a/headroom/install/supervisors.py b/headroom/install/supervisors.py
index 584d95128..35c01e9e0 100644
--- a/headroom/install/supervisors.py
+++ b/headroom/install/supervisors.py
@@ -21,6 +21,10 @@ from headroom._subprocess import run
from .models import ArtifactRecord, DeploymentManifest, SupervisorKind
from .paths import (
+ OWNER_ONLY_FILE_MODE,
+ OWNER_ONLY_SCRIPT_MODE,
+ POSIX_MODES_ENFORCED,
+ chmod_owner_only,
unix_ensure_script_path,
unix_run_script_path,
windows_ensure_cmd_path,
@@ -47,6 +51,32 @@ def _is_windows() -> bool:
return sys.platform.startswith("win")
+def _write_private_text(path: Path, data: str, mode: int) -> None:
+ """Atomically replace a secret-bearing runner with a private new inode.
+
+ Creating the temporary file exclusively avoids following a replacement
+ hard link. Restrict it before publishing; a failed write, restriction or
+ replacement leaves the previous runner and unrelated files untouched.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ temporary = Path(name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ if hasattr(os, "fchmod"):
+ os.fchmod(handle.fileno(), mode)
+ handle.write(data)
+ if not chmod_owner_only(temporary, mode) and POSIX_MODES_ENFORCED:
+ raise click.ClickException(
+ f"Refusing to write {path}: permissions could not be restricted "
+ f"to {oct(mode)}, and the file carries any API key passed via "
+ f"`headroom install --env`. Fix directory permissions and re-run."
+ )
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
def _validated_env_items(env: dict[str, str] | None) -> list[tuple[str, str]]:
items = list((env or {}).items())
for name, _value in items:
@@ -101,14 +131,19 @@ def _render_unix_runner(
export_lines = "".join(
f"export {name}={shlex.quote(value)}\n" for name, value in _validated_env_items(env)
)
- path.write_text(
+ # 0700, not 0755: `export_lines` can contain a provider API key in
+ # cleartext (see `_write_private_text`). The supervisor runs this script as
+ # the installing user for a user-scope install and as root for a
+ # system-scope one, so dropping group/other loses nothing.
+ _write_private_text(
+ path,
"#!/usr/bin/env bash\nset -euo pipefail\n"
+ export_lines
+ "exec "
+ " ".join(shlex.quote(x) for x in command)
- + "\n"
+ + "\n",
+ OWNER_ONLY_SCRIPT_MODE,
)
- path.chmod(0o755)
return ArtifactRecord(kind="script", path=str(path))
@@ -124,9 +159,17 @@ def _render_windows_runner(
env_lines = "".join(
f"$env:{name} = {_powershell_literal(value)}\n" for name, value in _validated_env_items(env)
)
- ps1_path.write_text(
- f"$ErrorActionPreference = 'Stop'\n{env_lines}& {escaped}\nexit $LASTEXITCODE\n"
+ # The .ps1 carries `$env:` assignments that can include a provider API key,
+ # so it is owner-only like its POSIX counterpart. Windows resolves access
+ # by ACL rather than by these bits, but the mode still matters when the
+ # profile directory is read from WSL, a backup, or a synced home.
+ _write_private_text(
+ ps1_path,
+ f"$ErrorActionPreference = 'Stop'\n{env_lines}& {escaped}\nexit $LASTEXITCODE\n",
+ OWNER_ONLY_FILE_MODE,
)
+ # The .cmd shim holds no secrets — it only invokes the .ps1 — so it keeps a
+ # conventional mode.
cmd_path.write_text(
'@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0'
+ ps1_path.name
diff --git a/pyproject.toml b/pyproject.toml
index c46e21375..b8ecfa89d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -356,8 +356,13 @@ dev = [
all = [
"headroom-ai[proxy,code,ml,memory,relevance,image,reports,otel,evals,voice,html,mcp,spreadsheet]",
]
-# Sandbox: a lean proxy with ALL torch-free capability — for running Headroom in
-# a locked-down/low-resource sandbox and offloading heavy ML elsewhere.
+# Lean: a proxy with ALL torch-free capability — for running Headroom in a
+# constrained or low-resource environment and offloading heavy ML elsewhere.
+#
+# This is a DEPENDENCY PROFILE. It provides no isolation, no confinement and
+# no privilege reduction of any kind. It was previously named `sandbox`, which
+# invited exactly that assumption; `sandbox` is retained below as a
+# deprecated alias for one release so existing installs keep resolving.
#
# = [all] MINUS:
# - image (SigLIP/OCR — excluded by request)
@@ -368,13 +373,18 @@ all = [
# - memory + evals (both pull sentence-transformers -> torch, i.e. the very
# ML weight a sandbox avoids; evals is a dev/test harness, not a
# runtime feature). Opt back in explicitly if you accept torch:
-# pip install headroom-ai[sandbox,memory]
+# pip install headroom-ai[lean,memory]
#
# Everything kept here is torch-free: code-aware compression (tree-sitter),
# embedding relevance (fastembed), HTML/spreadsheet ingestion, reports, OTel.
-sandbox = [
+lean = [
"headroom-ai[proxy,code,relevance,reports,otel,html,mcp,spreadsheet]",
]
+# Deprecated alias for `lean`, kept for one release. The name implied an
+# isolation guarantee the extra never provided. Remove after 0.39.x.
+sandbox = [
+ "headroom-ai[lean]",
+]
[project.scripts]
headroom = "headroom.cli:main"
diff --git a/run-all-plugins.sh b/run-all-plugins.sh
index 2570c5a65..8c5a78a8b 100755
--- a/run-all-plugins.sh
+++ b/run-all-plugins.sh
@@ -5,7 +5,7 @@
# to the Kompress-v2 Modal endpoint. Then confirm everything loaded.
#
# Plugins : lossless_guard, skill_search, observability, tier_router, tool_search
-# Extra : headroom-ai[sandbox] (torch-free proxy; ML offloaded to Modal)
+# Extra : headroom-ai[lean] (torch-free proxy; ML offloaded to Modal)
# Profile : coding (HEADROOM_SAVINGS_PROFILE) + cache mode (prefix-cache safe)
#
# Secrets are SOURCED from ~/env.txt and ~/.headroom/plugins.env — never inlined.
@@ -29,7 +29,7 @@ source "$VENV/bin/activate"
PY="$VENV/bin/python"
# ── 2. install (guarded) ──────────────────────────────────────────────────────
-# headroom-ai[sandbox] pulls proxy,code,relevance,reports,otel,html,mcp,spreadsheet
+# headroom-ai[lean] pulls proxy,code,relevance,reports,otel,html,mcp,spreadsheet
# (all torch-free — heavy ML is offloaded to the Modal Kompress endpoint below).
# The 5 plugins install --no-deps so pip won't drag PyPI's headroom-ai over the
# local editable one; headroom-license is their shared Ed25519 verifier.
@@ -44,14 +44,14 @@ if [ "$need_install" = "1" ]; then
if [ -n "$avail" ] && [ "$avail" -lt 2 ]; then
echo "!! <2Gi free — aborting before heavy install (free space, then re-run)"; exit 1
fi
- echo "▶ installing pip+maturin, then headroom-ai[sandbox] + license + 5 plugins (editable)…"
+ echo "▶ installing pip+maturin, then headroom-ai[lean] + license + 5 plugins (editable)…"
"$PY" -m pip install -U pip maturin
# litellm >=1.92 ships an sdist-only Rust bridge whose AWS-SDK crates need rustc>=1.94.1;
# the default rustup toolchain here is older (pip builds litellm in a temp dir that misses
# the repo's 1.95 pin), so pin to the last pure-Python wheel line (1.91.4). Satisfies
# headroom's litellm>=1.86.2,<2.0 and skips the Rust build entirely.
"$PY" -m pip install "litellm<1.92"
- "$PY" -m pip install -e "${HR}[sandbox]" "litellm<1.92"
+ "$PY" -m pip install -e "${HR}[lean]" "litellm<1.92"
"$PY" -m pip install -e /Users/tcms/demo/headroom-license
for p in lossless-guard skill-search observability tier-router tool-search; do
"$PY" -m pip install -e "/Users/tcms/demo/headroom-${p}" --no-deps
diff --git a/tests/test_install/test_owner_only_modes.py b/tests/test_install/test_owner_only_modes.py
new file mode 100644
index 000000000..470f42a78
--- /dev/null
+++ b/tests/test_install/test_owner_only_modes.py
@@ -0,0 +1,242 @@
+"""A mode that could not be set must never be reported as if it had been.
+
+``chmod_owner_only`` used to swallow every ``OSError`` and return nothing, so
+``save_manifest`` and ``_write_private_text`` continued as though the documented
+0600/0700 modes were established. Both of its callers NARROW A PRE-EXISTING
+INODE rather than create one -- a profile directory made before these modes
+existed is 0755, and a runner script rewritten through ``O_TRUNC`` keeps the
+mode it already had -- so on those paths the chmod is the only thing between a
+provider API key and every local user.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import stat
+from pathlib import Path
+
+import click
+import pytest
+
+from headroom.install import paths as install_paths
+from headroom.install import state as install_state
+from headroom.install import supervisors
+from headroom.install.paths import (
+ OWNER_ONLY_SCRIPT_MODE,
+ POSIX_MODES_ENFORCED,
+ chmod_owner_only,
+)
+
+# Windows governs access with ACLs; chmod there cannot establish these modes, so
+# asserting the bits would test the platform rather than the code.
+posix_modes_only = pytest.mark.skipif(
+ not POSIX_MODES_ENFORCED, reason="POSIX mode bits are not enforced on this platform"
+)
+
+
+def _raise_oserror(*_args, **_kwargs):
+ raise OSError(1, "Operation not permitted")
+
+
+class TestChmodOwnerOnlyReportsItsResult:
+ @posix_modes_only
+ def test_returns_true_and_narrows_an_existing_file(self, tmp_path):
+ target = tmp_path / "run-headroom.sh"
+ target.write_text("export ANTHROPIC_API_KEY=sk-live\n")
+ # The precondition this whole module exists for: a script left behind
+ # by a version that predates these modes. Spelled with `stat` flags
+ # because a bare 0o755 literal reads as an overly-permissive chmod.
+ os.chmod(target, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
+
+ assert chmod_owner_only(target, 0o700) is True
+ assert stat.S_IMODE(target.stat().st_mode) == 0o700
+
+ def test_returns_false_and_warns_when_chmod_raises(self, tmp_path, monkeypatch, caplog):
+ """The case the old code swallowed."""
+ target = tmp_path / "run-headroom.sh"
+ target.write_text("export ANTHROPIC_API_KEY=sk-live\n")
+ monkeypatch.setattr("pathlib.Path.chmod", _raise_oserror)
+
+ with caplog.at_level(logging.WARNING, logger="headroom.install.paths"):
+ assert chmod_owner_only(target, 0o700) is False
+
+ assert any("Could not restrict" in r.getMessage() for r in caplog.records)
+
+ def test_returns_false_when_chmod_succeeds_but_does_not_take(self, tmp_path, monkeypatch):
+ """Windows: ``chmod`` neither raises nor works, so the call cannot be
+ trusted and the mode has to be read back."""
+ target = tmp_path / "manifest.json"
+ target.write_text("{}")
+ monkeypatch.setattr("pathlib.Path.chmod", lambda *_a, **_k: None)
+
+ assert chmod_owner_only(target, 0o600) is False
+
+ def test_returns_false_when_the_path_is_gone(self, tmp_path, monkeypatch):
+ assert chmod_owner_only(tmp_path / "absent", 0o600) is False
+
+
+class TestRunnerScriptsFailClosed:
+ def test_replacement_never_truncates_a_racing_hard_link(self, tmp_path, monkeypatch):
+ target = tmp_path / "run-headroom.sh"
+ unrelated = tmp_path / "unrelated.txt"
+ unrelated.write_text("unrelated original")
+ original_open = os.open
+
+ def racing_open(path, flags, *args, **kwargs):
+ if Path(path) == target and not target.exists():
+ os.link(unrelated, target)
+ return original_open(path, flags, *args, **kwargs)
+
+ monkeypatch.setattr(os, "open", racing_open)
+ supervisors._write_private_text(target, "export KEY=fake-secret\n", OWNER_ONLY_SCRIPT_MODE)
+ assert unrelated.read_text() == "unrelated original"
+ assert target.read_text() == "export KEY=fake-secret\n"
+
+ def test_replacement_does_not_modify_a_link_inserted_before_publish(
+ self, tmp_path, monkeypatch
+ ):
+ target = tmp_path / "run-headroom.sh"
+ target.write_text("previous runner")
+ unrelated = tmp_path / "unrelated.txt"
+ unrelated.write_text("unrelated original")
+ original_replace = os.replace
+ attacked = []
+
+ def racing_replace(source, destination):
+ target.unlink()
+ os.link(unrelated, target)
+ attacked.append(True)
+ return original_replace(source, destination)
+
+ monkeypatch.setattr(os, "replace", racing_replace)
+ supervisors._write_private_text(target, "export KEY=fake-secret\n", OWNER_ONLY_SCRIPT_MODE)
+ assert attacked == [True]
+ assert unrelated.read_text() == "unrelated original"
+ assert target.read_text() == "export KEY=fake-secret\n"
+
+ def test_failed_restriction_preserves_the_previous_runner(self, tmp_path, monkeypatch):
+ target = tmp_path / "run-headroom.sh"
+ target.write_text("previous runner")
+ monkeypatch.setattr(supervisors, "POSIX_MODES_ENFORCED", True)
+ monkeypatch.setattr(supervisors, "chmod_owner_only", lambda *_args: False)
+ with pytest.raises(click.ClickException):
+ supervisors._write_private_text(
+ target, "export KEY=fake-secret\n", OWNER_ONLY_SCRIPT_MODE
+ )
+ assert target.read_text() == "previous runner"
+ assert list(tmp_path.iterdir()) == [target]
+
+ def test_failed_atomic_replace_preserves_the_previous_runner(self, tmp_path, monkeypatch):
+ target = tmp_path / "run-headroom.sh"
+ target.write_text("previous runner")
+
+ def reject_replace(*args):
+ raise PermissionError("replacement denied")
+
+ monkeypatch.setattr(os, "replace", reject_replace)
+ with pytest.raises(PermissionError):
+ supervisors._write_private_text(
+ target, "export KEY=fake-secret\n", OWNER_ONLY_SCRIPT_MODE
+ )
+ assert target.read_text() == "previous runner"
+ assert list(tmp_path.iterdir()) == [target]
+
+ def test_refuses_to_leave_a_script_it_could_not_restrict(self, tmp_path, monkeypatch):
+ """A runner script ``export``s the API key in cleartext, so a
+ half-protected one must not survive the call."""
+ target = tmp_path / "run-headroom.sh"
+ monkeypatch.setattr(install_paths, "POSIX_MODES_ENFORCED", True)
+ monkeypatch.setattr(supervisors, "POSIX_MODES_ENFORCED", True)
+ monkeypatch.setattr("pathlib.Path.chmod", _raise_oserror)
+
+ with pytest.raises(click.ClickException) as excinfo:
+ supervisors._write_private_text(
+ target, "export ANTHROPIC_API_KEY=sk-live\n", OWNER_ONLY_SCRIPT_MODE
+ )
+
+ assert "could not be restricted" in str(excinfo.value)
+ assert not target.exists(), "a key-bearing script must not be left behind"
+
+ def test_does_not_fail_closed_where_posix_modes_are_advisory(self, tmp_path, monkeypatch):
+ """On Windows the bits never take, so this check must not brick installs."""
+ target = tmp_path / "run-headroom.sh"
+ monkeypatch.setattr(supervisors, "POSIX_MODES_ENFORCED", False)
+ monkeypatch.setattr("pathlib.Path.chmod", _raise_oserror)
+
+ supervisors._write_private_text(target, "echo hi\n", OWNER_ONLY_SCRIPT_MODE)
+
+ assert target.read_text() == "echo hi\n"
+
+ @posix_modes_only
+ def test_rewriting_an_old_script_never_writes_secrets_at_its_old_mode(
+ self, tmp_path, monkeypatch
+ ):
+ """``O_TRUNC`` keeps an existing inode's mode, so rewriting a 0755
+ script in place would put the key in a world-readable file until the
+ chmod ran. The new content must land in a file created owner-only --
+ proven here by taking the after-the-fact chmod away."""
+ target = tmp_path / "run-headroom.sh"
+ target.write_text("#!/usr/bin/env bash\n")
+ os.chmod(target, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
+ monkeypatch.setattr(supervisors, "chmod_owner_only", lambda *_a: True)
+
+ supervisors._write_private_text(
+ target, "export ANTHROPIC_API_KEY=sk-live\n", OWNER_ONLY_SCRIPT_MODE
+ )
+
+ assert target.read_text() == "export ANTHROPIC_API_KEY=sk-live\n"
+ assert stat.S_IMODE(target.stat().st_mode) == OWNER_ONLY_SCRIPT_MODE
+
+ def test_a_writable_script_keeps_working(self, tmp_path):
+ target = tmp_path / "run-headroom.sh"
+ supervisors._write_private_text(target, "echo hi\n", OWNER_ONLY_SCRIPT_MODE)
+
+ assert target.read_text() == "echo hi\n"
+ if POSIX_MODES_ENFORCED:
+ assert stat.S_IMODE(target.stat().st_mode) == OWNER_ONLY_SCRIPT_MODE
+
+
+class TestManifestWarnsButPersists:
+ def test_unrestrictable_profile_dir_warns_and_still_saves(self, tmp_path, monkeypatch, caplog):
+ """The manifest is born 0600 from ``mkstemp``, so a directory that could
+ not be narrowed weakens the outer layer without exposing the file --
+ warn, but do not abandon the deployment."""
+ # Patch the deployment root itself, not HOME: Windows resolves the
+ # home directory without consulting $HOME, so a HOME-only patch writes
+ # this fixture key into the real user's default profile.
+ deploy = tmp_path / "deploy"
+ monkeypatch.setattr("headroom.install.paths._paths.deploy_root", lambda: deploy)
+ monkeypatch.setattr(install_state, "POSIX_MODES_ENFORCED", True)
+
+ real_chmod = os.chmod
+
+ def _fail_on_directories(path, mode, *args, **kwargs):
+ if os.path.isdir(path):
+ raise OSError(1, "Operation not permitted")
+ return real_chmod(path, mode, *args, **kwargs)
+
+ monkeypatch.setattr(os, "chmod", _fail_on_directories)
+
+ manifest = install_state.DeploymentManifest(
+ profile="default",
+ preset="persistent-service",
+ runtime_kind="python",
+ supervisor_kind="service",
+ scope="user",
+ provider_mode="manual",
+ targets=["claude"],
+ port=8787,
+ host="127.0.0.1",
+ backend="anthropic",
+ base_env={"ANTHROPIC_API_KEY": "sk-live"},
+ )
+ with caplog.at_level(logging.WARNING):
+ install_state.save_manifest(manifest)
+
+ path = install_state.manifest_path("default")
+ assert path.parent.parent == deploy, f"{path} escaped the test deployment root"
+ assert path.exists(), "a warning must not cost the operator their manifest"
+ if POSIX_MODES_ENFORCED:
+ assert stat.S_IMODE(path.stat().st_mode) == install_paths.OWNER_ONLY_FILE_MODE
+ assert any("not owner-only" in r.getMessage() for r in caplog.records)
diff --git a/tests/test_install/test_state.py b/tests/test_install/test_state.py
index 931572f85..802e3247c 100644
--- a/tests/test_install/test_state.py
+++ b/tests/test_install/test_state.py
@@ -4,11 +4,13 @@ import json
import logging
import os
import stat
+import sys
from pathlib import Path
import pytest
from headroom.install.models import ArtifactRecord, DeploymentManifest, ManagedMutation
+from headroom.install.paths import manifest_path, profile_root
from headroom.install.state import (
ManifestError,
delete_manifest,
@@ -235,6 +237,48 @@ def test_delete_manifest_removes_profile_root(monkeypatch, tmp_path: Path) -> No
assert not extra_file.parent.exists()
+ sys.platform.startswith("win"),
+ reason="POSIX mode bits are advisory on Windows, where access is governed by ACLs",
+)
+def test_save_manifest_writes_owner_only(monkeypatch, tmp_path: Path) -> None:
+ """`base_env` can hold a provider API key, so the manifest is 0600/0700.
+
+ `headroom install --env ANTHROPIC_API_KEY=...` is the supported way to give
+ a supervised proxy a credential (supervisors start from a bare
+ environment), and the value is serialized verbatim. At the common 022 umask
+ a plain write would leave a live key world-readable.
+ """
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ manifest = _manifest()
+ manifest.base_env = {"ANTHROPIC_API_KEY": "sk-ant-api03-not-a-real-key"}
+
+ save_manifest(manifest)
+
+ path = manifest_path("default")
+ assert "sk-ant-api03-not-a-real-key" in path.read_text(encoding="utf-8")
+ assert path.stat().st_mode & 0o777 == 0o600
+ assert path.parent.stat().st_mode & 0o777 == 0o700
+
+
+ sys.platform.startswith("win"),
+ reason="POSIX mode bits are advisory on Windows, where access is governed by ACLs",
+)
+def test_save_manifest_narrows_a_profile_directory_created_before_this_change(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """An upgrade must fix an existing 0755 profile directory, not only new ones."""
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ root = profile_root("default")
+ root.mkdir(parents=True)
+ root.chmod(0o755)
+
+ save_manifest(_manifest())
+
+ assert root.stat().st_mode & 0o777 == 0o700
+
+
def test_delete_manifest_propagates_removal_failure(monkeypatch, tmp_path: Path) -> None:
monkeypatch.setattr(Path, "home", lambda: tmp_path)
root = tmp_path / ".headroom" / "deploy" / "default"
diff --git a/tests/test_install/test_supervisors.py b/tests/test_install/test_supervisors.py
index a6fdfc650..8d43c528d 100644
--- a/tests/test_install/test_supervisors.py
+++ b/tests/test_install/test_supervisors.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import subprocess
+import sys
from pathlib import Path
import click
@@ -1184,6 +1185,57 @@ def test_remove_supervisor_darwin_and_windows(monkeypatch, tmp_path: Path) -> No
assert calls == windows_cleanup + windows_cleanup
+ sys.platform.startswith("win"),
+ reason="POSIX mode bits are advisory on Windows, where access is governed by ACLs",
+)
+def test_render_runner_scripts_are_owner_only_because_they_export_secrets(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """0700, not 0755: the export lines can carry a provider API key.
+
+ `headroom install --env ANTHROPIC_API_KEY=...` lands in `base_env`, and
+ these scripts `export` every entry in cleartext because launchd/systemd
+ hand the process a bare environment. At 0755 that put a live key in a
+ world-readable file. The supervisor runs the script as the installing user
+ (user scope) or as root (system scope), so neither needs the other bits.
+ """
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")
+ monkeypatch.setattr(
+ "headroom.install.supervisors.resolve_headroom_command", lambda: ["headroom"]
+ )
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ manifest = _manifest(base_env={"ANTHROPIC_API_KEY": "sk-ant-api03-not-a-real-key"})
+
+ records = render_runner_scripts(manifest)
+
+ assert records
+ for record in records:
+ path = Path(record.path)
+ content = path.read_text(encoding="utf-8")
+ assert "export ANTHROPIC_API_KEY=sk-ant-api03-not-a-real-key" in content
+ mode = path.stat().st_mode & 0o777
+ assert mode == 0o700, f"{path.name} is {mode:04o}, exposing an API key"
+
+
+ sys.platform.startswith("win"),
+ reason="POSIX mode bits are advisory on Windows, where access is governed by ACLs",
+)
+def test_render_unix_runner_narrows_a_script_written_by_an_earlier_version(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """Re-running `install apply` must fix an existing 0755 runner script."""
+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "linux")
+ path = tmp_path / "run-headroom.sh"
+ path.write_text("#!/usr/bin/env bash\n")
+ path.chmod(0o755)
+
+ _render_unix_runner(path, ["headroom", "proxy"], {"ANTHROPIC_API_KEY": "sk-ant-x"})
+
+ assert path.stat().st_mode & 0o777 == 0o700
+
+
@pytest.mark.parametrize(
("failed_command", "failure_code"), [("sc.exe", 5), ("schtasks", 1), ("schtasks", 5)]
)
diff --git a/tests/test_packaging_extras_and_security_docs.py b/tests/test_packaging_extras_and_security_docs.py
new file mode 100644
index 000000000..f520d21d6
--- /dev/null
+++ b/tests/test_packaging_extras_and_security_docs.py
@@ -0,0 +1,231 @@
+"""A-10: the `sandbox` extra promised isolation it never provided, and
+SECURITY.md drifted four minor releases behind the code.
+
+Both are documentation defects with a security consequence: a reader who
+believes either one makes a deployment decision on a false premise. These tests
+pin the rename's compatibility alias and make the stale version table — the part
+that silently rots — a build failure instead of a reviewer's job.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+try:
+ import tomllib
+except ModuleNotFoundError: # Python 3.10
+ import tomli as tomllib # type: ignore[no-redef]
+
+_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _pyproject() -> dict:
+ with (_ROOT / "pyproject.toml").open("rb") as fh:
+ return tomllib.load(fh)
+
+
+def test_sandbox_alias_still_resolves_to_the_lean_profile() -> None:
+ """The old name must keep working for one release.
+
+ `sandbox` was renamed to `lean`; anything already installing the old extra
+ (our own python-314-wheels CI job did) must not break on upgrade.
+ """
+ extras = _pyproject()["project"]["optional-dependencies"]
+
+ assert "lean" in extras, "the renamed extra is missing"
+ assert "sandbox" in extras, "the deprecated alias was removed too early"
+ assert extras["sandbox"] == ["headroom-ai[lean]"], (
+ "the alias must forward to `lean` rather than duplicate its dependency "
+ "list, or the two will drift"
+ )
+
+
+def test_lean_profile_stays_torch_free() -> None:
+ """The profile's whole purpose is avoiding torch; guard it by name.
+
+ A torch-pulling extra added here would quietly defeat the reason anyone
+ selects this profile.
+ """
+ extras = _pyproject()["project"]["optional-dependencies"]
+ (spec,) = extras["lean"]
+ selected = set(re.search(r"\[(.*)\]", spec).group(1).split(","))
+
+ torch_pulling = {"ml", "memory", "evals", "image", "voice", "pytorch-mps"}
+ assert not (selected & torch_pulling), (
+ f"`lean` must stay torch-free; it now selects {sorted(selected & torch_pulling)}"
+ )
+
+
+def test_security_policy_supports_the_latest_release_without_a_version_number() -> None:
+ """SECURITY.md's table sat at 0.27.x while the code shipped 0.38.0.
+
+ A supported-versions table that lags is worse than none: it tells a reporter
+ their release is unsupported when it is the current one. The policy now
+ supports "the latest release on PyPI", which cannot go stale; pin that, and
+ fail if a hard-coded version row (the thing that rotted) comes back.
+ """
+ text = (_ROOT / "SECURITY.md").read_text(encoding="utf-8")
+ table = text.split("## Supported Versions", 1)[1].split("\n## ", 1)[0]
+
+ assert re.search(r"^\| Latest release on PyPI \| :white_check_mark: +\|$", table, re.M), (
+ "SECURITY.md must list the latest PyPI release as the supported version"
+ )
+ pinned = re.findall(r"^\|[^|]*\d+\.\d+(?:\.x)?[^|]*\|", table, re.M)
+ assert not pinned, f"SECURITY.md pins a version number that will go stale: {pinned}"
+
+
+def test_security_policy_does_not_claim_blanket_no_credential_storage() -> None:
+ """`headroom copilot login` writes an OAuth refresh token to disk.
+
+ The policy used to say "We never store or log API keys", which is broader
+ than the code supports. Keep the honest wording.
+ """
+ text = (_ROOT / "SECURITY.md").read_text(encoding="utf-8")
+
+ assert "never store or log API keys" not in text, (
+ "the blanket no-credential-storage claim is contradicted by "
+ "headroom/copilot_auth.py, which persists the Copilot OAuth refresh token"
+ )
+ assert "copilot_auth.json" in text, "the one stored credential must stay documented"
+
+
+# --- The persistent-install credential path -------------------------------
+#
+# The assertions above are negative string checks: they stop the *old* wording
+# coming back, but they would happily pass while the replacement wording is
+# itself false (review of PR #3727 — the first correction claimed Headroom
+# "does not write [API keys] to disk", which `headroom install --env` falsifies).
+#
+# So the tests below drive the real install path with a provider key, read what
+# actually lands in `~/.headroom/deploy/<profile>/`, and compare it against the
+# claims parsed out of SECURITY.md. A change to either side that is not matched
+# on the other fails here.
+
+_SECRET = "sk-ant-api03-not-a-real-key"
+
+_MANIFEST_MODE_CLAIM = re.compile(
+ r"`~/\.headroom/deploy/<profile>/manifest\.json` \(mode `(0[0-7]{3})`\)"
+)
+_SCRIPT_MODE_CLAIM = re.compile(
+ r"`run-headroom\.sh` / `ensure-headroom\.sh` \(mode `(0[0-7]{3})`\)"
+)
+_DIR_MODE_CLAIM = re.compile(r"in the same directory \(mode `(0[0-7]{3})`\)")
+
+
+def _security_policy_prose() -> str:
+ """SECURITY.md with its line wrapping flattened, so claims match as written."""
+ return re.sub(r"\s+", " ", (_ROOT / "SECURITY.md").read_text(encoding="utf-8"))
+
+
+def _claimed_mode(pattern: re.Pattern[str]) -> int:
+ match = pattern.search(_security_policy_prose())
+ assert match is not None, (
+ f"SECURITY.md no longer states the mode matched by {pattern.pattern!r}. The "
+ "persistent-install credential path must keep documenting where a key "
+ "passed to `headroom install --env` is written and how it is protected."
+ )
+ return int(match.group(1), 8)
+
+
+def _install_with_a_provider_key(deploy: Path) -> tuple[Path, Path, Path]:
+ """Run the real planner/state/supervisor path with a key in ``--env``.
+
+ Returns the profile directory, its manifest and its foreground runner
+ script. Imports are local so the module-level packaging assertions above
+ still run if the install package fails to import.
+ """
+ from headroom.install.paths import manifest_path, profile_root, unix_run_script_path
+ from headroom.install.planner import build_manifest
+ from headroom.install.state import save_manifest
+ from headroom.install.supervisors import render_runner_scripts
+
+ assert profile_root("default").parent == deploy, "the deploy-root monkeypatch did not take"
+
+ manifest = build_manifest(
+ profile="default",
+ preset="persistent-service",
+ runtime_kind="python",
+ scope="user",
+ provider_mode="manual",
+ targets=[],
+ port=8787,
+ backend="anthropic",
+ anyllm_provider=None,
+ region=None,
+ proxy_mode="passthrough",
+ memory_enabled=False,
+ telemetry_enabled=False,
+ image="ghcr.io/headroomlabs-ai/headroom:latest",
+ extra_env={"ANTHROPIC_API_KEY": _SECRET},
+ )
+ save_manifest(manifest)
+ render_runner_scripts(manifest)
+ return profile_root("default"), manifest_path("default"), unix_run_script_path("default")
+
+
+ sys.platform.startswith("win"),
+ reason="POSIX mode bits are advisory on Windows, where access is governed by ACLs",
+)
+def test_install_env_persists_a_provider_key_exactly_as_the_policy_describes(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """`--env ANTHROPIC_API_KEY=...` really does write the key to disk.
+
+ This is deliberate — supervisors start from a bare environment, so `--env`
+ is the only channel that reaches a supervised proxy — but it means the
+ policy may not claim keys are never written. Pin both halves: that the key
+ lands where SECURITY.md says, and that it lands owner-only.
+ """
+ # Patch the deployment root itself, not HOME: Windows resolves the home
+ # directory without consulting $HOME, so a HOME-only patch writes this
+ # fixture key into the real user's profile.
+ deploy = tmp_path / "deploy"
+ monkeypatch.setattr("headroom.install.paths._paths.deploy_root", lambda: deploy)
+
+ profile_dir, manifest_file, run_script = _install_with_a_provider_key(deploy)
+
+ # 1. What lands on disk. Both files carry the key in cleartext; the runner
+ # script `export`s it because launchd/systemd hand the process nothing.
+ assert manifest_file.exists(), "a persistent install must write a manifest"
+ assert _SECRET in manifest_file.read_text(encoding="utf-8"), (
+ "the key passed to --env is stored verbatim in manifest.json; if that "
+ "stopped being true, SECURITY.md and the --env help must change with it"
+ )
+ assert run_script.exists(), "a persistent install must write a runner script"
+ assert f"export ANTHROPIC_API_KEY={_SECRET}" in run_script.read_text(encoding="utf-8")
+
+ # 2. With what protection — read back out of the policy document, so the
+ # two cannot drift.
+ assert manifest_file.stat().st_mode & 0o777 == _claimed_mode(_MANIFEST_MODE_CLAIM)
+ assert run_script.stat().st_mode & 0o777 == _claimed_mode(_SCRIPT_MODE_CLAIM)
+ assert profile_dir.stat().st_mode & 0o777 == _claimed_mode(_DIR_MODE_CLAIM)
+
+ # 3. And, concretely: nothing in that directory is readable by group or
+ # other, whatever the umask was.
+ for path in [profile_dir, *profile_dir.iterdir()]:
+ assert not path.stat().st_mode & 0o077, f"{path.name} is readable beyond its owner"
+
+
+def test_security_policy_discloses_the_persistent_install_credential_path() -> None:
+ """The policy must name the `--env` path, not just the Copilot token."""
+ prose = _security_policy_prose()
+
+ assert "does not write them to disk" not in prose, (
+ "`headroom install --env ANTHROPIC_API_KEY=...` writes the key to "
+ "~/.headroom/deploy/<profile>/, so a blanket 'not written to disk' "
+ "claim is false"
+ )
+ assert "headroom install --env KEY=VALUE" in prose, (
+ "the supported way to hand a supervised proxy a provider key must be "
+ "documented as a credential-persistence path"
+ )
+ assert "~/.headroom/deploy/<profile>/manifest.json" in prose
+ assert "owner-only, not encrypted" in prose, (
+ "owner-only file modes are not encryption; the policy must say so "
+ "rather than let a reader infer the key is protected at rest"
+ )
diff --git a/uv.lock b/uv.lock
index b29e74e0b..743193d04 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1549,6 +1549,33 @@ langgraph = [
{ name = "langchain-openai" },
{ name = "langgraph" },
]
+lean = [
+ { name = "fastapi" },
+ { name = "fastembed", marker = "python_full_version < '3.14' or platform_machine != 'x86_64' or sys_platform != 'darwin'" },
+ { name = "httpx", extra = ["http2"] },
+ { name = "jinja2" },
+ { name = "magika", marker = "python_full_version < '3.14' or platform_machine != 'x86_64' or sys_platform != 'darwin'" },
+ { name = "mcp" },
+ { name = "numpy" },
+ { name = "onnxruntime", version = "1.23.2", source = { registry = "https://pypi.org/simple/" }, marker = "python_full_version < '3.14' and platform_machine == 'x86_64' and sys_platform == 'darwin'" },
+ { name = "onnxruntime", version = "1.26.0", source = { registry = "https://pypi.org/simple/" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
+ { name = "openai" },
+ { name = "openpyxl" },
+ { name = "opentelemetry-exporter-otlp-proto-http" },
+ { name = "opentelemetry-sdk" },
+ { name = "orjson", marker = "platform_python_implementation != 'PyPy'" },
+ { name = "sqlite-vec" },
+ { name = "starlette" },
+ { name = "trafilatura" },
+ { name = "transformers" },
+ { name = "tree-sitter" },
+ { name = "tree-sitter-language-pack" },
+ { name = "uvicorn" },
+ { name = "watchdog", marker = "python_full_version < '3.14' or sys_platform != 'darwin'" },
+ { name = "websockets" },
+ { name = "xlrd" },
+ { name = "zstandard" },
+]
mcp = [
{ name = "httpx" },
{ name = "mcp" },
@@ -1693,9 +1720,10 @@ requires-dist = [
{ name = "fastembed", marker = "(python_full_version < '3.14' and extra == 'relevance') or (platform_machine != 'x86_64' and extra == 'relevance') or (sys_platform != 'darwin' and extra == 'relevance')", specifier = ">=0.6.0" },
{ name = "filelock", specifier = ">=4.2.1" },
{ name = "gunicorn", marker = "sys_platform != 'win32' and extra == 'proxy-prod'", specifier = ">=21.0.0" },
+ { name = "headroom-ai", extras = ["lean"], marker = "extra == 'sandbox'" },
{ name = "headroom-ai", extras = ["proxy"], marker = "extra == 'proxy-prod'" },
{ name = "headroom-ai", extras = ["proxy", "code", "ml", "memory", "relevance", "image", "reports", "otel", "evals", "voice", "html", "mcp", "spreadsheet"], marker = "extra == 'all'" },
- { name = "headroom-ai", extras = ["proxy", "code", "relevance", "reports", "otel", "html", "mcp", "spreadsheet"], marker = "extra == 'sandbox'" },
+ { name = "headroom-ai", extras = ["proxy", "code", "relevance", "reports", "otel", "html", "mcp", "spreadsheet"], marker = "extra == 'lean'" },
{ name = "headroom-ai", extras = ["voice"], marker = "extra == 'voice-train'" },
{ name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'", specifier = ">=1.6.0" },
{ name = "hnswlib", marker = "extra == 'dev'", specifier = ">=0.8.0" },
@@ -1787,7 +1815,7 @@ requires-dist = [
{ name = "xlwt", marker = "extra == 'dev'", specifier = ">=1.3.0" },
{ name = "zstandard", marker = "extra == 'proxy'", specifier = ">=0.20.0" },
]
-provides-extras = ["proxy", "proxy-prod", "code", "ml", "memory", "vector", "memory-stack", "pytorch-mps", "relevance", "image", "reports", "spreadsheet", "otel", "anyllm", "langchain", "langgraph", "agno", "strands", "autogen", "mcp", "voice", "voice-train", "evals", "bedrock", "redis", "html", "dev", "all", "sandbox"]
+provides-extras = ["proxy", "proxy-prod", "code", "ml", "memory", "vector", "memory-stack", "pytorch-mps", "relevance", "image", "reports", "spreadsheet", "otel", "anyllm", "langchain", "langgraph", "agno", "strands", "autogen", "mcp", "voice", "voice-train", "evals", "bedrock", "redis", "html", "dev", "all", "lean", "sandbox"]
[[package]]
name = "hf-xet"