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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(offline): make HEADROOM_OFFLINE a real air-gap via one chokepoint (#3729)
Tejas Chopra119d1a193936
diff --git a/crates/headroom-core/src/lib.rs b/crates/headroom-core/src/lib.rsindex 76d4b4daf..f209b4131 100644--- a/crates/headroom-core/src/lib.rs+++ b/crates/headroom-core/src/lib.rs@@ -8,6 +8,7 @@ pub mod auth_mode;pub mod cache_control;pub mod ccr;pub mod compression_policy;+pub mod offline;#[cfg(feature = "ml")]mod onnx_cpu;pub mod relevance;@@ -29,6 +30,24 @@ pub fn hello() -> &'static str {"headroom-core"}+#[cfg(test)]+pub(crate) mod test_support {+ use std::sync::{Mutex, MutexGuard};++ /// The process environment is global while `cargo test` runs tests in+ /// parallel threads inside one process, so a test that sets an env var can+ /// be observed by an unrelated sibling mid-assertion. Every test that+ /// mutates the environment holds this for its whole body. Same shape as+ /// `REGISTRY_LOCK` in `tokenizer::registry`.+ static ENV_LOCK: Mutex<()> = Mutex::new(());++ /// Recovers from poisoning on purpose: one panicking test should not+ /// cascade into every later test that touches the environment.+ pub(crate) fn env_lock() -> MutexGuard<'static, ()> {+ ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/headroom-core/src/offline.rs b/crates/headroom-core/src/offline.rsnew file mode 100644index 000000000..53412c9d7--- /dev/null+++ b/crates/headroom-core/src/offline.rs@@ -0,0 +1,181 @@+//! Air-gap / no-egress master switch (`HEADROOM_OFFLINE`) — Rust half.+//!+//! The Python side lives in `headroom/offline.py`. This is the same switch+//! read by the same environment variable with the same truthiness rules, so a+//! deployment that sets `HEADROOM_OFFLINE=1` gets identical behaviour whether+//! the egress attempt originates in the Python proxy or in a Rust core path.+//!+//! Two functions, mirroring the Python module deliberately:+//!+//! - [`is_offline`] — the predicate, for code that wants to take a different+//! route (use a cached artifact, skip an optional refresh).+//! - [`guard_egress`] — the chokepoint, for code that is about to open a+//! socket. It returns [`OfflineEgressBlocked`], a distinct error type, so a+//! caller that otherwise degrades gracefully on network failure can still+//! tell "the operator air-gapped this box" from "the network was flaky" and+//! refuse loudly instead of silently falling back.+//!+//! # Parity contract+//!+//! `HEADROOM_OFFLINE` is true for `1`, `true`, `yes`, `on` — trimmed and+//! ASCII-case-insensitive — and false for anything else, including unset and+//! empty. Any change here must be mirrored in `headroom/offline.py`'s+//! `_TRUE_VALUES`, and vice versa: the two implementations are a pair, and a+//! deployment that reads as offline to Python but online to Rust is precisely+//! the failure this module exists to prevent.+//!+//! The parity covers **normalisation**, not just the accepted values. This+//! used to call `str::trim()` while Python called `str.strip()`, and those are+//! not the same set: Python's strips U+001C-U+001F (the ASCII file/group/+//! record/unit separators) because `str.isspace()` includes them, Rust's does+//! not because the Unicode `White_Space` property does not. `HEADROOM_OFFLINE`+//! set to `"\x1c1"` read as offline to Python and online to Rust — one+//! environment variable, one process air-gapped and the other not. Both sides+//! now trim exactly [`TRIM_CHARS`].++use std::env;++use thiserror::Error;++/// The environment variable that selects fully-offline operation.+pub const OFFLINE_ENV: &str = "HEADROOM_OFFLINE";++/// Values that read as "yes, offline". Kept byte-identical to the Python+/// side's `_TRUE_VALUES` (see the parity contract in the module docs).+const TRUE_VALUES: [&str; 4] = ["1", "true", "yes", "on"];++/// Whitespace trimmed off the raw value before matching. Enumerated rather+/// than left to `str::trim()`, which is the Unicode `White_Space` property and+/// does not agree with Python's `str.strip()`. Kept byte-identical to the+/// Python side's `_TRIM_CHARS` (see the parity contract in the module docs).+const TRIM_CHARS: [char; 6] = [' ', '\t', '\n', '\r', '\u{b}', '\u{c}'];++/// An egress attempt was refused because `HEADROOM_OFFLINE` is in force.+///+/// Carries the human-readable `purpose` and `destination` handed to+/// [`guard_egress`] so the operator learns which feature to turn off rather+/// than just that "something" was blocked.+#[derive(Debug, Clone, Error)]+#[error(+ "{OFFLINE_ENV} is set: refusing outbound network access for {purpose} to \+ {destination}. Unset {OFFLINE_ENV}, or turn off the feature that needs \+ this connection."+)]+pub struct OfflineEgressBlocked {+ pub purpose: String,+ pub destination: String,+}++/// Return `true` when `HEADROOM_OFFLINE` selects fully-offline operation.+pub fn is_offline() -> bool {+ match env::var(OFFLINE_ENV) {+ Ok(raw) => {+ let normalized = raw.trim_matches(TRIM_CHARS.as_slice()).to_ascii_lowercase();+ TRUE_VALUES.contains(&normalized.as_str())+ }+ // Unset, or not valid UTF-8 — neither is an opt-in to offline mode.+ Err(_) => false,+ }+}++/// The chokepoint every Rust egress path must call before opening a socket.+///+/// `Ok(())` when online; `Err(OfflineEgressBlocked)` when `HEADROOM_OFFLINE`+/// is set. Call it *before* constructing the HTTP client, not merely before+/// the request — several clients (`ureq`, `reqwest`) resolve DNS or warm a+/// connection pool during setup, so a guard placed at the request would leak+/// the very packets the air-gap switch promises not to send.+pub fn guard_egress(purpose: &str, destination: &str) -> Result<(), OfflineEgressBlocked> {+ if is_offline() {+ return Err(OfflineEgressBlocked {+ purpose: purpose.to_string(),+ destination: destination.to_string(),+ });+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::test_support::env_lock;++ #[test]+ fn unset_is_online() {+ let _guard = env_lock();+ env::remove_var(OFFLINE_ENV);+ assert!(!is_offline());+ assert!(guard_egress("anything", "https://example.invalid").is_ok());+ }++ #[test]+ fn truthy_values_match_python() {+ let _guard = env_lock();+ // Same set, same trimming, same case-insensitivity as+ // headroom/offline.py::_TRUE_VALUES. If this list drifts, the two+ // halves of the switch disagree and the air-gap has a hole.+ for raw in ["1", "true", "TRUE", "Yes", " on ", "\ton\n"] {+ env::set_var(OFFLINE_ENV, raw);+ assert!(is_offline(), "{raw:?} should read as offline");+ }+ env::remove_var(OFFLINE_ENV);+ }++ #[test]+ fn falsy_values_stay_online() {+ let _guard = env_lock();+ for raw in ["", "0", "off", "no", "false", "maybe", " "] {+ env::set_var(OFFLINE_ENV, raw);+ assert!(!is_offline(), "{raw:?} should read as online");+ }+ env::remove_var(OFFLINE_ENV);+ }++ /// Normalisation parity, not just value parity. Every case here is+ /// duplicated verbatim in `tests/test_offline_egress_chokepoint.py`'s+ /// `test_normalisation_matches_the_rust_side`, and the two must agree.+ ///+ /// The `\x1c` cases are the regression: they are whitespace to Python's+ /// `str.strip()` and not to Rust's `str::trim()`, so before `TRIM_CHARS`+ /// existed `"\x1c1"` air-gapped the Python proxy and left the Rust core+ /// dialling out.+ #[test]+ fn normalisation_matches_python() {+ let _guard = env_lock();+ for (raw, expected) in [+ ("1", true),+ (" 1 ", true),+ ("\t1\n", true),+ ("\r\n TRUE \r\n", true),+ ("\u{b}yes\u{c}", true),+ ("\u{1c}1", false),+ ("1\u{1f}", false),+ ("\u{a0}1", false),+ ("\u{2007}on", false),+ ("", false),+ (" ", false),+ ] {+ env::set_var(OFFLINE_ENV, raw);+ assert_eq!(is_offline(), expected, "{raw:?}");+ }+ env::remove_var(OFFLINE_ENV);+ }++ #[test]+ fn guard_reports_purpose_and_destination() {+ let _guard = env_lock();+ env::set_var(OFFLINE_ENV, "1");+ let err = guard_egress("HuggingFace tokenizer download", "hf.co/acme/model")+ .expect_err("guard must refuse while offline");+ assert_eq!(err.purpose, "HuggingFace tokenizer download");+ assert_eq!(err.destination, "hf.co/acme/model");+ let rendered = err.to_string();+ assert!(rendered.contains(OFFLINE_ENV), "{rendered}");+ assert!(+ rendered.contains("HuggingFace tokenizer download"),+ "{rendered}"+ );+ assert!(rendered.contains("hf.co/acme/model"), "{rendered}");+ env::remove_var(OFFLINE_ENV);+ }+}diff --git a/crates/headroom-core/src/relevance/embedding.rs b/crates/headroom-core/src/relevance/embedding.rsindex 02facf02b..96f3fb447 100644--- a/crates/headroom-core/src/relevance/embedding.rs+++ b/crates/headroom-core/src/relevance/embedding.rs@@ -98,6 +98,22 @@ impl EmbeddingScorer {/// quality/speed tradeoff for compression-relevance scoring on/// short snippets.pub fn try_new_with_model(model_kind: EmbeddingModel) -> Result<Self, String> {+ let name = format!("{:?}", model_kind);+ // Air-gap chokepoint, FIRST thing in the function. `TextEmbedding::+ // try_new` resolves the model's ONNX weights through `hf-hub`, which+ // downloads from huggingface.co on a cache miss even with+ // `HF_HUB_OFFLINE` set — the same hole the tokenizer and Kompress model+ // fetches had. It sits ahead of the AVX2 and ort-loader probes below so+ // that an air-gapped box reports the policy refusal rather than+ // whichever local prerequisite happened to be missing as well.+ //+ // The refusal is soft here by design: this function already returns+ // `Err(String)` for "ONNX runtime unavailable" and every caller degrades+ // to the BM25 scorer, so an air-gapped box loses embedding relevance+ // instead of failing a request. The message names the switch so the+ // operator can tell the two causes apart in the log.+ crate::offline::guard_egress("fastembed embedding model download", &name)+ .map_err(|e| format!("EmbeddingScorer model load refused: {e}"))?;// fastembed links the precompiled ONNX Runtime binary, which contains// AVX2 instructions on x86. Loading/running it on a non-AVX2 CPU traps// with SIGILL (issue #1723) — an uncatchable native fault. Bail early so@@ -113,7 +129,6 @@ impl EmbeddingScorer {// `dynamic_ort_loader_ready`).crate::transforms::magika_detector::dynamic_ort_loader_ready().map_err(|e| format!("EmbeddingScorer: ONNX Runtime unavailable: {e}"))?;- let name = format!("{:?}", model_kind);let model = TextEmbedding::try_new(InitOptions::new(model_kind)).map_err(|e| format!("EmbeddingScorer model load failed: {}", e))?;Ok(EmbeddingScorer {@@ -308,6 +323,28 @@ mod tests {std::env::var("RUN_FASTEMBED_TESTS").is_ok()}+ /// `try_new_with_model` must refuse before fastembed resolves the model,+ /// and must say so in the returned message rather than looking like an+ /// ordinary load failure — the caller only ever sees the `String`.+ ///+ /// Not gated on `RUN_FASTEMBED_TESTS`: the whole point is that no network+ /// call happens, so this is safe to run in CI. If the guard were removed+ /// this test would either download ~30 MB or fail with a load error, and+ /// neither says "refused".+ #[cfg(feature = "ml")]+ #[test]+ fn try_new_refuses_while_offline() {+ let _guard = crate::test_support::env_lock();+ std::env::set_var(crate::offline::OFFLINE_ENV, "1");+ let result = EmbeddingScorer::try_new();+ std::env::remove_var(crate::offline::OFFLINE_ENV);++ let err = result.err().expect("guard must refuse while offline");+ assert!(err.contains("refused"), "{err}");+ assert!(err.contains(crate::offline::OFFLINE_ENV), "{err}");+ assert!(err.contains("fastembed embedding model download"), "{err}");+ }+/// Construct a stub scorer with `model = None` for offline-safe/// tests of the unavailable-path behavior.#[cfg(feature = "ml")]diff --git a/crates/headroom-core/src/tokenizer/hf_impl.rs b/crates/headroom-core/src/tokenizer/hf_impl.rsindex a63d9f94d..f120c76ac 100644--- a/crates/headroom-core/src/tokenizer/hf_impl.rs+++ b/crates/headroom-core/src/tokenizer/hf_impl.rs@@ -49,6 +49,13 @@ pub enum HfTokenizerError {#[source]source: Box<dyn std::error::Error + Send + Sync>,},+ /// `HEADROOM_OFFLINE` is set, so the Hub fetch was refused before any+ /// socket was opened. Deliberately a separate variant from [`Self::Hub`]:+ /// a caller that retries or falls back on a transient download failure+ /// must not do either here — the operator asked for no egress, and+ /// retrying an air-gap refusal is just a slower refusal.+ #[error(transparent)]+ Offline(#[from] crate::offline::OfflineEgressBlocked),}/// Token counter backed by a HuggingFace `tokenizer.json`.@@ -110,11 +117,35 @@ impl HfTokenizer {/// processes hit the on-disk cache.////// Errors:+ /// - [`HfTokenizerError::Offline`] when `HEADROOM_OFFLINE` is set. Refused+ /// before any socket is opened; see below./// - [`HfTokenizerError::Hub`] for download failures (no network, 404,/// 401 on a gated model without `HF_TOKEN`)./// - [`HfTokenizerError::Load`] if the downloaded bytes don't parse as/// a valid `tokenizer.json`. Should not happen for healthy HF repos.pub fn from_pretrained(repo: &str) -> Result<Self, HfTokenizerError> {+ // Air-gap chokepoint, matching `headroom/offline.py`'s `guard_egress`.+ // This is the Rust half of the same switch, so an operator who sets+ // HEADROOM_OFFLINE=1 gets the same refusal whichever runtime reaches+ // for the Hub.+ //+ // It has to sit here rather than around the `get` below: `Api::new`+ // builds the `ureq` agent and resolves the endpoint, and hf-hub's own+ // HF_HUB_OFFLINE handling only covers the cache lookup — a cache miss+ // still dials out. Guarding first means the air-gapped case never+ // constructs a client at all.+ //+ // The refusal is hard on purpose. Silently returning a cached or+ // estimating tokenizer would leave token counts subtly wrong with no+ // signal; the caller (`tokenizer::registry::try_register_hf`) already+ // propagates the error so the operator sees which repo was wanted.+ //+ // Note it refuses even on a warm cache: `hf-hub` 0.5 exposes no+ // cache-hit/cache-miss split at this layer, so "guard before the+ // client exists" and "serve from the cache" cannot both hold here. An+ // air-gapped deployment with pre-seeded artifacts should point at them+ // with `from_file`, which is network-free by construction.+ crate::offline::guard_egress("HuggingFace tokenizer download", repo)?;let api = hf_hub::api::sync::Api::new().map_err(|e| HfTokenizerError::Hub {repo: repo.to_string(),source: Box::new(e),@@ -260,6 +291,41 @@ mod tests {assert!(Arc::ptr_eq(&a.inner, &b.inner));}+ /// A-2: `HEADROOM_OFFLINE=1` must stop the Hub fetch before a socket exists.+ ///+ /// The repo name is deliberately one that cannot exist, which is what makes+ /// this a real assertion rather than a tautology: without the guard the call+ /// reaches `hf-hub`, dials `huggingface.co`, gets a 401/404 and returns+ /// `HfTokenizerError::Hub`. Only the guard can produce `Offline`, and only+ /// by returning before `Api::new` — so `Offline` *is* the "no socket was+ /// opened" assertion for this path. (A packet-level assertion is not+ /// available to a `cargo test` unit test the way `socket.socket` patching is+ /// in Python; this typed-error distinction is the equivalent signal.)+ #[test]+ fn from_pretrained_refuses_while_offline() {+ let _guard = crate::test_support::env_lock();+ std::env::set_var(crate::offline::OFFLINE_ENV, "1");+ let result = HfTokenizer::from_pretrained("headroomlabs-ai/this-repo-does-not-exist-a2");+ std::env::remove_var(crate::offline::OFFLINE_ENV);++ match result {+ Err(HfTokenizerError::Offline(blocked)) => {+ assert_eq!(blocked.purpose, "HuggingFace tokenizer download");+ assert_eq!(+ blocked.destination,+ "headroomlabs-ai/this-repo-does-not-exist-a2"+ );+ }+ Err(other) => panic!("expected an offline refusal, got a network error: {other}"),+ Ok(_) => panic!("expected an offline refusal, got a tokenizer"),+ }+ }++ // The "switch off ⇒ guard is a no-op" half is covered in `crate::offline`'s+ // own tests rather than here: asserting it through `from_pretrained` would+ // mean actually dialling huggingface.co, which is exactly the thing a unit+ // test must not do.+#[test]fn from_file_loads_a_real_file() {// Round-trip via a temp file to cover the on-disk constructor.diff --git a/crates/headroom-core/src/transforms/kompress.rs b/crates/headroom-core/src/transforms/kompress.rsindex 455c179dd..06c51b075 100644--- a/crates/headroom-core/src/transforms/kompress.rs+++ b/crates/headroom-core/src/transforms/kompress.rs@@ -180,6 +180,12 @@ pub enum KompressError {#[source]source: Box<dyn std::error::Error + Send + Sync>,},+ /// `HEADROOM_OFFLINE` is set, so the Hub fetch was refused before any+ /// socket was opened. A separate variant from [`Self::Hub`] for the same+ /// reason as [`crate::tokenizer::HfTokenizerError::Offline`]: retrying or+ /// falling back on a policy refusal is just a slower refusal.+ #[error(transparent)]+ Offline(#[from] crate::offline::OfflineEgressBlocked),}// ─── Compressor ─────────────────────────────────────────────────────────@@ -255,6 +261,22 @@ impl Kompress {/// downloading on miss). Blocking — call off the hot path. Tries the/// [`ONNX_CANDIDATES`] in order.pub fn from_pretrained(config: KompressConfig) -> Result<Self, KompressError> {+ // Air-gap chokepoint — the same one `hf_impl.rs` uses for the+ // tokenizer, for the same reason. `HF_HUB_OFFLINE` only shortcuts the+ // cache *lookup*; on a cache miss `hf-hub` still dials huggingface.co,+ // so the Kompress model download is a live egress path under+ // `HEADROOM_OFFLINE=1` and was not covered.+ //+ // It sits before `Api::new()` because that already resolves the Hub+ // endpoint and builds the `ureq` agent, so guarding at the `get` call+ // would leak the setup packets the switch promises not to send.+ //+ // Trade-off, stated plainly: this refuses even when the artifacts are+ // already in `~/.cache/huggingface/hub`, because `hf-hub` 0.5 gives no+ // cache-hit/cache-miss split at this layer. An air-gapped caller that+ // has pre-seeded artifacts should use [`Self::from_files`], which is+ // network-free by construction and unaffected by this guard.+ crate::offline::guard_egress("Kompress model download", &config.model_id)?;let api = hf_hub::api::sync::Api::new().map_err(|e| KompressError::Hub {repo: config.model_id.clone(),source: Box::new(e),@@ -635,6 +657,38 @@ fn hf_hub_roots() -> Vec<PathBuf> {mod tests {use super::*;+ /// `from_pretrained` must refuse before `Api::new()` when the operator+ /// air-gapped the box.+ ///+ /// The model id cannot exist, which is what makes this a real assertion+ /// rather than a tautology: without the guard the call reaches `hf-hub`,+ /// dials `huggingface.co` and comes back `KompressError::Hub`. Only the+ /// guard can produce `Offline`, and only by returning before the client is+ /// built — so `Offline` *is* the "no socket was opened" assertion here.+ #[test]+ fn from_pretrained_refuses_while_offline() {+ let _guard = crate::test_support::env_lock();+ std::env::set_var(crate::offline::OFFLINE_ENV, "1");+ let config = KompressConfig {+ model_id: "headroomlabs-ai/this-model-does-not-exist-a2".to_string(),+ ..KompressConfig::default()+ };+ let result = Kompress::from_pretrained(config);+ std::env::remove_var(crate::offline::OFFLINE_ENV);++ match result {+ Err(KompressError::Offline(blocked)) => {+ assert_eq!(blocked.purpose, "Kompress model download");+ assert_eq!(+ blocked.destination,+ "headroomlabs-ai/this-model-does-not-exist-a2"+ );+ }+ Err(other) => panic!("expected an offline refusal, got a network error: {other}"),+ Ok(_) => panic!("expected an offline refusal, got a loaded model"),+ }+ }+#[test]fn config_defaults_match_kompress_v2_base() {let c = KompressConfig::default();diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdxindex f9812a82e..43de97cfd 100644--- a/docs/content/docs/proxy.mdx+++ b/docs/content/docs/proxy.mdx@@ -341,7 +341,7 @@ with a privileged job.| `HEADROOM_PROXY_TOKEN` | none | Require a token from non-loopback callers, as `X-Headroom-Proxy-Token: <token>` or `Authorization: Bearer <token>`. The token is removed from the request before it is forwarded upstream; clients that also send a provider credential should use `X-Headroom-Proxy-Token` and keep `Authorization` for the provider. Also gates the read-only operator routes (`/stats-history`, `/quota`, `/subscription-window`, `/metrics`), which otherwise answer loopback and trusted-CIDR callers only. || `HEADROOM_ALLOW_UNAUTHENTICATED_BIND` | `false` | Acknowledge a non-loopback bind (`--host 0.0.0.0`, `::`, a LAN address) with **no** `HEADROOM_PROXY_TOKEN`. Without a token or this flag the proxy refuses to start, because `/v1/*` would relay upstream with the operator's credentials for every peer that can reach the port. Only set it when the runtime already restricts reachability (a container published on `127.0.0.1`). || `HEADROOM_COMPRESS_ALLOW_REMOTE` | `false` | Allow non-loopback callers to reach [`POST /v1/compress`](#post-v1compress) and `POST /v1/usage`. Required to run Headroom as a remote gateway/sidecar; without it remote callers get `404`. |-| `--offline` / `HEADROOM_OFFLINE` | `false` | Air-gap mode: hard-disable **all** egress (telemetry, update checks, license reporting, model downloads). |+| `--offline` / `HEADROOM_OFFLINE` | `false` | Air-gap mode: refuse every connection Headroom itself initiates — telemetry, update checks, license reporting, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP and Langfuse export, Copilot auth, the subscription pollers, the OpenAI embedders, Headroom Cloud compression and the TLS diagnostics (`headroom doctor --network` reports them as skipped). Four things still work on purpose: forwarding your own requests to the upstream you configured, operator-configured local endpoints (the Ollama embedder), loopback health probes, and paths an `is_offline()` check already disables. Refusals surface as messages, not tracebacks. See the air-gap notes in `docs/metrics-technical-guide.md`. || `HEADROOM_LICENSE` | unset | Licence token, read by core and every licensed extension. `HEADROOM_LICENSE_KEY` is a deprecated alias for one release and logs a warning. A licence on its own sends nothing to Headroom. || `HEADROOM_USAGE_REPORTING` | `false` | Set `1` to let the proxy validate the licence and post aggregate usage counts (no content) to the Headroom cloud. Off unless set; `HEADROOM_OFFLINE` still overrides it. || `--stateless` / `HEADROOM_STATELESS` | `false` | Keep all state in memory; no filesystem writes (disables logs, memory, TOIN). |diff --git a/docs/metrics-technical-guide.md b/docs/metrics-technical-guide.mdindex d1dc3db6c..eefb53c69 100644--- a/docs/metrics-technical-guide.md+++ b/docs/metrics-technical-guide.md@@ -268,6 +268,17 @@ Verify with `curl -s localhost:8787/stats | jq .otel`.**Multi-tenant labels:** `register_otel_metric_attribute_provider()` adds request-scoped attributes (tenant, team, cost centre) to every OTel datapoint. Max 16 attributes, 256 chars each.-**Air-gapped deployments:** `HEADROOM_OFFLINE=1` disables all outbound traffic — the anonymous usage beacon (which is **on by default**), the update check, and model downloads.+**Air-gapped deployments:** `HEADROOM_OFFLINE=1` refuses every connection Headroom itself decides to make to a destination Headroom itself chose. That is the whole list, not a sample: the anonymous usage beacon (which is **on by default**), the update check, the license/usage reporter, **OTLP metric and Langfuse trace export**, HuggingFace / Kompress / fastembed model and tokenizer downloads (Python and Rust), the remote Kompress endpoint, the `headroom install` release-binary and codebase-memory-mcp downloads, the BFCL eval-dataset fetch and the provider SDK clients the eval harness drives, GitHub Copilot device-flow auth and token exchange, the Anthropic / Codex / Copilot subscription pollers, the OpenAI embedders, the Headroom Cloud compression modes in the ASGI and LiteLLM integrations, and the TLS diagnostics (`headroom doctor --network` endpoint checks and the certificate-chain re-probe after an upstream TLS failure).++Four things are deliberately still allowed, and they are the complete set of exceptions:++1. **Your traffic through the proxy.** Requests you send *through* Headroom are still forwarded to the upstream you configured. That is your traffic, not Headroom's, and an air-gapped deployment points it at an on-prem endpoint — refusing it would mean refusing to be a proxy.+2. **Operator-configured local endpoints.** Today that is exactly one thing: the Ollama embedder, whose address comes entirely from your configuration and defaults to `http://localhost:11434`. No hard-coded internet host is permitted under this exception.+3. **Loopback.** Health and readiness probes against your own proxy on `127.0.0.1` (`headroom doctor`, the installers, the MCP sidecar).+4. **Paths an `is_offline()` check already makes unreachable**, where no connection is ever built in the first place.++Those four are enumerated with written reasons in `_EGRESS_ALLOWLIST` in `tests/test_offline_egress_chokepoint.py`, which fails the build if a new egress path appears that is neither guarded nor one of them. There is no category for "known violation": a path that can dial the internet with the flag set is a bug. A refusal reaches you as a message — a Click error on the CLI, a named "model unavailable" from a model loader, a logged line from a background poller — never as a traceback and never as a silent degradation. Enforcing the same policy at the network layer as well is still good practice; it is no longer the only thing standing between you and Headroom-initiated egress.++OTLP export is refused loudly: with `HEADROOM_OFFLINE=1` set, `HEADROOM_OTEL_METRICS_ENABLED=1` plus the default `otlp_http` exporter makes the proxy exit 78 at startup with an explanation, rather than quietly dropping metrics. There is no exemption for a collector that looks local — an in-cluster address is not reliably distinguishable from an internet one. For metrics under an air-gap, either scrape `localhost:8787/metrics` or set `HEADROOM_OTEL_METRICS_EXPORTER=console`, both of which stay on-box. `HEADROOM_KOMPRESS_ENDPOINT` and `HEADROOM_LANGFUSE_ENABLED` are refused the same way, for the same reason.---diff --git a/headroom/binaries.py b/headroom/binaries.pyindex 4916e8f22..a9eb22d6d 100644--- a/headroom/binaries.py+++ b/headroom/binaries.py@@ -51,6 +51,7 @@ from pathlib import Pathfrom typing import Anyfrom headroom._subprocess import run+from headroom.offline import guard_egresslogger = logging.getLogger(__name__)@@ -266,6 +267,11 @@ def _mirror_url(url: str) -> str:def _download(url: str, dest: Path, *, progress: bool = True) -> None:if os.environ.get("HEADROOM_BINARIES_OFFLINE"):raise OfflineError(f"offline mode (HEADROOM_BINARIES_OFFLINE=1) but fetch required: {url}")+ # HEADROOM_BINARIES_OFFLINE above is the narrow, binaries-only switch; this+ # is the deployment-wide one. An operator who set the air-gap switch should+ # not have to also discover a second, differently-named flag to stop+ # Headroom fetching release assets from GitHub at install time.+ guard_egress("release binary download", url)if not _has_writable_existing_parent(dest.parent):raise OSError(f"binary cache directory parent is not writable: {dest.parent}")dest.parent.mkdir(parents=True, exist_ok=True)diff --git a/headroom/cli/doctor.py b/headroom/cli/doctor.pyindex b1cfae50a..aa98ec6da 100644--- a/headroom/cli/doctor.py+++ b/headroom/cli/doctor.py@@ -843,6 +843,28 @@ def run_network_probes(extra_urls: Sequence[str]) -> tuple[list[Any], set[str]]:return reports, required+def network_checks(extra_urls: Sequence[str]) -> list[CheckResult]:+ """The ``--network`` rows, or one skipped row when ``HEADROOM_OFFLINE`` is set.++ Every probe here dials an internet host, so under the air-gap switch none+ of them runs; saying so beats a page of "unreachable" failures.+ """+ from headroom.offline import OFFLINE_ENV, OfflineEgressBlocked++ try:+ reports, required = run_network_probes(extra_urls)+ except OfflineEgressBlocked as blocked:+ return [+ CheckResult(+ name="network",+ status=SKIP,+ summary=f"skipped: {OFFLINE_ENV} is set, no endpoint was contacted",+ hint=str(blocked),+ )+ ]+ return check_network_endpoints(reports, required)++def check_shell_env(environ: Mapping[str, str], port: int) -> CheckResult:"""Is the *current shell* pointed at the proxy for ad-hoc runs?"""name = "shell env"@@ -1233,8 +1255,7 @@ def doctor(if proxy_env_check is not None:checks.append(proxy_env_check)if network or network_urls:- reports, required = run_network_probes(network_urls)- checks.extend(check_network_endpoints(reports, required))+ checks.extend(network_checks(network_urls))auth_conflict_check = check_claude_auth_conflict(claude_settings_path(),project_claude_settings,diff --git a/headroom/cli/main.py b/headroom/cli/main.pyindex bd2fd7fce..23ebd77cb 100644--- a/headroom/cli/main.py+++ b/headroom/cli/main.py@@ -2,9 +2,39 @@import click+from headroom.offline import OfflineEgressBlocked+CLI_CONTEXT_SETTINGS = {"help_option_names": ["--help", "-?"]}+class OfflineAwareGroup(click.Group):+ """The CLI's single translation point for an air-gap refusal.++ ``OfflineEgressBlocked`` is a ``BaseException`` on purpose, so no+ ``except Exception`` anywhere in the tree can downgrade a policy refusal+ into "that feature is having a bad day". The cost of that choice is that+ nothing catches it either — Click's own error handling only knows about+ ``ClickException``/``Abort``, so an operator who ran ``headroom auth+ copilot`` on an air-gapped box would have got a stack trace ending in a+ type they have never heard of.++ Translating here, once, at the outermost boundary of every subcommand,+ turns it into the ordinary ``Error: ...`` line Click prints for any other+ bad invocation — with the switch, the feature and the host already in the+ message, because :class:`OfflineEgressBlocked` builds them in. The guard+ keeps its unswallowable property everywhere inside; only the last frame+ before the user's terminal is allowed to make it readable.+ """++ def invoke(self, ctx: click.Context) -> object:+ try:+ return super().invoke(ctx)+ except OfflineEgressBlocked as blocked:+ # ``from None``: the traceback is Headroom's own plumbing and+ # tells the operator nothing they can act on. The message does.+ raise click.ClickException(str(blocked)) from None++def get_version() -> str:"""Get the current version."""try:@@ -15,7 +45,7 @@ def get_version() -> str:return "unknown"[email protected](context_settings=CLI_CONTEXT_SETTINGS)[email protected](cls=OfflineAwareGroup, context_settings=CLI_CONTEXT_SETTINGS)@click.version_option(get_version(), "--version", "-v", prog_name="headroom")@click.pass_contextdef main(ctx: click.Context) -> None:diff --git a/headroom/copilot_auth.py b/headroom/copilot_auth.pyindex d8bcaf6d3..d88bf27e4 100644--- a/headroom/copilot_auth.py+++ b/headroom/copilot_auth.py@@ -26,6 +26,7 @@ from headroom import pathsfrom headroom._subprocess import runfrom headroom.copilot_linux_secret import read_copilot_oauth_token as read_linux_secret_tokenfrom headroom.copilot_macos_keychain import read_copilot_oauth_token as read_macos_keychain_token+from headroom.offline import guard_egressfrom headroom.proxy import ssl_context as proxy_ssl_contextlogger = logging.getLogger(__name__)@@ -79,8 +80,20 @@ _EXPIRY_KEYS = ("expires_at", "expiresAt", "expiry", "expires")def _urlopen(request: urllib_request.Request, *, timeout: float) -> Any:- """Open a GitHub request with Headroom's configured corporate trust roots."""+ """Open a GitHub request with Headroom's configured corporate trust roots.++ Every GitHub call in this module bottoms out here, so this is also the+ backstop for the air-gap switch. The four call sites guard individually+ too — they can name the specific step ("device-flow authorisation",+ "token exchange") in the refusal, which this frame cannot — but a fifth+ call site added later inherits the refusal from here whether its author+ thought about ``HEADROOM_OFFLINE`` or not.+ """+ guard_egress(+ "GitHub Copilot authentication",+ urlparse(request.full_url).hostname or request.full_url,+ )context = proxy_ssl_context.build_urlopen_context()if context is not None:return urllib_request.urlopen(request, timeout=timeout, context=context)@@ -699,6 +712,7 @@ def start_copilot_device_authorization("""Start the GitHub Copilot OAuth device-code flow."""urls = _github_oauth_urls(domain)+ guard_egress("GitHub Copilot device-flow authorisation", domain)body = urlencode({"client_id": COPILOT_CHAT_OAUTH_CLIENT_ID, "scope": "read:user"}).encode("utf-8")@@ -730,6 +744,7 @@ def poll_copilot_device_authorization("""Poll GitHub until the device-code OAuth flow returns an access token."""urls = _github_oauth_urls(domain)+ guard_egress("GitHub Copilot device-flow authorisation", domain)deadline = time.time() + max(1, expires_in)poll_interval = max(1, interval)while time.time() < deadline:@@ -1423,6 +1438,7 @@ def _fetch_copilot_user_info(token: str) -> dict[str, Any] | None:if not token:return None+ guard_egress("GitHub Copilot account lookup", urlparse(_user_info_url()).hostname)headers = _copilot_token_exchange_headers(token)request = urllib_request.Request(_user_info_url(), headers=headers, method="GET")try:@@ -1540,6 +1556,10 @@ class CopilotTokenProvider:@staticmethoddef _exchange_token_sync(headers: dict[str, str]) -> dict[str, Any]:+ guard_egress(+ "GitHub Copilot API token exchange",+ urlparse(_token_exchange_url()).hostname,+ )request = urllib_request.Request(_token_exchange_url(), headers=headers, method="GET")try:with _urlopen(request, timeout=10.0) as response:diff --git a/headroom/evals/batch_compression_eval.py b/headroom/evals/batch_compression_eval.pyindex 31d02fe17..bb9d6ab7f 100644--- a/headroom/evals/batch_compression_eval.py+++ b/headroom/evals/batch_compression_eval.py@@ -46,6 +46,7 @@ from headroom.evals.metrics import (compute_rouge_l,compute_semantic_similarity,)+from headroom.offline import guard_egressfrom headroom.transforms.content_router import ContentRouter, ContentRouterConfiglogger = logging.getLogger(__name__)@@ -1029,6 +1030,7 @@ class BatchCompressionEvaluator:def _init_llm_client(self) -> Any:"""Initialize LLM client."""+ guard_egress(f"{self.provider} API for the batch compression benchmark")if self.provider == "anthropic":try:import anthropicdiff --git a/headroom/evals/datasets.py b/headroom/evals/datasets.pyindex 5c94a8cfa..9c1673efc 100644--- a/headroom/evals/datasets.py+++ b/headroom/evals/datasets.py@@ -28,10 +28,14 @@ Custom:from __future__ import annotationsimport json+import loggingfrom pathlib import Pathfrom typing import Anyfrom headroom.evals.core import EvalCase, EvalSuite+from headroom.offline import guard_egress, is_offline++logger = logging.getLogger(__name__)def _check_datasets_installed() -> None:@@ -45,6 +49,36 @@ def _check_datasets_installed() -> None:) from e+def load_hf_dataset(path: str, *args: Any, **kwargs: Any) -> Any:+ """``datasets.load_dataset``, cache first under ``HEADROOM_OFFLINE``.++ ``load_dataset`` takes no ``local_files_only``, and with an explicit+ ``HF_HUB_OFFLINE=0`` it fetches from the Hub even when ``HEADROOM_OFFLINE``+ is set. So, as ``relevance/embedding._load_text_embedding`` does for+ fastembed: under the switch, try the load with the datasets and+ huggingface_hub offline constants forced on (a pre-seeded cache still+ loads), and only on a miss reach :func:`guard_egress`, which refuses+ before any remote attempt. Online, nothing changes.+ """+ from datasets import load_dataset++ if is_offline():+ import datasets.config as datasets_config+ from huggingface_hub import constants as hf_constants++ previous = (datasets_config.HF_HUB_OFFLINE, hf_constants.HF_HUB_OFFLINE)+ datasets_config.HF_HUB_OFFLINE = True+ hf_constants.HF_HUB_OFFLINE = True+ try:+ return load_dataset(path, *args, **kwargs)+ except Exception as cache_miss: # noqa: BLE001 - any local-lookup failure+ logger.debug("eval dataset %s not in the local cache: %s", path, cache_miss)+ finally:+ datasets_config.HF_HUB_OFFLINE, hf_constants.HF_HUB_OFFLINE = previous+ guard_egress(f"HuggingFace eval-dataset download ({path})", "huggingface.co")+ return load_dataset(path, *args, **kwargs)++# =============================================================================# RAG / RETRIEVAL DATASETS# =============================================================================@@ -69,9 +103,8 @@ def load_hotpotqa(EvalSuite with HotpotQA cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("hotpotqa/hotpot_qa", "fullwiki", split=split)+ ds = load_hf_dataset("hotpotqa/hotpot_qa", "fullwiki", split=split)cases: list[EvalCase] = []for i, item in enumerate(ds):@@ -121,9 +154,8 @@ def load_natural_questions(EvalSuite with Natural Questions cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("google-research-datasets/natural_questions", "default", split=split)+ ds = load_hf_dataset("google-research-datasets/natural_questions", "default", split=split)cases: list[EvalCase] = []for i, item in enumerate(ds):@@ -198,9 +230,8 @@ def load_triviaqa(EvalSuite with TriviaQA cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("trivia_qa", subset, split=split)+ ds = load_hf_dataset("trivia_qa", subset, split=split)cases: list[EvalCase] = []for i, item in enumerate(ds):@@ -269,9 +300,8 @@ def load_msmarco(EvalSuite with MS MARCO cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("microsoft/ms_marco", "v2.1", split=split)+ ds = load_hf_dataset("microsoft/ms_marco", "v2.1", split=split)cases: list[EvalCase] = []for i, item in enumerate(ds):@@ -337,9 +367,8 @@ def load_squad(EvalSuite with SQuAD cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("rajpurkar/squad_v2", split=split)+ ds = load_hf_dataset("rajpurkar/squad_v2", split=split)cases: list[EvalCase] = []for i, item in enumerate(ds):@@ -398,10 +427,9 @@ def load_longbench(EvalSuite with LongBench cases"""_check_datasets_installed()- from datasets import load_datasettry:- ds = load_dataset("THUDM/LongBench", task, split="test")+ ds = load_hf_dataset("THUDM/LongBench", task, split="test")except Exception as e:raise ValueError(f"Failed to load LongBench task '{task}': {e}") from e@@ -460,10 +488,9 @@ def load_multi_wiki_qa(EvalSuite with multi-wiki-qa cases"""_check_datasets_installed()- from datasets import load_datasettry:- ds = load_dataset("alexandrainst/multi-wiki-qa", lang, split=f"train[:{n}]")+ ds = load_hf_dataset("alexandrainst/multi-wiki-qa", lang, split=f"train[:{n}]")except Exception as e:raise ValueError(f"Failed to load multi-wiki-qa '{lang}': {e}") from e@@ -513,9 +540,8 @@ def load_narrativeqa(EvalSuite with NarrativeQA cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("deepmind/narrativeqa", split=split)+ ds = load_hf_dataset("deepmind/narrativeqa", split=split)cases: list[EvalCase] = []for i, item in enumerate(ds):@@ -590,6 +616,7 @@ def load_bfcl(import urllib.requestbase_url = "https://huggingface.co/datasets/gorilla-llm/Berkeley-Function-Calling-Leaderboard/resolve/main"+ guard_egress("BFCL eval-dataset download", base_url)data_file = f"BFCL_v3_{category}.json"gt_file = f"possible_answer/BFCL_v3_{category}.json"@@ -676,10 +703,9 @@ def load_toolbench(EvalSuite with ToolBench cases"""_check_datasets_installed()- from datasets import load_datasettry:- ds = load_dataset("ToolBench/ToolBench", category, split="test")+ ds = load_hf_dataset("ToolBench/ToolBench", category, split="test")except Exception as e:raise ValueError(f"Failed to load ToolBench category '{category}': {e}") from e@@ -759,10 +785,9 @@ def load_codesearchnet(EvalSuite with CodeSearchNet cases"""_check_datasets_installed()- from datasets import load_datasettry:- ds = load_dataset("code_search_net", language, split=split)+ ds = load_hf_dataset("code_search_net", language, split=split)except Exception as e:raise ValueError(f"Failed to load CodeSearchNet for '{language}': {e}") from e@@ -815,9 +840,8 @@ def load_humaneval(EvalSuite with HumanEval cases"""_check_datasets_installed()- from datasets import load_dataset- ds = load_dataset("openai_humaneval", split="test")+ ds = load_hf_dataset("openai_humaneval", split="test")cases: list[EvalCase] = []for i, item in enumerate(ds):diff --git a/headroom/evals/html_extraction.py b/headroom/evals/html_extraction.pyindex 6ccd2667e..4303ae9ab 100644--- a/headroom/evals/html_extraction.py+++ b/headroom/evals/html_extraction.py@@ -15,6 +15,8 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any+from headroom.offline import guard_egress+if TYPE_CHECKING:from headroom.transforms.html_extractor import HTMLExtractor@@ -255,6 +257,7 @@ class HTMLExtractionEvaluator:def _create_judge(self) -> Callable[[str, str, str], tuple[float, str]]:"""Create the LLM judge function."""+ guard_egress(f"{self.provider} API for the HTML-extraction eval judge")if self.provider == "openai":try:from openai import OpenAI@@ -355,6 +358,7 @@ class HTMLExtractionEvaluator:def _get_answer(self, content: str, question: str) -> str:"""Get LLM answer for a question given content."""+ guard_egress(f"{self.provider} API for the HTML-extraction eval answers")prompt = f"""Based on the following content, answer the question.Content:diff --git a/headroom/evals/html_oss_benchmarks.py b/headroom/evals/html_oss_benchmarks.pyindex 41164bec7..176224dea 100644--- a/headroom/evals/html_oss_benchmarks.py+++ b/headroom/evals/html_oss_benchmarks.py@@ -142,12 +142,15 @@ def evaluate_scrapinghub_benchmark(print(f"F1: {result.avg_f1:.3f} (baseline: {result.baseline_f1})")"""try:- from datasets import load_dataset+ import datasets # noqa: F401except ImportError:raise ImportError("HuggingFace datasets required. Install with: pip install datasets") from None+ # Cache first under HEADROOM_OFFLINE, guard_egress before any download.+ from headroom.evals.datasets import load_hf_dataset+if extractor is None:from headroom.transforms.html_extractor import HTMLExtractor@@ -155,7 +158,7 @@ def evaluate_scrapinghub_benchmark(# Load the benchmark datasetlogger.info("Loading Scrapinghub article extraction benchmark...")- dataset = load_dataset("allenai/scrapinghub-article-extraction-benchmark")+ dataset = load_hf_dataset("allenai/scrapinghub-article-extraction-benchmark")samples = dataset["train"]if max_samples:@@ -274,10 +277,13 @@ def evaluate_qa_accuracy_preservation(QAAccuracyResult showing whether accuracy is preserved"""try:- from datasets import load_dataset+ import datasets # noqa: F401except ImportError:raise ImportError("HuggingFace datasets required") from None+ # Cache first under HEADROOM_OFFLINE, guard_egress before any download.+ from headroom.evals.datasets import load_hf_dataset+if extractor is None:from headroom.transforms.html_extractor import HTMLExtractor@@ -287,9 +293,9 @@ def evaluate_qa_accuracy_preservation(logger.info(f"Loading {dataset_name} dataset...")if dataset_name == "squad":- dataset = load_dataset("rajpurkar/squad_v2", split="validation")+ dataset = load_hf_dataset("rajpurkar/squad_v2", split="validation")elif dataset_name == "hotpotqa":- dataset = load_dataset("hotpotqa/hotpot_qa", "fullwiki", split="validation")+ dataset = load_hf_dataset("hotpotqa/hotpot_qa", "fullwiki", split="validation")else:raise ValueError(f"Unknown dataset: {dataset_name}")diff --git a/headroom/evals/memory/judge.py b/headroom/evals/memory/judge.pyindex 4e711d352..9713b7176 100644--- a/headroom/evals/memory/judge.py+++ b/headroom/evals/memory/judge.py@@ -17,6 +17,8 @@ from __future__ import annotationsimport loggingfrom collections.abc import Callable+from headroom.offline import guard_egress+logger = logging.getLogger(__name__)# Prompt template for LLM judge@@ -73,6 +75,7 @@ def create_openai_judge("OpenAI package required for LLM judge. Install with: pip install openai") from e+ guard_egress("OpenAI API for the memory eval LLM judge", "api.openai.com")client = OpenAI(api_key=api_key) if api_key else OpenAI()def judge(question: str, ground_truth: str, prediction: str) -> tuple[float, str]:@@ -124,6 +127,7 @@ def create_anthropic_judge("Anthropic package required for LLM judge. Install with: pip install anthropic") from e+ guard_egress("Anthropic API for the memory eval LLM judge", "api.anthropic.com")client = anthropic.Anthropic(api_key=api_key) if api_key else anthropic.Anthropic()def judge(question: str, ground_truth: str, prediction: str) -> tuple[float, str]:diff --git a/headroom/evals/prompt_comparison.py b/headroom/evals/prompt_comparison.pyindex 31393e972..ea84af246 100644--- a/headroom/evals/prompt_comparison.py+++ b/headroom/evals/prompt_comparison.py@@ -32,6 +32,8 @@ from datetime import datetimefrom pathlib import Pathfrom typing import Any+from headroom.offline import guard_egress+logger = logging.getLogger(__name__)@@ -259,6 +261,7 @@ def compare_prompts("or pass api_key parameter.")+ guard_egress("OpenAI API for the prompt-comparison judge", "api.openai.com")client = OpenAI(api_key=resolved_api_key)# Build the judge promptdiff --git a/headroom/evals/runners/before_after.py b/headroom/evals/runners/before_after.pyindex 8bd6a2b3b..254f14e3a 100644--- a/headroom/evals/runners/before_after.py+++ b/headroom/evals/runners/before_after.py@@ -25,6 +25,7 @@ from headroom.evals.core import (EvalSuiteResult,)from headroom.evals.metrics import compute_semantic_similarity+from headroom.offline import guard_egressfrom headroom.transforms.content_router import ContentRouter, ContentRouterConfigfrom headroom.transforms.smart_crusher import SmartCrusherConfig@@ -95,8 +96,13 @@ class BeforeAfterRunner:self._judge_fn: Any = Nonedef _init_llm_client(self) -> Any:- """Initialize the appropriate LLM client."""+ """Initialize the appropriate LLM client.++ Ollama is not guarded: like the Ollama embedder it is an+ operator-configured endpoint that defaults to localhost.+ """if self.llm_config.provider == "anthropic":+ guard_egress("anthropic API for the before/after eval runner")try:import anthropic@@ -106,6 +112,7 @@ class BeforeAfterRunner:"anthropic package required. Install with: pip install anthropic") from eelif self.llm_config.provider == "openai":+ guard_egress("openai API for the before/after eval runner")try:import openai@@ -128,6 +135,10 @@ class BeforeAfterRunner:def _init_proxy_client(self) -> Any:"""Initialize an OpenAI client pointing at the Headroom proxy."""+ guard_egress(+ "LLM calls through the Headroom proxy for the before/after eval runner",+ self.llm_config.headroom_proxy_url,+ )import openaireturn openai.OpenAI(diff --git a/headroom/graph/installer.py b/headroom/graph/installer.pyindex a94a31544..92c625462 100644--- a/headroom/graph/installer.py+++ b/headroom/graph/installer.py@@ -12,6 +12,8 @@ import zipfilefrom pathlib import Pathfrom urllib.request import urlopen+from headroom.offline import guard_egress+logger = logging.getLogger(__name__)CBM_VERSION = "v0.8.1"@@ -98,6 +100,7 @@ def download_cbm(version: str | None = None) -> Path:plat = _detect_platform()filename = _asset_filename(plat)url = f"{GITHUB_RELEASE_URL}/{version}/{filename}"+ guard_egress("codebase-memory-mcp binary download", url)CBM_BIN_DIR.mkdir(parents=True, exist_ok=True)target_path = CBM_BIN_DIR / _installed_name(plat)diff --git a/headroom/image/onnx_router.py b/headroom/image/onnx_router.pyindex a6bc582b1..fdf41f5fa 100644--- a/headroom/image/onnx_router.py+++ b/headroom/image/onnx_router.py@@ -22,6 +22,7 @@ from typing import Anyimport numpy as npfrom headroom.image.image_types import ImageMemo, ImageSignals, RouteDecision, Technique+from headroom.offline import OFFLINE_ENV, OfflineEgressBlockedfrom headroom.onnx_runtime import create_cpu_session_options, hf_hub_download_local_firstlogger = logging.getLogger(__name__)@@ -67,6 +68,25 @@ def _classifier_intra_op_threads() -> int:# ImageSignals, RouteDecision, Technique imported from trained_router+def _hf_artifact(repo: str, filename: str) -> str:+ """``hf_hub_download_local_first``, translating the air-gap refusal.++ ``OfflineEgressBlocked`` is a ``BaseException`` so that it cannot be+ swallowed by accident. Here it is handled on purpose: ``ImageCompressor``+ already degrades a router that will not load to ``Technique.PRESERVE``, and+ an air-gapped box with no cached router should get that same degradation+ rather than a failed request. Re-raised as a plain ``RuntimeError``, with+ the switch named in the message, so the existing handler sees it and the+ log says why.+ """+ try:+ return hf_hub_download_local_first(repo, filename)+ except OfflineEgressBlocked as blocked:+ raise RuntimeError(+ f"{filename} for {repo} is not cached and {OFFLINE_ENV} forbids fetching it: {blocked}"+ ) from blocked++class OnnxTechniqueRouter:"""ONNX-based technique router — no PyTorch dependency.@@ -98,8 +118,15 @@ class OnnxTechniqueRouter:logger.info("Loading technique-router ONNX INT8...")- model_path = hf_hub_download_local_first(_TECHNIQUE_ROUTER_REPO, "model_quantized.onnx")- self._classifier_session = ort.InferenceSession(+ # Resolve every artifact before publishing anything: the session is the+ # "loaded" flag, so setting it before a later artifact fails (e.g. not+ # cached under HEADROOM_OFFLINE) would leave a half-loaded router that+ # never retries.+ model_path = _hf_artifact(_TECHNIQUE_ROUTER_REPO, "model_quantized.onnx")+ tokenizer_path = _hf_artifact(_TECHNIQUE_ROUTER_REPO, "tokenizer.json")+ config_path = _hf_artifact(_TECHNIQUE_ROUTER_REPO, "config.json")++ session = ort.InferenceSession(model_path,create_cpu_session_options(ort,@@ -109,18 +136,18 @@ class OnnxTechniqueRouter:providers=["CPUExecutionProvider"],)- tokenizer_path = hf_hub_download_local_first(_TECHNIQUE_ROUTER_REPO, "tokenizer.json")- self._tokenizer = Tokenizer.from_file(tokenizer_path)- self._tokenizer.enable_truncation(max_length=64)- self._tokenizer.enable_padding(length=64)+ tokenizer = Tokenizer.from_file(tokenizer_path)+ tokenizer.enable_truncation(max_length=64)+ tokenizer.enable_padding(length=64)# Load label mappingimport json- config_path = hf_hub_download_local_first(_TECHNIQUE_ROUTER_REPO, "config.json")with open(config_path) as f:config = json.load(f)self._id2label = {int(k): v for k, v in config.get("id2label", {}).items()}+ self._tokenizer = tokenizer+ self._classifier_session = sessionlogger.info(f"Technique router loaded: {len(self._id2label)} classes, "@@ -136,16 +163,18 @@ class OnnxTechniqueRouter:logger.info("Loading SigLIP ONNX INT8 image encoder...")- model_path = hf_hub_download_local_first(_SIGLIP_ENCODER_REPO, "image_encoder_int8.onnx")- self._siglip_session = ort.InferenceSession(+ # Both artifacts first, session last — see _load_classifier.+ model_path = _hf_artifact(_SIGLIP_ENCODER_REPO, "image_encoder_int8.onnx")+ embeddings_path = _hf_artifact(_SIGLIP_ENCODER_REPO, "text_embeddings.npz")++ session = ort.InferenceSession(model_path,create_cpu_session_options(ort),providers=["CPUExecutionProvider"],)-- embeddings_path = hf_hub_download_local_first(_SIGLIP_ENCODER_REPO, "text_embeddings.npz")loaded = np.load(embeddings_path)self._text_embeddings = {k: loaded[k] for k in loaded.files}+ self._siglip_session = sessionlogger.info(f"SigLIP image encoder loaded: ONNX INT8 "diff --git a/headroom/integrations/asgi.py b/headroom/integrations/asgi.pyindex feb3220e1..d1ae4babc 100644--- a/headroom/integrations/asgi.py+++ b/headroom/integrations/asgi.py@@ -34,6 +34,8 @@ from typing import Anyfrom starlette.types import ASGIApp, Receive, Scope, Send+from headroom.offline import guard_egress+logger = logging.getLogger(__name__)_DEFAULT_CLOUD_URL = "https://api.headroomlabs.ai"@@ -204,7 +206,18 @@ class CompressionMiddleware:}async def _cloud_compress(self, messages: list[dict], model: str) -> dict[str, Any] | None:- """Compress via Headroom Cloud API (managed CCR, TOIN, analytics)."""+ """Compress via Headroom Cloud API (managed CCR, TOIN, analytics).++ This is the one path in this file that puts the caller's prompt+ content on the wire to a Headroom-operated host, so it is exactly what+ HEADROOM_OFFLINE exists to stop. "Opt-in by configuration" was the old+ reason for leaving it open, and it is not good enough: an operator who+ sets an air-gap switch is overriding earlier configuration on purpose.+ The refusal is loud rather than a silent fall-through to local+ compression, because silently compressing locally would hide the fact+ that the deployment is no longer doing what it was configured to do.+ """+ guard_egress("Headroom Cloud compression", self._api_url)if self._client is None:try:import httpxdiff --git a/headroom/integrations/litellm_callback.py b/headroom/integrations/litellm_callback.pyindex 434d60a19..d9d20048d 100644--- a/headroom/integrations/litellm_callback.py+++ b/headroom/integrations/litellm_callback.py@@ -20,6 +20,8 @@ import jsonimport loggingfrom typing import Any+from headroom.offline import guard_egress+logger = logging.getLogger(__name__)_DEFAULT_CLOUD_URL = "https://api.headroomlabs.ai"@@ -184,7 +186,18 @@ class HeadroomCallback(_CustomLogger):}async def _cloud_compress(self, messages: list[dict], model: str) -> dict[str, Any] | None:- """Compress via Headroom Cloud API (managed CCR, TOIN, analytics)."""+ """Compress via Headroom Cloud API (managed CCR, TOIN, analytics).++ This is the one path in this file that puts the caller's prompt+ content on the wire to a Headroom-operated host, so it is exactly what+ HEADROOM_OFFLINE exists to stop. "Opt-in by configuration" was the old+ reason for leaving it open, and it is not good enough: an operator who+ sets an air-gap switch is overriding earlier configuration on purpose.+ The refusal is loud rather than a silent fall-through to local+ compression, because silently compressing locally would hide the fact+ that the deployment is no longer doing what it was configured to do.+ """+ guard_egress("Headroom Cloud compression", self._api_url)if self._client is None:try:import httpxdiff --git a/headroom/memory/adapters/embedders.py b/headroom/memory/adapters/embedders.pyindex 1120b4fed..2d6f2b21d 100644--- a/headroom/memory/adapters/embedders.py+++ b/headroom/memory/adapters/embedders.py@@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Any, castimport numpy as npfrom headroom.models.config import ML_MODEL_DEFAULTS+from headroom.offline import OFFLINE_ENV, OfflineEgressBlocked, guard_egressfrom headroom.onnx_runtime import create_cpu_session_options, hf_hub_download_local_firstif TYPE_CHECKING:@@ -450,8 +451,20 @@ class OnnxLocalEmbedder:logger.info("Loading ONNX embedding model (all-MiniLM-L6-v2, ~86MB)...")# Prefer local cache to avoid a redundant network HEAD on warm starts.- model_path = hf_hub_download_local_first(self.ONNX_REPO, "model.onnx")- tok_path = hf_hub_download_local_first(self.ONNX_REPO, "tokenizer.json")+ # OfflineEgressBlocked is a BaseException so it cannot be swallowed by+ # accident; here the degradation is deliberate and written down. A model+ # download is not data leaving the box, and an air-gapped deployment+ # without a cached embedder should get "the local embedder is+ # unavailable" — the caller's existing failure mode — rather than a+ # BaseException escaping into the memory pipeline.+ try:+ model_path = hf_hub_download_local_first(self.ONNX_REPO, "model.onnx")+ tok_path = hf_hub_download_local_first(self.ONNX_REPO, "tokenizer.json")+ except OfflineEgressBlocked as blocked:+ raise RuntimeError(+ f"local ONNX embedder {self.ONNX_REPO} is not cached and "+ f"{OFFLINE_ENV} forbids fetching it: {blocked}"+ ) from blocked# Keep a small thread pool for Docker compatibility and disable ORT's# CPU memory arena/pattern caches so long-running proxy workers do not@@ -655,6 +668,7 @@ class OpenAIEmbedder:@cached_propertydef _async_client(self) -> Any:"""Lazy initialization of async OpenAI client."""+ guard_egress("OpenAI embedding API", "api.openai.com")from openai import AsyncOpenAIreturn AsyncOpenAI(api_key=self._api_key)diff --git a/headroom/memory/backends/direct_mem0.py b/headroom/memory/backends/direct_mem0.pyindex 03d7394dc..8f7c1f530 100644--- a/headroom/memory/backends/direct_mem0.py+++ b/headroom/memory/backends/direct_mem0.py@@ -60,6 +60,7 @@ from typing import Anyfrom headroom.memory import qdrant_envfrom headroom.memory.models import Memoryfrom headroom.memory.ports import MemorySearchResult+from headroom.offline import guard_egresslogger = logging.getLogger(__name__)@@ -169,7 +170,12 @@ class DirectMem0Adapter:if self._initialized:return- # Initialize embedder (OpenAI)+ # Initialize embedder (OpenAI). The air-gap switch outranks the+ # backend configuration: this embeds the user's memories by shipping+ # them to api.openai.com, which is precisely what an operator who set+ # HEADROOM_OFFLINE is refusing. Use the ONNX or Ollama embedder+ # instead on an air-gapped box.+ guard_egress("OpenAI embedding API (direct mem0 backend)", "api.openai.com")try:from openai import OpenAIdiff --git a/headroom/models/ml_models.py b/headroom/models/ml_models.pyindex 9f48cf2ed..73765fcbc 100644--- a/headroom/models/ml_models.py+++ b/headroom/models/ml_models.py@@ -32,6 +32,7 @@ import loggingfrom threading import RLockfrom typing import TYPE_CHECKING, Any+from ..offline import OFFLINE_ENV, OfflineEgressBlockedfrom .config import ML_MODEL_DEFAULTSif TYPE_CHECKING:@@ -40,6 +41,42 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+class ModelUnavailableOffline(RuntimeError):+ """A model is not in the local cache and ``HEADROOM_OFFLINE`` forbids fetching it.++ The legible form of an air-gap refusal at a model-loader boundary. Fetching+ public weights is not data leaving the box, so the loader degrades instead+ of failing the request: every caller of this registry already treats a+ load failure as "feature unavailable" (the image router preserves the+ image, the memory embedder falls back, ...). The original+ :class:`~headroom.offline.OfflineEgressBlocked` is chained.+ """++ def __init__(self, purpose: str, name_or_path: str) -> None:+ self.purpose = purpose+ self.name_or_path = name_or_path+ super().__init__(+ f"{purpose} {name_or_path!r} is not in the local HuggingFace cache and "+ f"{OFFLINE_ENV} forbids downloading it. Pre-seed the cache to use this feature."+ )+++def _load_local_first(loader: Any, name_or_path: str, *, purpose: str, **kwargs: Any) -> Any:+ """Cache-first load with the air-gap refusal translated and logged.++ Thin wrapper over :func:`headroom.onnx_runtime.hf_from_pretrained_local_first`+ (the one place the cache-first + ``guard_egress`` order lives).+ """+ from ..onnx_runtime import hf_from_pretrained_local_first++ try:+ return hf_from_pretrained_local_first(loader, name_or_path, purpose=purpose, **kwargs)+ except OfflineEgressBlocked as blocked:+ unavailable = ModelUnavailableOffline(purpose, name_or_path)+ logger.warning("%s (%s)", unavailable, blocked)+ raise unavailable from blocked++class MLModelRegistry:"""Singleton registry for shared ML model instances.@@ -168,7 +205,12 @@ class MLModelRegistry:if device is None:device = cls._detect_device()- model = SentenceTransformer(model_name, device=device)+ model = _load_local_first(+ SentenceTransformer,+ model_name,+ purpose="SentenceTransformer model",+ device=device,+ )instance._models[key] = modellogger.info(f"Loaded SentenceTransformer: {model_name} on {device}")@@ -207,8 +249,12 @@ class MLModelRegistry:if device is None:device = cls._detect_device()- model = AutoModel.from_pretrained(model_name)- processor = AutoProcessor.from_pretrained(model_name)+ model = _load_local_first(+ AutoModel.from_pretrained, model_name, purpose="SigLIP model"+ )+ processor = _load_local_first(+ AutoProcessor.from_pretrained, model_name, purpose="SigLIP processor"+ )# Move to device and set eval modeif device != "cpu":@@ -295,8 +341,16 @@ class MLModelRegistry:if device is None:device = cls._detect_device()- tokenizer = AutoTokenizer.from_pretrained(model_path)- model = AutoModelForSequenceClassification.from_pretrained(model_path)+ tokenizer = _load_local_first(+ AutoTokenizer.from_pretrained,+ model_path,+ purpose="technique-router tokenizer",+ )+ model = _load_local_first(+ AutoModelForSequenceClassification.from_pretrained,+ model_path,+ purpose="technique-router model",+ )# Move to device and set eval modeif device != "cpu":diff --git a/headroom/observability/metrics.py b/headroom/observability/metrics.pyindex 430c690a3..3f3592652 100644--- a/headroom/observability/metrics.py+++ b/headroom/observability/metrics.py@@ -13,6 +13,7 @@ from opentelemetry import metricsfrom opentelemetry.metrics import CallbackOptions, Observationfrom headroom._version import get_version+from headroom.offline import guard_egresslogger = logging.getLogger(__name__)@@ -717,6 +718,22 @@ def configure_otel_metrics(config: OTelMetricsConfig | None = None) -> HeadroomOif resolved.exporter == "console":exporter = ConsoleMetricExporter()else:+ # Air-gap chokepoint. OTLP/HTTP export dials a collector and then keeps+ # POSTing on a background timer (PeriodicExportingMetricReader), so it+ # is exactly the kind of long-lived, easy-to-forget egress+ # HEADROOM_OFFLINE is supposed to cover — and it was not covered.+ #+ # The guard runs before OTLPMetricExporter is constructed, because the+ # exporter opens its session eagerly. No exemption for a collector that+ # looks local: the endpoint may be unset here (the OTEL SDK then falls+ # back to OTEL_EXPORTER_OTLP_ENDPOINT or the 4318 default) and a+ # sidecar address is not distinguishable from an internet one. An+ # operator who wants in-cluster metrics under an air-gap should use the+ # "console" exporter or scrape /metrics, both of which stay on-box.+ guard_egress(+ "OTLP metric export",+ resolved.endpoint or "the OTEL SDK's default OTLP endpoint",+ )exporter_kwargs: dict[str, Any] = {}if resolved.endpoint is not None:exporter_kwargs["endpoint"] = resolved.endpointdiff --git a/headroom/observability/tracing.py b/headroom/observability/tracing.pyindex 6637b8a3f..128e46a5d 100644--- a/headroom/observability/tracing.py+++ b/headroom/observability/tracing.py@@ -11,6 +11,8 @@ from typing import Anyfrom opentelemetry import trace+from headroom.offline import guard_egress+from .metrics import _headroom_version, _parse_bool, _parse_key_value_pairslogger = logging.getLogger(__name__)@@ -158,6 +160,17 @@ def configure_langfuse_tracing()return get_headroom_tracer()+ # Air-gap chokepoint, the exact counterpart of the one in metrics.py.+ # Langfuse OTLP tracing ships every span off the box on a background+ # BatchSpanProcessor timer — and unlike the metrics exporter, the endpoint+ # here is Langfuse Cloud unless the operator overrode it. It was missed+ # when the metric exporter was guarded; the two are the same egress shape+ # and now refuse the same way. Guarded before OTLPSpanExporter is+ # constructed, because the exporter opens its session eagerly.+ guard_egress(+ "Langfuse OTLP trace export",+ resolved.endpoint or "the OTEL SDK's default OTLP endpoint",+ )resource = Resource.create({SERVICE_NAME: resolved.service_name,diff --git a/headroom/offline.py b/headroom/offline.pyindex 7468f6a0c..a6ed91d2a 100644--- a/headroom/offline.py+++ b/headroom/offline.py@@ -1,10 +1,59 @@"""Air-gap / no-egress master switch (``HEADROOM_OFFLINE``).-A single predicate the individual egress paths consult so a regulated or-air-gapped deployment can disable **all** outbound network access with one-flag: the telemetry beacon, the update check, the license/usage reporter, and-HuggingFace model downloads. Each of those already had its own opt-out; this-is the one switch that turns them all off together and fails closed.+THE POLICY, in one sentence: with ``HEADROOM_OFFLINE`` set, Headroom refuses+every connection **Headroom itself decides to make to a destination Headroom+itself chose**, and keeps working for the two kinds of traffic an air-gapped+deployment exists to carry.++Refused (this is not a sample — it is the rule, and the meta-test enforces it):+the telemetry beacon, the update check, the license/usage reporter, OTLP and+Langfuse export, HuggingFace/Kompress/fastembed model downloads, release-binary+and codebase-memory-mcp downloads, eval dataset downloads and the provider SDK+clients the eval harness drives, GitHub Copilot device-flow auth and token+exchange, the Anthropic / Codex / Copilot subscription pollers, the OpenAI+embedders, both Headroom Cloud compression integrations, and the TLS+diagnostics (``doctor --network`` endpoint checks and the certificate-chain+re-probe after an upstream TLS failure).++Permitted, explicitly and by name — an air-gapped deployment needs these and+none of them is Headroom phoning home:++``user-traffic``+ The proxy forwarding the caller's own request to the upstream the operator+ configured. Forwarding a request the user's client made, to the endpoint+ the user pointed Headroom at, is the proxy's entire job. An air-gapped+ install points it at an on-prem model endpoint.+``operator-endpoint``+ Headroom dialling an address that comes **entirely** from operator+ configuration and whose default is loopback — today that is exactly one+ thing, the Ollama embedder (``http://localhost:11434``). No hard-coded+ internet host may hide behind this category.+``loopback``+ Hard-coded ``127.0.0.1`` traffic to the operator's own local proxy: the+ readiness and health probes, ``headroom doctor``, the MCP sidecar.+``gated``+ A path that an ``is_offline()`` check upstream already makes unreachable,+ so the connection is never even built.++Those four are the complete list of exceptions. There is no "known violation"+category: a path that dials out under ``HEADROOM_OFFLINE`` for any other+reason is a bug, not an entry in a table.++:func:`guard_egress` is the chokepoint: a path that is about to open an+outbound connection calls it and gets a loud :class:`OfflineEgressBlocked`+instead of a socket. Prefer it over a bare ``if is_offline(): return`` at any+call site that actually dials out — the meta-test in+``tests/test_offline_egress_chokepoint.py`` enumerates the outbound clients in+``headroom/`` and ``crates/`` and requires each **site** to have a guard that+dominates it or to be counted in an allowlist under one of the four categories+above, so the guard is what keeps a newly-added egress path from silently+escaping the air-gap.++A refusal must reach a human as a sentence, never as a traceback and never as+a silent degradation. Interactive paths get that from the CLI boundary in+``headroom/cli/main.py``, which turns the refusal into a Click error; model+loaders translate it into their own "model unavailable"; background pollers+call :func:`note_refusal` and stop.Kept at the top level (depends only on the stdlib) so any layer — telemetry,proxy, model code — can import it without creating a package cycle.@@ -12,16 +61,32 @@ proxy, model code — can import it without creating a package cycle.from __future__ import annotations+import loggingimport os_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})+# Whitespace trimmed off the raw value before matching. Enumerated rather than+# left to ``str.strip()``'s default, because that default is Python's+# ``str.isspace()`` — which includes U+001C-U+001F (the ASCII file/group/record+# /unit separators) — while Rust's ``str::trim()`` is the Unicode White_Space+# property, which does not. ``HEADROOM_OFFLINE=$'\x1c1'`` therefore read as+# offline to Python and online to Rust: one process air-gapped, the other not,+# from one environment variable. Neither side's default is more right than the+# other, so both now trim exactly this set. Mirrored by ``TRIM_CHARS`` in+# ``crates/headroom-core/src/offline.rs``; the parity test compares them.+#+# Case folding needs no such treatment: Python's ``str.lower()`` and Rust's+# ``to_ascii_lowercase()`` differ only on non-ASCII input, and no non-ASCII+# character lowercases into any character of "1"/"true"/"yes"/"on".+_TRIM_CHARS = " \t\n\r\x0b\x0c"+OFFLINE_ENV = "HEADROOM_OFFLINE"def is_offline() -> bool:"""Return True when ``HEADROOM_OFFLINE`` selects fully-offline operation."""- return os.environ.get(OFFLINE_ENV, "").strip().lower() in _TRUE_VALUES+ return os.environ.get(OFFLINE_ENV, "").strip(_TRIM_CHARS).lower() in _TRUE_VALUESdef apply_offline_env() -> None:@@ -34,3 +99,121 @@ def apply_offline_env() -> None:if is_offline():os.environ.setdefault("HF_HUB_OFFLINE", "1")os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")+++class OfflineEgressBlocked(BaseException):+ """Raised by :func:`guard_egress` when ``HEADROOM_OFFLINE`` is in force.++ A distinct, named type so callers can tell "the operator air-gapped this+ box" apart from "the network was flaky". That distinction matters because+ several Headroom egress paths deliberately fail OPEN on network errors+ (remote Kompress passes content through verbatim, the license reporter+ falls back to a cached grant). Fail-open is right for a flaky endpoint and+ WRONG for a policy refusal: swallowing this turns the air-gap switch back+ into a suggestion.++ **It derives from BaseException, not Exception, on purpose.** The first+ version of this class was a ``RuntimeError`` whose docstring asked every+ broad handler to re-raise it. Nothing did — there were zero re-raise sites+ in the package — and the refusal was swallowed by four reachable+ ``except Exception`` blocks on the way out of a single ``/v1/messages``+ request, which returned 200 with the content uncompressed while the guard+ had fired twice. A convention that has to be re-applied at every future+ ``except Exception`` in a 100k-line codebase is not a guarantee; the type+ hierarchy is. This is the same reason ``KeyboardInterrupt`` and+ ``SystemExit`` sit outside ``Exception``: a policy decision is control+ flow, not a runtime error to degrade around.++ Consequences to know about:++ * ``except Exception`` no longer catches it anywhere — including in+ third-party code (httpx, the OTEL SDK, Starlette's error middleware).+ * ``except BaseException`` still does. Those are rare, they are enumerated+ by ``tests/test_offline_egress_chokepoint.py``'s broad-handler sweep, and+ each must either re-raise or carry a written reason.+ * Reaching this at request time means the operator changed the environment+ under a running proxy; the ordinary contradictory-configuration case is+ caught at startup by ``headroom/proxy/server.py``'s offline preflight,+ which exits 78 with an explanation instead.+ * Where a refusal SHOULD become a degradation, the boundary that owns the+ degradation says so explicitly. Fetching public model weights is not data+ leaving the box, so each optional model loader catches this and re-raises+ its own "model unavailable" error with the switch named — see+ ``kompress_compressor._hf_artifact``, ``image/onnx_router._hf_artifact``+ and the ONNX embedder in ``memory/adapters/embedders.py``. Translating is+ fine; inheriting a translation from whichever ``except Exception`` happens+ to be in the stack is what this type prevents.+ """++ def __init__(self, purpose: str, destination: str | None = None) -> None:+ self.purpose = purpose+ self.destination = destination+ where = f" to {destination}" if destination else ""+ super().__init__(+ f"{OFFLINE_ENV} is set: refusing outbound network access for "+ f"{purpose}{where}. Unset {OFFLINE_ENV}, or turn off the feature "+ f"that needs this connection."+ )+++def guard_egress(purpose: str, destination: str | None = None) -> None:+ """The single chokepoint every Headroom-initiated egress path must call.++ Raise :class:`OfflineEgressBlocked` when ``HEADROOM_OFFLINE`` selects+ offline operation; return silently otherwise.++ Call it BEFORE the socket exists — before constructing the client, not+ just before the request — so a pooled/keep-alive connection is never even+ opened. ``purpose`` and ``destination`` land verbatim in the message, so+ an operator who trips this learns which feature to turn off.++ Why raise instead of returning a no-op result: a silent skip is+ indistinguishable from success at the call site, so a future refactor can+ quietly reintroduce egress and nothing fails. A loud, named exception is+ what makes the meta-test in ``tests/test_offline_egress_chokepoint.py``+ able to assert "every egress path is behind this or allowlisted".++ Deliberately NOT exempted:++ * Loopback / in-cluster destinations. The guard cannot reliably tell an+ in-cluster collector from an internet host (DNS, proxies and sidecars+ all blur it), and ``HEADROOM_OFFLINE`` is documented as "no outbound+ traffic". Paths that only ever talk to ``127.0.0.1`` — the readiness+ probes, the proxy's own ``/livez`` check — simply do not call the guard+ and are allowlisted by name in the meta-test instead.+ * The proxy's own request forwarding to the caller's configured upstream.+ That is the caller's traffic, not Headroom phoning home; an air-gapped+ deployment points it at an on-prem endpoint and still needs it to work.+ """+ if is_offline():+ raise OfflineEgressBlocked(purpose, destination)+++# Purposes already reported, so a poller that runs every 30s says it once at+# WARNING and then keeps quiet. Module-level rather than per-object because+# several of these pollers are recreated per poll.+_REPORTED_REFUSALS: set[str] = set()+++def note_refusal(blocked: OfflineEgressBlocked, log: logging.Logger) -> str:+ """Report an air-gap refusal on a background path and return its message.++ Background pollers and other fire-and-forget tasks cannot let a+ ``BaseException`` escape — an unhandled task exception is a traceback in+ the log, not an explanation, and asyncio may not surface it until the+ task is garbage collected. They also must not swallow the refusal+ silently, because "the subscription window stopped updating" with no+ stated cause is the exact confusion this switch was supposed to end.++ So: catch :class:`OfflineEgressBlocked` specifically, call this, and stop.+ The first refusal for a given purpose is logged at WARNING with the switch+ named; later ones drop to DEBUG so a 30-second poller does not flood the+ log with a decision the operator already made.+ """+ message = str(blocked)+ if blocked.purpose in _REPORTED_REFUSALS:+ log.debug("%s", message)+ else:+ _REPORTED_REFUSALS.add(blocked.purpose)+ log.warning("%s", message)+ return messagediff --git a/headroom/onnx_runtime.py b/headroom/onnx_runtime.pyindex 445d85b4f..16d1781b7 100644--- a/headroom/onnx_runtime.py+++ b/headroom/onnx_runtime.py@@ -8,6 +8,8 @@ import osimport sysfrom typing import Any+from headroom.offline import guard_egress+logger = logging.getLogger(__name__)# Override for the CPU memory-arena default below: "1"/"true" forces the@@ -121,6 +123,10 @@ def hf_hub_download_local_first(Absolute path to the local cached file.Raises:+ OfflineEgressBlocked: when ``HEADROOM_OFFLINE`` is set and the file is+ not already cached. A cache HIT still succeeds — the guard sits on+ the network fallback only, so a pre-seeded air-gapped deployment+ keeps working, which is the whole point of pre-seeding.Any exception raised by ``hf_hub_download`` on a genuine download failure,or the local-lookup error when ``allow_network`` is ``False`` and thefile is not cached.@@ -135,6 +141,17 @@ def hf_hub_download_local_first(except (LocalEntryNotFoundError, EntryNotFoundError, OSError):if not allow_network:raise+ # Air-gap chokepoint: this is the Python half of the HuggingFace fetch+ # the Rust core already guards. ``apply_offline_env`` sets+ # ``HF_HUB_OFFLINE=1``, but only with ``setdefault`` (an explicit+ # ``HF_HUB_OFFLINE=0`` wins) and only inside the proxy process — the CLI+ # and library entry points never call it, so the flag alone is not the+ # guarantee. Guarding here is, and it costs nothing on the cache-hit+ # path above.+ guard_egress(+ f"HuggingFace download of {repo_id}/{filename}",+ "huggingface.co",+ )return str(hf_hub_download(repo_id, filename, revision=revision))@@ -157,6 +174,76 @@ def hf_entry_known_absent(repo_id: str, filename: str, *, revision: str | None =return result is _CACHED_NO_EXIST+def _hf_not_cached_errors() -> tuple[type[BaseException], ...]:+ """Errors a ``local_files_only=True`` load raises on a plain cache miss.++ Transformers and sentence-transformers both surface a miss as ``OSError``;+ huggingface_hub's own lookup errors are listed explicitly in case a loader+ lets one through unwrapped.+ """+ try:+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError+ except Exception: # pragma: no cover - huggingface_hub ships with every HF loader+ return (OSError,)+ return (LocalEntryNotFoundError, EntryNotFoundError, OSError)+++def hf_from_pretrained_local_first(+ loader: Any,+ name_or_path: str,+ *,+ purpose: str,+ allow_network: bool = True,+ **kwargs: Any,+) -> Any:+ """Load a HuggingFace model/tokenizer/processor, local cache first.++ The ``from_pretrained`` twin of :func:`hf_hub_download_local_first`, for+ every loader that takes ``local_files_only`` — ``AutoModel.from_pretrained``,+ ``AutoTokenizer.from_pretrained``, ``AutoProcessor.from_pretrained``,+ ``SentenceTransformer`` and friends. ``loader`` is that callable, passed+ uncalled; ``kwargs`` are forwarded to both attempts.++ 1. ``local_files_only=True``: a pure cache lookup that cannot open a socket.+ A warm (or pre-seeded air-gapped) cache loads here and never touches the+ network, which also skips the Hub re-validation round-trips a plain+ ``from_pretrained`` makes on every load.+ 2. On a cache miss, :func:`guard_egress` runs BEFORE the remote attempt.++ Why the guard and not ``HF_HUB_OFFLINE``: ``apply_offline_env`` sets it with+ ``setdefault``, so an explicit ``HF_HUB_OFFLINE=0`` wins, and only the proxy+ process calls it at all. Under that configuration huggingface_hub's offline+ constant is false even with ``TRANSFORMERS_OFFLINE=1``, and a bare+ ``from_pretrained`` downloads. ``HEADROOM_OFFLINE`` is the master switch;+ this guard is what makes it one for model loaders.++ Args:+ loader: The ``from_pretrained``-style callable.+ name_or_path: Hub repo id or local directory.+ purpose: What is being loaded, for the refusal message ("SigLIP model").+ allow_network: When ``False`` a cache miss re-raises the local-lookup+ error instead of falling back to a download.+ **kwargs: Forwarded to ``loader`` (``revision=``, ``device=``, ...).++ Raises:+ OfflineEgressBlocked: ``HEADROOM_OFFLINE`` is set and the model is not+ cached. Callers translate this into their own "model unavailable".+ The loader's own error on a cache miss when ``allow_network`` is+ ``False``, when ``name_or_path`` is a local directory (nothing remote+ to fall back to), or when the remote attempt itself fails.+ """+ kwargs.pop("local_files_only", None)+ try:+ return loader(name_or_path, local_files_only=True, **kwargs)+ except _hf_not_cached_errors():+ # A local directory that failed to load has no remote to fall back to;+ # surface the real error rather than a download attempt or a refusal.+ if not allow_network or os.path.isdir(name_or_path):+ raise+ guard_egress(f"HuggingFace download of {purpose} ({name_or_path})", "huggingface.co")+ return loader(name_or_path, local_files_only=False, **kwargs)++def create_cpu_session_options(ort: Any,*,diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 4d36dcbd3..fd35a4ebf 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -97,7 +97,13 @@ from headroom.observability import (shutdown_headroom_tracing,shutdown_otel_metrics,)-from headroom.offline import apply_offline_env, is_offline+from headroom.offline import (+ OFFLINE_ENV,+ OfflineEgressBlocked,+ apply_offline_env,+ guard_egress,+ is_offline,+)from headroom.pipeline import PipelineExtensionManager, PipelineStagefrom headroom.providers.proxy_routes import register_provider_routesfrom headroom.providers.registry import (@@ -698,6 +704,89 @@ def _check_rust_core() -> tuple[str, str | None]:return ("loaded", None)+def _refuse_offline_egress(blocked: OfflineEgressBlocked, feature: str, fix: str) -> None:+ """Turn a startup-time air-gap refusal into a clean exit, never a traceback.++ ``OfflineEgressBlocked`` derives from ``BaseException``, so nothing in the+ lifespan's own ``except Exception`` will catch it and it would otherwise+ escape uvicorn as an unhandled error — killing a proxy that had been+ serving traffic, with a stack trace instead of an explanation, and before+ ``app.state.startup_error`` exists to record why. ``_check_rust_core``+ above already settled the shape for a startup refusal: say what is wrong,+ say how to fix it, exit 78 (``EX_CONFIG``).+ """+ msg = (+ f"FATAL: {feature} needs outbound network access, but "+ f"{OFFLINE_ENV}=1 forbids it.\n"+ f" refused: {blocked}\n"+ f" fix: {fix}\n"+ )+ logger.error(+ "event=offline_egress_refused feature=%r reason=%r action=exit_78",+ feature,+ str(blocked),+ )+ print(msg, file=sys.stderr, flush=True)+ sys.exit(_EXIT_CONFIG)+++def _configure_observability_or_refuse() -> None:+ """Install the metric/trace exporters, refusing cleanly under an air-gap.++ Both exporters call ``guard_egress`` before they build a client, so under+ ``HEADROOM_OFFLINE`` they raise rather than dial. Catching that here is what+ keeps the refusal a refusal: these two calls sit OUTSIDE ``lifespan``'s own+ ``try``/``except Exception``, and ``OfflineEgressBlocked`` is a+ ``BaseException``, so an uncaught one escapes uvicorn as an unhandled error+ — a proxy that had been serving traffic dies on a traceback with+ ``app.state.startup_error`` never set.+ """+ _preflight_offline_egress()+ try:+ configure_otel_metrics(OTelMetricsConfig.from_env(default_service_name="headroom-proxy"))+ except OfflineEgressBlocked as blocked:+ _refuse_offline_egress(+ blocked,+ "OTLP metric export (HEADROOM_OTEL_METRICS_ENABLED)",+ "set HEADROOM_OTEL_METRICS_EXPORTER=console or scrape /metrics "+ "(both stay on-box), or unset HEADROOM_OTEL_METRICS_ENABLED",+ )+ try:+ configure_langfuse_tracing(+ LangfuseTracingConfig.from_env(default_service_name="headroom-proxy")+ )+ except OfflineEgressBlocked as blocked:+ _refuse_offline_egress(+ blocked,+ "Langfuse OTLP trace export (HEADROOM_LANGFUSE_ENABLED)",+ "unset HEADROOM_LANGFUSE_ENABLED; Langfuse ingestion has no on-box mode",+ )+++def _preflight_offline_egress() -> None:+ """Refuse, at startup, any configuration that asks for egress while offline.++ Runs before the observability exporters are configured and before the+ compressors are preloaded. Without it the same contradiction surfaces later+ and worse: the OTLP exporter raised out of ``lifespan`` with a raw+ traceback, and the remote Kompress endpoint was not noticed until a request+ reached for the compressor.+ """+ if not is_offline():+ return+ endpoint = os.environ.get("HEADROOM_KOMPRESS_ENDPOINT", "").strip()+ if endpoint:+ try:+ guard_egress("remote Kompress inference", endpoint)+ except OfflineEgressBlocked as blocked:+ _refuse_offline_egress(+ blocked,+ "remote Kompress compression (HEADROOM_KOMPRESS_ENDPOINT)",+ "unset HEADROOM_KOMPRESS_ENDPOINT to use the local Kompress "+ "model, or unset " + OFFLINE_ENV + " if this box is not air-gapped",+ )++# Compression pipeline timeout in seconds@@ -3104,15 +3193,29 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:# Air-gap master switch. Propagate config.offline to the env so the# env-based egress predicates (telemetry, update check, license) all honor- # it, force HF/transformers offline before any model code loads, and- # announce that every outbound path is disabled.+ # it, force HF/transformers offline before any model code loads, and say+ # what is covered.+ #+ # The banner names the exception rather than claiming a whole-process kill+ # switch, and the exception is permanent rather than a to-do: a proxy that+ # refused to forward the caller's request to the caller's own upstream+ # would not be a proxy. Every connection Headroom itself initiates IS+ # refused; tests/test_offline_egress_chokepoint.py fails the build if a new+ # egress path appears that is neither guarded nor one of the four written+ # exceptions. TestDocsMatchTheGuarantee scans this file for the absolute+ # phrasings and fails while any remain.if config.offline:os.environ.setdefault("HEADROOM_OFFLINE", "1")if is_offline():apply_offline_env()logger.warning(- "event=proxy_offline_mode air-gap active — all outbound egress disabled "- "(telemetry, update check, license reporter, HuggingFace downloads)"+ "event=proxy_offline_mode air-gap active — every connection Headroom "+ "initiates is refused (telemetry, update check, license reporter, "+ "model/tokenizer/binary/dataset downloads, remote Kompress, "+ "OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI "+ "embedders, Headroom Cloud compression). Still allowed on purpose: "+ "forwarding your requests to the upstream you configured, "+ "operator-configured local endpoints, loopback health probes.")proxy = HeadroomProxy(config)@@ -3231,10 +3334,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:_rust_core_error,)- configure_otel_metrics(OTelMetricsConfig.from_env(default_service_name="headroom-proxy"))- configure_langfuse_tracing(- LangfuseTracingConfig.from_env(default_service_name="headroom-proxy")- )+ _configure_observability_or_refuse()app.state.started_at = time.time()app.state.ready = Falsediff --git a/headroom/proxy/tls_diagnostics.py b/headroom/proxy/tls_diagnostics.pyindex 0e7d3c303..527999fa4 100644--- a/headroom/proxy/tls_diagnostics.py+++ b/headroom/proxy/tls_diagnostics.py@@ -33,6 +33,8 @@ from dataclasses import asdict, dataclass, fieldfrom typing import Anyfrom urllib.parse import urlsplit+from headroom.offline import OfflineEgressBlocked, guard_egress, note_refusal+logger = logging.getLogger("headroom.proxy")DOCS_URL = "https://docs.headroomlabs.ai/docs/corporate-networks"@@ -302,6 +304,14 @@ def probe_presented_chain(def _probe_uncached(host: str, port: int, *, timeout: float, allow_private: bool) -> ChainInfo:proxy = _proxy_for(host)info = ChainInfo(host=host, port=port, reachable=False, via_proxy=proxy)+ # A second connection Headroom opens on its own, so HEADROOM_OFFLINE refuses+ # it. It only enriches a diagnostic: on the request path the refusal becomes+ # "no chain to report", and the TLS explanation is still given without it.+ try:+ guard_egress("TLS certificate-chain probe", f"{host}:{port}")+ except OfflineEgressBlocked as blocked:+ info.error = f"skipped: {note_refusal(blocked, logger)}"+ return info# Certificate-inspection handshake only: it reads the presented chain and# closes without sending a byte, so it deliberately skips verification (the# chain is what we are diagnosing). It still refuses TLS < 1.2, and it only@@ -459,7 +469,13 @@ def probe_endpoint(name: str, url: str, *, timeout: float = 8.0) -> EndpointRepoReports the presented chain (and any inspection vendor), whether the chainverifies under the policy Headroom will use, and whether the response is agateway block page instead of the service.++ Raises :class:`OfflineEgressBlocked` under ``HEADROOM_OFFLINE`` before+ either connection is attempted; ``headroom doctor`` reports that as a+ skipped check."""+ guard_egress("doctor --network endpoint check", url)+import httpxfrom headroom.proxy.ssl_context import build_httpx_verifydiff --git a/headroom/relevance/embedding.py b/headroom/relevance/embedding.pyindex 5105c2df8..666b6bb16 100644--- a/headroom/relevance/embedding.py+++ b/headroom/relevance/embedding.py@@ -30,6 +30,8 @@ import loggingimport osfrom typing import TYPE_CHECKING+from headroom.offline import OfflineEgressBlocked, guard_egress+from .base import RelevanceScore, RelevanceScorer# numpy is an optional dependency - import lazily@@ -57,6 +59,57 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)++def _load_text_embedding(kwargs: dict[str, str]) -> TextEmbedding:+ """Build a fastembed ``TextEmbedding``, cache first and network second.++ ``onnx_runtime.hf_hub_download_local_first`` can hang the air-gap guard on+ an explicit ``local_files_only=True`` attempt because ``hf_hub_download``+ takes that flag. fastembed's constructor does not, so the same cache-hit /+ network-fallback split has to be made here: try the load with the whole+ HuggingFace stack forced offline, and only reach for the guard when that+ fails, which is exactly the case where a socket would have been opened.++ This keeps the behaviour an air-gapped deployment actually wants — a+ pre-seeded cache still loads under ``HEADROOM_OFFLINE`` — while making a+ cold cache refuse instead of quietly dialling huggingface.co. A plain+ unconditional guard would have broken the pre-seeded case, which is the+ reason this path was left unguarded before.++ The ``HF_HUB_OFFLINE`` flip is process-global for the duration of the+ call. That is acceptable here because loading is one-shot and memoised by+ the caller, and because the value it forces is *stricter* than whatever it+ replaces, so a concurrent HuggingFace call can only be refused locally,+ never sent somewhere it would not otherwise go.+ """+ from fastembed import TextEmbedding+ from huggingface_hub import constants as hf_constants++ # huggingface_hub reads HF_HUB_OFFLINE once, at import, into+ # ``constants.HF_HUB_OFFLINE``; if it was imported before this call the+ # env var alone changes nothing. Force both.+ previous = os.environ.get("HF_HUB_OFFLINE")+ previous_constant = hf_constants.HF_HUB_OFFLINE+ os.environ["HF_HUB_OFFLINE"] = "1"+ hf_constants.HF_HUB_OFFLINE = True+ try:+ return TextEmbedding(**kwargs)+ except Exception as cache_miss: # noqa: BLE001 - any local-lookup failure+ logger.debug("fastembed cache lookup failed, falling back to network: %s", cache_miss)+ finally:+ hf_constants.HF_HUB_OFFLINE = previous_constant+ if previous is None:+ os.environ.pop("HF_HUB_OFFLINE", None)+ else:+ os.environ["HF_HUB_OFFLINE"] = previous++ guard_egress(+ f"fastembed weight download for {kwargs['model_name']}",+ "huggingface.co",+ )+ return TextEmbedding(**kwargs)++# Default model name. Same string used by the Rust embedding scorer.DEFAULT_MODEL_NAME = "BAAI/bge-small-en-v1.5"@@ -169,14 +222,24 @@ class EmbeddingScorer(RelevanceScorer):)if self._model is None:- from fastembed import TextEmbedding-revision = _pinned_revision(self.model_name)+ kwargs = {"model_name": self.model_name}if revision is not None:# fastembed forwards **kwargs to snapshot_download(revision=...).- self._model = TextEmbedding(model_name=self.model_name, revision=revision)- else:- self._model = TextEmbedding(model_name=self.model_name)+ kwargs["revision"] = revision+ try:+ self._model = _load_text_embedding(kwargs)+ except OfflineEgressBlocked as blocked:+ # Translate at the boundary that owns the degradation, the way+ # the Kompress and ONNX loaders do. Public model weights are+ # not data leaving the box, so what the caller needs to hear+ # is "this model is not available here and why", not an+ # air-gap type it has never seen.+ raise RuntimeError(+ f"Embedding model {self.model_name!r} is unavailable: {blocked}. "+ "Pre-seed the fastembed/HuggingFace cache on this host, or "+ "use the BM25-only scorer."+ ) from Nonereturn self._modeldef _encode(self, texts: list[str]):diff --git a/headroom/subscription/client.py b/headroom/subscription/client.pyindex 11b6b08fa..1cf9ed7fb 100644--- a/headroom/subscription/client.py+++ b/headroom/subscription/client.py@@ -21,6 +21,7 @@ from typing import Anyimport httpx+from headroom.offline import OfflineEgressBlocked, guard_egress, note_refusalfrom headroom.subscription.models import SubscriptionSnapshotlogger = logging.getLogger(__name__)@@ -106,6 +107,10 @@ class SubscriptionClient:}try:+ # First statement in the block that opens the socket, so the guard+ # provably runs before the client is built (which is also what the+ # egress meta-test's dominance rule checks).+ guard_egress("Anthropic subscription usage polling", _USAGE_URL)async with httpx.AsyncClient(timeout=self._timeout) as client:resp = await client.get(_USAGE_URL, headers=headers)@@ -123,6 +128,14 @@ class SubscriptionClient:data: dict[str, Any] = resp.json()return SubscriptionSnapshot.from_api_response(data, token=resolved)+ except OfflineEgressBlocked as blocked:+ # Refuse, but as a sentence in the log rather than an unhandled+ # BaseException inside a background poll. The caller reads `None`+ # as "no window data", which is the truth here: an air-gapped box+ # cannot know the subscription window, and pretending otherwise+ # would be worse than saying so once and moving on.+ note_refusal(blocked, logger)+ return Noneexcept httpx.TimeoutException:logger.debug("Timeout fetching Anthropic subscription window")return Nonediff --git a/headroom/subscription/codex_rate_limits.py b/headroom/subscription/codex_rate_limits.pyindex 096735fb1..e7c3e1747 100644--- a/headroom/subscription/codex_rate_limits.py+++ b/headroom/subscription/codex_rate_limits.py@@ -50,6 +50,7 @@ from threading import Lockimport httpx+from headroom.offline import OfflineEgressBlocked, guard_egress, is_offline, note_refusalfrom headroom.subscription.base import QuotaTrackerlogger = logging.getLogger(__name__)@@ -450,6 +451,7 @@ def _build_usage_headers(request_headers: dict[str, str]) -> dict[str, str] | Noasync def _fetch_and_store_usage(url: str, headers: dict[str, str]) -> None:state = get_codex_rate_limit_state()try:+ guard_egress("Codex rate-limit polling", url)async with httpx.AsyncClient(timeout=_USAGE_POLL_TIMEOUT_S) as client:resp = await client.get(url, headers=headers)if resp.status_code == 200:@@ -459,6 +461,12 @@ async def _fetch_and_store_usage(url: str, headers: dict[str, str]) -> None:logger.debug("codex usage poll: 200 but no usable rate-limit data")else:logger.debug("codex usage poll: HTTP %s", resp.status_code)+ except OfflineEgressBlocked as blocked:+ # Background task: report the refusal as a sentence. Letting a+ # BaseException out of a bare ``create_task`` surfaces as "Task+ # exception was never retrieved" whenever the GC gets round to it,+ # which is a traceback with no explanation in it.+ note_refusal(blocked, logger)except Exception as exc: # pragma: no cover - network/JSON defensivelogger.debug("codex usage poll failed: %s", exc)finally:@@ -488,6 +496,12 @@ def maybe_schedule_usage_poll(headers = _build_usage_headers(request_headers)if headers is None:return False+ if is_offline():+ # Cheap pre-check so an air-gapped proxy does not spawn (and log) a+ # doomed task on every single Codex request. The guard inside+ # _fetch_and_store_usage is still the thing that makes the refusal+ # true; this only keeps the log and the event loop quiet.+ return Falsetry:loop = asyncio.get_running_loop()except RuntimeError:diff --git a/headroom/subscription/copilot_quota.py b/headroom/subscription/copilot_quota.pyindex 7a0cf9849..7e5c5f239 100644--- a/headroom/subscription/copilot_quota.py+++ b/headroom/subscription/copilot_quota.py@@ -41,6 +41,7 @@ from dataclasses import dataclass, fieldfrom threading import Lockfrom typing import Any+from headroom.offline import OfflineEgressBlocked, guard_egress, note_refusalfrom headroom.subscription.base import QuotaTrackerlogger = logging.getLogger(__name__)@@ -314,6 +315,7 @@ class _CopilotQuotaTracker(QuotaTracker):}try:+ guard_egress("GitHub Copilot quota polling", _GITHUB_API_BASE)async with aiohttp.ClientSession() as session:async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=10)@@ -333,6 +335,13 @@ class _CopilotQuotaTracker(QuotaTracker):returndata = await resp.json()+ except OfflineEgressBlocked as blocked:+ # Say it twice, in the two places an operator looks: once in the+ # log, and once in the quota panel's own error slot, so the empty+ # panel carries its reason instead of looking like a broken poll.+ with self._lock:+ self._state.last_error = note_refusal(blocked, logger)+ returnexcept Exception as exc:with self._lock:self._state.last_error = str(exc)diff --git a/headroom/tokenizers/huggingface.py b/headroom/tokenizers/huggingface.pyindex f6f546756..0a81ff10e 100644--- a/headroom/tokenizers/huggingface.py+++ b/headroom/tokenizers/huggingface.py@@ -226,7 +226,7 @@ def _load_tokenizer(tokenizer_name: str):# vetted, not a variant the caller chose.tokenizer_name = repo- from headroom.offline import apply_offline_env, is_offline+ from headroom.offline import apply_offline_env, guard_egress, is_offlineoffline = is_offline()if offline:@@ -268,6 +268,10 @@ def _load_tokenizer(tokenizer_name: str):def _download() -> None:try:+ # Defence in depth behind the is_offline() return above: the switch+ # could flip between that check and this thread, and the guard is+ # what the egress meta-test recognises as dominating the fetch.+ guard_egress(f"HuggingFace tokenizer download ({tokenizer_name})", "huggingface.co")result.append(AutoTokenizer.from_pretrained(tokenizer_name,diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex 200657468..848cb81fe 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -63,6 +63,7 @@ from ..config import (is_tool_excluded,unwrap_tool_call,)+from ..offline import OfflineEgressBlockedfrom ..parser import CCR_RETRIEVAL_MARKER_REfrom ..tokenizer import Tokenizerfrom ..tokenizers.base import count_content_blocks@@ -1185,7 +1186,7 @@ def _detect_content(content: str) -> DetectionResult:# "json_array"); translate to the Python `ContentType` enum so# downstream mapping keys match.content_type = ContentType(rust_result.content_type)- except (KeyboardInterrupt, SystemExit, GeneratorExit):+ except (KeyboardInterrupt, SystemExit, GeneratorExit, OfflineEgressBlocked):raiseexcept BaseException as exc: # noqa: BLE001# A native Rust panic surfaces as pyo3_runtime.PanicException, which@@ -1194,7 +1195,9 @@ def _detect_content(content: str) -> DetectionResult:# (panic, or an unrecognized content-type tag) degrades to the# pure-Python detector instead of aborting the request. See #1123.# Guard: don't swallow cancellation/control-flow BaseExceptions such- # as asyncio.CancelledError — keep them propagating.+ # as asyncio.CancelledError — keep them propagating. OfflineEgressBlocked+ # is in that list for the same reason: it is a policy refusal, not a+ # detector failure, and degrading it here would hide the air-gap switch.if isinstance(exc, asyncio.CancelledError):raiseif isinstance(exc, TimeoutError):diff --git a/headroom/transforms/kompress_compressor.py b/headroom/transforms/kompress_compressor.pyindex 0fab296f2..0b9a8a8e6 100644--- a/headroom/transforms/kompress_compressor.py+++ b/headroom/transforms/kompress_compressor.py@@ -28,11 +28,13 @@ from functools import lru_cachefrom typing import Any, Literalfrom ..config import TransformResult+from ..offline import OFFLINE_ENV, OfflineEgressBlockedfrom ..onnx_runtime import (ONNX_CPU_ARENA_ENV,_resolve_revision,create_cpu_session_options,hf_entry_known_absent,+ hf_from_pretrained_local_first,hf_hub_download_local_first,trim_process_heap,)@@ -220,6 +222,70 @@ class KompressModelNotCached(RuntimeError):"""+def _hf_artifact(model_id: str, filename: str, *, allow_network: bool) -> str:+ """``hf_hub_download_local_first`` with the air-gap refusal translated.++ ``OfflineEgressBlocked`` is a ``BaseException`` so that no ``except+ Exception:`` can silently degrade an air-gap refusal into "that feature+ stopped working". At THIS boundary that degradation is the correct+ behaviour and is written down rather than inherited: a model download is+ not data leaving the box, every caller below already handles+ "the model is not available locally", and failing a user's request because+ an optional compressor could not fetch public weights would punish the+ request for a decision the operator made about the host.++ So the refusal is logged with the switch named and re-raised as+ :class:`KompressModelNotCached`, which is exactly what it means: under+ ``HEADROOM_OFFLINE`` the only artifacts that will ever be available are the+ cached ones. The original refusal is chained, so it is still in the+ traceback.+ """+ try:+ return hf_hub_download_local_first(model_id, filename, allow_network=allow_network)+ except OfflineEgressBlocked as blocked:+ logger.warning(+ "Kompress: %r for %s is not cached and %s forbids fetching it (%s). "+ "Compression falls back to the non-ML path.",+ filename,+ model_id,+ OFFLINE_ENV,+ blocked,+ )+ raise KompressModelNotCached(model_id) from blocked+++def _hf_pretrained(+ loader: Any, name: str, *, purpose: str, allow_download: bool, **kwargs: Any+) -> Any:+ """``hf_from_pretrained_local_first`` with Kompress's two translations.++ The ``from_pretrained`` counterpart of :func:`_hf_artifact`: cache first,+ ``guard_egress`` before any remote attempt, and both "not cached while+ downloads are disallowed" and "not cached while ``HEADROOM_OFFLINE`` is set"+ surface as :class:`KompressModelNotCached` — the error every Kompress caller+ already treats as "use the non-ML path". A genuine remote failure while+ downloads are allowed propagates unchanged.+ """+ try:+ return hf_from_pretrained_local_first(+ loader, name, purpose=purpose, allow_network=allow_download, **kwargs+ )+ except OfflineEgressBlocked as blocked:+ logger.warning(+ "Kompress: the %s (%s) is not cached and %s forbids fetching it (%s). "+ "Compression falls back to the non-ML path.",+ purpose,+ name,+ OFFLINE_ENV,+ blocked,+ )+ raise KompressModelNotCached(name) from blocked+ except _NOT_CACHED_ERRORS as exc:+ if allow_download:+ raise+ raise KompressModelNotCached(name) from exc++# Model cache: model_id -> (model, tokenizer, backend)# Supports multiple models loaded simultaneously._kompress_cache: dict[str, tuple[Any, Any, str]] = {}@@ -611,11 +677,14 @@ def _get_model_class() -> type:super().__init__()# Same pin as the tokenizer: the fine-tuned heads were trained on# this encoder snapshot. Unknown repos resolve to None (floating).- self.encoder = AutoModel.from_pretrained(+ # Cache first, air-gap guard before any download (see _hf_pretrained).+ self.encoder = _hf_pretrained(+ AutoModel.from_pretrained,model_name,+ purpose="Kompress PyTorch encoder",+ allow_download=allow_download,attn_implementation="eager",revision=_resolve_revision(model_name, revision),- local_files_only=not allow_download,)hidden_size = self.encoder.config.hidden_size # 768@@ -750,12 +819,19 @@ def _create_onnx_session("""last_err: Exception | None = Nonecache_miss = False+ refused: KompressModelNotCached | None = Noneort: Any = Nonefor filename in _onnx_filename_candidates():try:- onnx_path = hf_hub_download_local_first(- model_id, filename, allow_network=allow_download+ onnx_path = _hf_artifact(+ model_id, filename, allow_network=allow_download and refused is None)+ except KompressModelNotCached as exc:+ # Only _hf_artifact's air-gap translation raises this here. It says+ # THIS candidate is not cached; a later one may be. Keep looking,+ # cache-only, so the refusal is logged once and never retried.+ refused = exc+ continueexcept Exception as exc:last_err = exccache_miss = cache_miss or isinstance(exc, _NOT_CACHED_ERRORS)@@ -781,6 +857,8 @@ def _create_onnx_session(model_id,exc,)+ if refused is not None:+ raise refusedif not allow_download and cache_miss:raise KompressModelNotCached(model_id) from last_errraise FileNotFoundError(@@ -860,8 +938,11 @@ def _load_modernbert_tokenizer(auto_tokenizer: Any, *, allow_download: bool) ->Same files, same tokenizer, so the loaded object is identical; this onlychanges whether the Hub is consulted to confirm what is already on disk.- Mirrors ``onnx_runtime.hf_hub_download_local_first``, which the ONNX half of- this loader already uses.+ Goes through ``onnx_runtime.hf_from_pretrained_local_first`` (via+ :func:`_hf_pretrained`), the ``from_pretrained`` twin of the+ ``hf_hub_download_local_first`` the ONNX half of this loader uses, so a cache+ miss under ``HEADROOM_OFFLINE`` is refused before any remote attempt even+ when ``HF_HUB_OFFLINE=0`` is set explicitly.The load is pinned to the same immutable revision as the model artifacts(``onnx_runtime._PINNED_REVISIONS``): the ONNX export was produced against@@ -869,17 +950,12 @@ def _load_modernbert_tokenizer(auto_tokenizer: Any, *, allow_download: bool) ->the shipped weights without any code change. ``HEADROOM_HF_PIN=off`` floatsit, exactly as for the weights."""- revision = _resolve_revision(_MODERNBERT_TOKENIZER_REPO, None)- try:- return auto_tokenizer.from_pretrained(- _MODERNBERT_TOKENIZER_REPO, revision=revision, local_files_only=True- )- except _NOT_CACHED_ERRORS as exc:- if not allow_download:- raise KompressModelNotCached(_MODERNBERT_TOKENIZER_REPO) from exc- # Genuine cache miss and downloading is permitted: fetch it at the pin.- return auto_tokenizer.from_pretrained(- _MODERNBERT_TOKENIZER_REPO, revision=revision, local_files_only=False+ return _hf_pretrained(+ auto_tokenizer.from_pretrained,+ _MODERNBERT_TOKENIZER_REPO,+ purpose="ModernBERT tokenizer",+ allow_download=allow_download,+ revision=_resolve_revision(_MODERNBERT_TOKENIZER_REPO, None),)@@ -954,7 +1030,7 @@ def _load_pytorch_weights(model: Any, model_id: str, *, allow_download: bool) ->HuggingFace Hub's own cache of confirmed-404 lookups."""try:- ckpt_path = hf_hub_download_local_first(model_id, "merged.pt", allow_network=allow_download)+ ckpt_path = _hf_artifact(model_id, "merged.pt", allow_network=allow_download)except _NOT_CACHED_ERRORS as exc:if not allow_download:if not hf_entry_known_absent(model_id, "merged.pt"):@@ -971,9 +1047,7 @@ def _load_pytorch_weights(model: Any, model_id: str, *, allow_download: bool) -># merged.pt genuinely does not exist in this repo (confirmed by a# real network lookup, not just a cache miss) - fall back to the# plain format instead of treating it as a download failure.- weights_path = hf_hub_download_local_first(- model_id, "model.safetensors", allow_network=allow_download- )+ weights_path = _hf_artifact(model_id, "model.safetensors", allow_network=allow_download)_load_plain_state_dict(model, weights_path, model_id)returnraise@@ -1218,6 +1292,21 @@ def _background_download(model_id: str, device: str) -> None:logger.info("Kompress: downloading model %s in the background ...", model_id)_load_kompress(model_id, device, allow_download=True)logger.info("Kompress: background model download complete for %s", model_id)+ except OfflineEgressBlocked as blocked:+ # Explicit, because OfflineEgressBlocked is a BaseException and would+ # otherwise reach threading.excepthook as a bare traceback on every+ # air-gapped startup with a cold cache. This is a background *refresh*,+ # not the request path: the refusal is reported once, at WARNING, and+ # the compressor keeps whatever is already cached. Do NOT widen this to+ # `except Exception` — that is the shape the guard exists to defeat.+ _record_download_failure(model_id)+ logger.warning(+ "Kompress: background model download refused for %s (%s is set): %s. "+ "The model will only load if its artifacts are already cached.",+ model_id,+ OFFLINE_ENV,+ blocked,+ )except Exception as exc:_record_download_failure(model_id)logger.warning("Kompress: background model download failed for %s: %s", model_id, exc)@@ -1277,6 +1366,18 @@ def prefetch_kompress_artifacts(model_id: str = HF_MODEL_ID) -> bool:try:hf_hub_download_local_first(model_id, filename, allow_network=True)return True+ except OfflineEgressBlocked as blocked:+ # Same reasoning as _background_download: explicit because it is a+ # BaseException, reported rather than swallowed, and terminal for+ # the whole loop — every candidate would be refused for the same+ # reason, so retrying them just logs the same refusal four times.+ logger.warning(+ "Kompress: artifact prefetch refused for %s (%s is set): %s",+ model_id,+ OFFLINE_ENV,+ blocked,+ )+ return Falseexcept Exception as exc:logger.debug("Kompress prefetch: %r unavailable for %s: %s", filename, model_id, exc)return Falsediff --git a/headroom/transforms/kompress_remote.py b/headroom/transforms/kompress_remote.pyindex 0d1be810d..4ebabd88d 100644--- a/headroom/transforms/kompress_remote.py+++ b/headroom/transforms/kompress_remote.py@@ -57,6 +57,7 @@ import loggingimport httpx+from ..offline import guard_egressfrom .kompress_compressor import (KompressConfig,KompressResult,@@ -139,6 +140,13 @@ class RemoteKompressCompressor:# without needing a separate auth-scheme setting.if headers:self._headers.update(headers)+ # Air-gap chokepoint. HEADROOM_KOMPRESS_ENDPOINT points at a box that is+ # by definition off this host, so under HEADROOM_OFFLINE this class must+ # not exist at all. Guarding at construction (not at the POST) means the+ # connection pool is never created and the operator hears about the+ # contradictory configuration the first time the router reaches for+ # Kompress, rather than discovering it in a packet capture.+ guard_egress("remote Kompress inference", self._url)# httpx.Client is safe to share across the proxy's worker threads.self._client = httpx.Client(timeout=timeout)@@ -212,6 +220,16 @@ class RemoteKompressCompressor:if n_words < max(_MIN_WORDS, self.config.min_input_words):return self._passthrough(content, n_words)+ # Re-check outside the fail-open try. __init__ already refused if the+ # flag was set then, but the env can be flipped after this object was+ # cached on the ContentRouter (the router builds it once per instance+ # and reuses it for the process lifetime), and the security property we+ # owe is "no socket", not "no construction". It is outside the try on+ # purpose: the except below turns every exception into a silent+ # pass-through, and a policy refusal that degrades silently is exactly+ # the hole this guard closes.+ guard_egress("remote Kompress inference", self._url)+try:resp = self._client.post(self._url,diff --git a/tests/test_offline_egress_chokepoint.py b/tests/test_offline_egress_chokepoint.pynew file mode 100644index 000000000..e6dff6d42--- /dev/null+++ b/tests/test_offline_egress_chokepoint.py@@ -0,0 +1,2947 @@+"""A-2: ``HEADROOM_OFFLINE=1`` must actually stop outbound connections.++The switch was documented as an air-gap guarantee but several egress paths+never consulted it, so a customer who set it and believed they were air-gapped+was wrong. These tests pin the guarantee down in two complementary ways:++* **Per-path socket tests.** Each previously-unguarded path is exercised with+ ``socket.socket.connect`` / ``socket.create_connection`` booby-trapped, so+ the test fails if a single connection is attempted. Asserting "no socket"+ rather than "raises" matters: a guard placed after the client is constructed+ would still pass a raises-check while leaking a connection.++* **A meta-test.** The per-path tests only cover the paths we already know+ about, and the whole point of a chokepoint is that path number four cannot+ forget it. ``test_every_egress_site_is_guarded_or_allowlisted`` enumerates+ the outbound clients in ``headroom/`` and requires each **site** either to+ have a ``guard_egress`` call that dominates it or to be counted in the+ allowlist with a written reason. Per site, not per file: a file-wide+ "contains the string guard_egress" check — the first version of this test —+ exempts a module because of a word in its docstring, and makes the+ allowlist's site counts unreachable for every file that guards anything.+ ``TestSiteScannerRules`` pins each of those bypasses.++* **The same sweep over ``crates/``.** ``TestRustEgressChokepointCoverage``+ applies a text-level version of the rule to the Rust sources. ``crates/``+ was outside the Python scan entirely, which is how the Kompress model and+ fastembed weight downloads stayed open in the same change that guarded the+ Rust tokenizer fetch for precisely the reason that applied to all three.++The runtime behaviour of the Rust switch (``crates/headroom-core/src/+offline.rs``) is tested by ``cargo test -p headroom-core``; what lives here is+the cross-language parity assertion, because the two implementations silently+drifting apart is the failure mode a Python-only test suite cannot see.+"""++from __future__ import annotations++import ast+import ipaddress+import os+import re+import socket+from collections.abc import Iterator+from dataclasses import dataclass+from pathlib import Path+from types import SimpleNamespace+from urllib.parse import urlsplit++import pytest++from headroom.offline import OfflineEgressBlocked, guard_egress++REPO_ROOT = Path(__file__).resolve().parent.parent+PACKAGE_ROOT = REPO_ROOT / "headroom"+++# ──────────────────────────── socket booby trap ────────────────────────────+++class SocketOpened(AssertionError):+ """Raised from the patched socket entry points.++ An ``AssertionError`` subclass so that a path which swallows broad+ ``Exception`` still surfaces this as a test failure rather than being+ mistaken for the network error it is imitating.+ """+++def _is_loopback(address: object) -> bool:+ """True for an ``(ip, port, ...)`` address whose IP literal is loopback.++ IP literals only: a hostname such as ``localhost`` would need resolving,+ and resolving is exactly what the trap must not take on trust.+ """+ if not isinstance(address, tuple) or not address or not isinstance(address[0], str):+ return False+ try:+ return ipaddress.ip_address(address[0].split("%", 1)[0]).is_loopback+ except ValueError:+ return False+++def no_sockets(monkeypatch: pytest.MonkeyPatch) -> None:+ """Make any attempt to open an outbound TCP connection fail the test.++ We patch the three entry points that every client in this tree bottoms out+ in: ``socket.create_connection`` (urllib, httpcore's sync backend),+ ``socket.socket.connect`` and ``socket.socket.connect_ex`` (everything+ else, including anyio's async backend). Creating a socket object is+ harmless — connecting is what leaves the box — so we trap the connect, not+ the constructor.++ Connects to a loopback IP literal are let through, because they cannot+ leave the box and the event loop itself makes one: on Windows,+ ``asyncio.run()`` builds a Proactor loop whose self-pipe is a+ ``socket.socketpair()``, and Windows implements that as a ``127.0.0.1``+ listen + connect. Trapping it failed every async test while the loop was+ being constructed, before any Headroom code ran.+ """+ real_create_connection = socket.create_connection+ real_connect = socket.socket.connect+ real_connect_ex = socket.socket.connect_ex++ def _refuse(address: object) -> None:+ raise SocketOpened(f"outbound connection attempted while offline: {address!r}")++ def _create_connection(address: object, *args: object, **kwargs: object) -> socket.socket:+ if not _is_loopback(address):+ _refuse(address)+ return real_create_connection(address, *args, **kwargs) # type: ignore[arg-type]++ def _connect(self: socket.socket, address: object) -> None:+ if not _is_loopback(address):+ _refuse(address)+ real_connect(self, address) # type: ignore[arg-type]++ def _connect_ex(self: socket.socket, address: object) -> int:+ if not _is_loopback(address):+ _refuse(address)+ return real_connect_ex(self, address) # type: ignore[arg-type]++ monkeypatch.setattr(socket, "create_connection", _create_connection)+ monkeypatch.setattr(socket.socket, "connect", _connect)+ monkeypatch.setattr(socket.socket, "connect_ex", _connect_ex)+++class TestSocketTrap:+ """The trap itself: it must still catch egress, and must not catch the loop."""++ def test_event_loop_wakeup_pipe_is_not_egress(+ self, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Reproduces the Windows failure on every platform.++ ``socket._fallback_socketpair`` is the implementation Windows uses for+ ``socket.socketpair()``: a loopback listen + connect. Forcing it makes+ ``asyncio.run()`` build its self-pipe the way the Proactor loop does.+ """+ import asyncio++ fallback = getattr(socket, "_fallback_socketpair", None)+ if fallback is None:+ pytest.skip("this Python has no socket._fallback_socketpair")+ monkeypatch.setattr(socket, "socketpair", fallback)++ async def nothing() -> str:+ return "ran"++ assert asyncio.run(nothing()) == "ran"++ @pytest.mark.parametrize("address", [("192.0.2.1", 443), ("2001:db8::1", 443)])+ def test_an_outbound_connect_is_still_caught(+ self, no_sockets: None, address: tuple[str, int]+ ) -> None:+ family = socket.AF_INET6 if ":" in address[0] else socket.AF_INET+ with socket.socket(family, socket.SOCK_STREAM) as sock:+ with pytest.raises(SocketOpened):+ sock.connect(address)+ with pytest.raises(SocketOpened):+ sock.connect_ex(address)+ with pytest.raises(SocketOpened):+ socket.create_connection(address, timeout=0.01)++ def test_a_hostname_is_not_trusted_as_loopback(self, no_sockets: None) -> None:+ with pytest.raises(SocketOpened):+ socket.create_connection(("localhost", 9), timeout=0.01)+++def offline(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("HEADROOM_OFFLINE", "1")+++# ``"example.com" in url`` is true of ``https://example.com.attacker.test``+# and of ``https://host/?next=example.com``. These two helpers parse instead,+# so a refusal test asserts the host the guard actually named.+_URL_IN_PROSE = re.compile(r"https?://[^\s,)'\"]+")+++def _hostnames_in(text: str) -> set[str]:+ """Every URL host mentioned in a message, compared by parsing."""+ return {+ host+ for url in _URL_IN_PROSE.findall(text)+ if (host := urlsplit(url.rstrip(".")).hostname) is not None+ }+++def _refused_hostname(blocked: OfflineEgressBlocked) -> str | None:+ """The host the guard refused, taken from the exception, not the prose."""+ destination = blocked.destination+ if destination is None:+ return None+ if "://" not in destination:+ return urlsplit(f"//{destination}").hostname+ return urlsplit(destination).hostname+++# ─────────────────────────── the guard's own contract ───────────────────────+++class TestGuardEgress:+ def test_raises_when_offline(self, offline: None) -> None:+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ guard_egress("widget sync", "https://widgets.example.com")+ message = str(excinfo.value)+ # The operator has to be able to act on this without reading source:+ # which switch, which feature, which host. The host is compared by+ # parsing rather than by substring — `"widgets.example.com" in url` is+ # true of `https://widgets.example.com.attacker.test` too, so a+ # substring check here would assert something weaker than the thing+ # the test is named after (and CodeQL is right to flag it).+ destination = excinfo.value.destination+ assert destination is not None+ assert urlsplit(destination).hostname == "widgets.example.com"+ assert "HEADROOM_OFFLINE" in message+ assert excinfo.value.purpose == "widget sync"+ assert "widget sync" in message+ assert f" to {destination}" in message++ def test_is_a_no_op_when_online(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("HEADROOM_OFFLINE", raising=False)+ assert guard_egress("widget sync", "https://widgets.example.com") is None++ def test_is_outside_the_exception_hierarchy(self) -> None:+ """The refusal must survive a ``except Exception`` fail-open handler.++ It used to be a ``RuntimeError`` and the module docstring asked every+ broad handler to re-raise it. Nothing did: four reachable+ ``except Exception`` blocks turned the refusal into silent degradation,+ and a full ``/v1/messages`` request under ``HEADROOM_OFFLINE=1`` with a+ remote Kompress endpoint returned 200 with the content uncompressed+ while the guard had fired twice. The convention was the bug; the type+ is the fix.+ """+ assert issubclass(OfflineEgressBlocked, BaseException)+ assert not issubclass(OfflineEgressBlocked, Exception), (+ "OfflineEgressBlocked must stay outside Exception, or every "+ "`except Exception:` fail-open handler in the tree silently "+ "downgrades an air-gap refusal to 'that feature stopped working'."+ )++ def test_a_broad_exception_handler_cannot_swallow_it(self, offline: None) -> None:+ """The property above, exercised rather than asserted about."""+ swallowed = False+ try:+ try:+ guard_egress("widget sync", "https://widgets.example.com")+ except Exception: # noqa: BLE001 — the whole point of the test+ swallowed = True+ except OfflineEgressBlocked:+ pass+ assert not swallowed+++# ──────────────────────── path 1: remote Kompress ───────────────────────────+++class TestRemoteKompressOffline:+ def test_constructing_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom.transforms.kompress_remote import RemoteKompressCompressor++ with pytest.raises(OfflineEgressBlocked):+ RemoteKompressCompressor(endpoint="https://kompress.example.com", token="secret")++ def test_compress_refuses_when_the_flag_flips_after_construction(+ self, monkeypatch: pytest.MonkeyPatch, no_sockets: None+ ) -> None:+ """The ContentRouter caches one compressor per instance, so an object+ built before the switch was set outlives it. The second guard, inside+ ``compress``, is what covers that window."""+ from headroom.transforms.kompress_remote import RemoteKompressCompressor++ monkeypatch.delenv("HEADROOM_OFFLINE", raising=False)+ compressor = RemoteKompressCompressor(endpoint="https://kompress.example.com")++ monkeypatch.setenv("HEADROOM_OFFLINE", "1")+ # Comfortably over KompressConfig.min_input_words (64), so we are past+ # the short-input passthrough and genuinely on the POST path.+ content = "alpha beta gamma delta " * 40+ with pytest.raises(OfflineEgressBlocked):+ compressor.compress(content)++ def test_compress_guard_is_outside_the_fail_open_handler(+ self, monkeypatch: pytest.MonkeyPatch, no_sockets: None+ ) -> None:+ """``compress`` turns every exception into a silent passthrough. If the+ guard sat inside that ``try``, the air-gap refusal would degrade to+ "compression just stopped working" with no signal — which is how the+ defect hid in the first place."""+ from headroom.transforms.kompress_remote import RemoteKompressCompressor++ monkeypatch.delenv("HEADROOM_OFFLINE", raising=False)+ compressor = RemoteKompressCompressor(endpoint="https://kompress.example.com")+ monkeypatch.setenv("HEADROOM_OFFLINE", "1")++ content = "alpha beta gamma delta " * 40+ try:+ result = compressor.compress(content)+ except OfflineEgressBlocked:+ return+ pytest.fail(+ "compress() swallowed the offline refusal and passed content "+ f"through (compressed == original: {result.compressed == content})"+ )+++# ────────────────────── path 2: OTLP metric exporter ────────────────────────+++class TestOtlpExporterOffline:+ def test_configure_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom.observability.metrics import OTelMetricsConfig, configure_otel_metrics++ config = OTelMetricsConfig(+ enabled=True,+ exporter="otlp_http",+ endpoint="http://collector.example.com:4318/v1/metrics",+ )+ with pytest.raises(OfflineEgressBlocked):+ configure_otel_metrics(config)++ def test_default_endpoint_is_blocked_too(self, offline: None, no_sockets: None) -> None:+ """With no explicit endpoint the OTEL SDK falls back to+ ``OTEL_EXPORTER_OTLP_ENDPOINT`` or ``localhost:4318``. "We did not name+ a host" is not the same as "we will not connect", so the guard must+ fire on the unset case as well."""+ from headroom.observability.metrics import OTelMetricsConfig, configure_otel_metrics++ with pytest.raises(OfflineEgressBlocked):+ configure_otel_metrics(OTelMetricsConfig(enabled=True, exporter="otlp_http"))++ def test_disabled_config_is_untouched(self, offline: None, no_sockets: None) -> None:+ # enabled=False never had an exporter; it must stay a quiet no-op+ # rather than becoming a new startup failure.+ from headroom.observability.metrics import OTelMetricsConfig, configure_otel_metrics++ assert configure_otel_metrics(OTelMetricsConfig(enabled=False)) is not None++ def test_console_exporter_still_works_offline(self, offline: None, no_sockets: None) -> None:+ """The escape hatch we point operators at. If this ever starts raising,+ an air-gapped deployment has no metrics story at all."""+ from headroom.observability import metrics as metrics_mod+ from headroom.observability.metrics import OTelMetricsConfig, configure_otel_metrics++ previous = metrics_mod._global_metrics+ try:+ configured = configure_otel_metrics(OTelMetricsConfig(enabled=True, exporter="console"))+ assert configured is not None+ finally:+ # configure_otel_metrics installs a process-global MeterProvider+ # with a background export timer. Left running, it keeps writing to+ # pytest's captured stdout after the test closes it. Tear it down+ # and put the previous facade back.+ provider = metrics_mod._owned_meter_provider+ if provider is not None:+ provider.shutdown()+ with metrics_mod._metrics_lock:+ metrics_mod._owned_meter_provider = None+ metrics_mod._owned_metrics_config = None+ metrics_mod._global_metrics = previous+++# ───────────── path 2b: the Langfuse OTLP trace exporter ────────────────────+++class TestLangfuseExporterOffline:+ """The metric exporter's twin, missed when the metric one was guarded.++ Same shape — an OTLP/HTTP exporter plus a background batch timer — but+ pointed at ``cloud.langfuse.com`` by default rather than at whatever the+ operator configured, so if anything it is the more clear-cut egress of the+ two.+ """++ def test_configure_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom.observability.tracing import (+ LangfuseTracingConfig,+ configure_langfuse_tracing,+ )++ config = LangfuseTracingConfig(enabled=True, public_key="pk", secret_key="sk")+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ configure_langfuse_tracing(config)+ assert _refused_hostname(excinfo.value) == "cloud.langfuse.com"++ def test_disabled_config_is_untouched(self, offline: None, no_sockets: None) -> None:+ from headroom.observability.tracing import (+ LangfuseTracingConfig,+ configure_langfuse_tracing,+ )++ assert configure_langfuse_tracing(LangfuseTracingConfig(enabled=False)) is not None+++# ────────── path 4: the Python half of the HuggingFace download ─────────────+++class TestHuggingFaceDownloadOffline:+ """``onnx_runtime.hf_hub_download_local_first`` is the Python twin of the+ Rust Hub fetch this PR guarded, and it was left open — every ONNX model in+ the tree (Kompress, the image router, the memory embedders) resolves+ through it.++ Both halves of the contract are pinned here, because the interesting part+ is what is NOT refused: the guard sits on the network fallback only, so a+ pre-seeded air-gapped cache keeps working. A guard at the top of the+ function would pass a "raises" test and break every air-gapped deployment+ that did the thing we tell operators to do.+ """++ @staticmethod+ def _fake_hub(monkeypatch: pytest.MonkeyPatch, *, cached: str | None) -> list[bool]:+ import huggingface_hub+ from huggingface_hub.errors import LocalEntryNotFoundError++ seen: list[bool] = []++ def fake_download(+ repo_id: str,+ filename: str,+ *,+ revision: str | None = None,+ local_files_only: bool = False,+ ) -> str:+ seen.append(local_files_only)+ if local_files_only and cached is None:+ raise LocalEntryNotFoundError("cold cache")+ return cached or "/downloaded/from/the/hub"++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)+ return seen++ def test_a_cold_cache_is_refused(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.onnx_runtime import hf_hub_download_local_first++ seen = self._fake_hub(monkeypatch, cached=None)+ with pytest.raises(OfflineEgressBlocked):+ hf_hub_download_local_first("acme/model", "model.onnx")+ # The cache lookup ran; the network download never did.+ assert seen == [True]++ def test_a_warm_cache_still_resolves_offline(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.onnx_runtime import hf_hub_download_local_first++ self._fake_hub(monkeypatch, cached="/cache/acme/model.onnx")+ assert hf_hub_download_local_first("acme/model", "model.onnx") == "/cache/acme/model.onnx"++ def test_allow_network_false_still_raises_the_cache_error(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """``allow_network=False`` never reaches the guard, so the caller keeps+ seeing the local-lookup error it already handles."""+ from huggingface_hub.errors import LocalEntryNotFoundError++ from headroom.onnx_runtime import hf_hub_download_local_first++ self._fake_hub(monkeypatch, cached=None)+ with pytest.raises(LocalEntryNotFoundError):+ hf_hub_download_local_first("acme/model", "model.onnx", allow_network=False)+++# ───────────────── path 3: the Rust HuggingFace fetch (parity) ──────────────++_RUST_OFFLINE = REPO_ROOT / "crates" / "headroom-core" / "src" / "offline.rs"+_RUST_HF = REPO_ROOT / "crates" / "headroom-core" / "src" / "tokenizer" / "hf_impl.rs"+++class TestRustOfflineParity:+ """The Rust core reads the same switch from the same process environment.++ The runtime assertion ("``from_pretrained`` returns ``Offline`` and never+ reaches the Hub") lives in ``hf_impl.rs``'s own ``#[cfg(test)]`` module,+ because a socket-level assertion has to run inside the process that would+ open the socket. What pytest can usefully add is the part cargo cannot+ see: that the two halves of one switch still agree.+ """++ def test_rust_guard_exists_and_reads_the_same_env_var(self) -> None:+ source = _RUST_OFFLINE.read_text(encoding="utf-8")+ assert 'pub const OFFLINE_ENV: &str = "HEADROOM_OFFLINE";' in source+ assert "pub fn guard_egress(" in source++ def test_truthy_values_match_the_python_side(self) -> None:+ from headroom.offline import _TRUE_VALUES++ source = _RUST_OFFLINE.read_text(encoding="utf-8")+ match = re.search(r"const TRUE_VALUES: \[&str; \d+\] = \[(.*?)\];", source, re.DOTALL)+ assert match, "TRUE_VALUES not found in crates/headroom-core/src/offline.rs"+ rust_values = set(re.findall(r'"([^"]+)"', match.group(1)))+ assert rust_values == set(_TRUE_VALUES), (+ "HEADROOM_OFFLINE truthiness has drifted between Python and Rust. "+ f"python={sorted(_TRUE_VALUES)} rust={sorted(rust_values)}. A "+ "deployment that reads as offline to one runtime and online to the "+ "other is exactly the hole this switch is supposed to close."+ )++ def test_trim_chars_match_the_python_side(self) -> None:+ """Value parity is only half of it.++ The old pair diffed the accepted token sets and nothing else, so it was+ green while Python used ``str.strip()`` (which strips U+001C-U+001F)+ and Rust used ``str::trim()`` (which does not). Normalisation is part+ of the contract; this pins the set both sides trim.+ """+ from headroom.offline import _TRIM_CHARS++ source = _RUST_OFFLINE.read_text(encoding="utf-8")+ match = re.search(r"const TRIM_CHARS: \[char; \d+\] = \[(.*?)\];", source, re.DOTALL)+ assert match, "TRIM_CHARS not found in crates/headroom-core/src/offline.rs"+ rust_chars = set()+ # One Rust char literal is exactly one character: an escape, or a+ # single non-quote. The `(...)+` this replaces could backtrack+ # exponentially on a long unterminated run (CodeQL py/redos) and was+ # matching something the grammar does not even allow.+ for literal in re.findall(r"'(\\u\{[0-9a-fA-F]{1,6}\}|\\.|[^'\\])'", match.group(1)):+ escape = re.fullmatch(r"\\u\{([0-9a-fA-F]+)\}", literal)+ if escape:+ rust_chars.add(chr(int(escape.group(1), 16)))+ else:+ rust_chars.add({"\\t": "\t", "\\n": "\n", "\\r": "\r"}.get(literal, literal))+ assert rust_chars == set(_TRIM_CHARS), (+ "HEADROOM_OFFLINE trimming has drifted between Python and Rust. "+ f"python={sorted(map(ord, _TRIM_CHARS))} rust={sorted(map(ord, rust_chars))}. "+ "A value that normalises differently in the two runtimes air-gaps "+ "one half of the process and not the other."+ )++ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("1", True),+ (" 1 ", True),+ ("\t1\n", True),+ ("\r\n TRUE \r\n", True),+ ("\x0byes\x0c", True),+ # U+001C-U+001F: whitespace to str.strip(), not to str::trim().+ # This pair is the regression the token-set diff could not see.+ ("\x1c1", False),+ ("1\x1f", False),+ # Unicode spaces: whitespace to str::trim(), and (NBSP) to+ # str.strip() as well. Neither trims them now.+ ("\xa01", False),+ ("\u2007on", False),+ ("", False),+ (" ", False),+ ],+ )+ def test_normalisation_matches_the_rust_side(+ self, monkeypatch: pytest.MonkeyPatch, raw: str, expected: bool+ ) -> None:+ """Same table as ``offline::tests::normalisation_matches_python``.++ Duplicated rather than shared because the point is that two separate+ implementations agree; a shared fixture would only prove one of them+ reads the fixture.+ """+ from headroom.offline import is_offline++ monkeypatch.setenv("HEADROOM_OFFLINE", raw)+ assert is_offline() is expected++ def test_the_rust_normalisation_table_covers_the_same_cases(self) -> None:+ """If one side's table grows a case the other lacks, the pair stops+ being a parity test and becomes two independent tests that happen to+ share a name."""+ source = _RUST_OFFLINE.read_text(encoding="utf-8")+ assert "fn normalisation_matches_python()" in source+ for needle in ('"\\u{1c}1"', '"1\\u{1f}"', '"\\u{a0}1"', '"\\u{2007}on"'):+ assert needle in source, f"rust normalisation table is missing {needle}"++ def test_hf_fetch_guards_before_it_builds_a_client(self) -> None:+ source = _RUST_HF.read_text(encoding="utf-8")+ assert "guard_egress(" in source, "hf_impl.rs does not consult the offline guard"+ guard_at = source.index("guard_egress(")+ api_at = source.index("hf_hub::api::sync::Api::new()")+ assert guard_at < api_at, (+ "the offline guard runs after Api::new(), which already resolves the "+ "Hub endpoint and builds the ureq agent — guard before the client "+ "exists, not before the request"+ )+++# ─────────── the refusal has to survive the fail-open handlers ──────────────+++class TestRefusalSurvivesFailOpenHandlers:+ """Raising was never the hard part; being heard was.++ Under ``HEADROOM_OFFLINE=1`` + ``HEADROOM_KOMPRESS_ENDPOINT``, a full+ ``/v1/messages`` request used to return **200 with the content+ uncompressed** while ``guard_egress`` had fired twice: every fail-open+ ``except Exception`` between the guard and the response logged a warning+ and passed the content through. Each site below is one of those handlers,+ exercised with a compressor that refuses.+ """++ def test_thinking_compactor_does_not_swallow_it(self) -> None:+ """``_memo_compact`` wraps ``kompress.compress(...)`` — the very call+ the in-``compress()`` guard protects — in ``except Exception``."""+ from headroom.transforms.thinking_compactor import _memo_compact++ class _Refusing:+ def compress(self, text: str, allow_download: bool = False) -> object:+ raise OfflineEgressBlocked("remote Kompress inference", "https://k.example.com")++ with pytest.raises(OfflineEgressBlocked):+ _memo_compact("a2 offline probe, unique so the memo cache misses", _Refusing())++ def test_kompress_model_ready_does_not_report_a_refusal_as_ready(self) -> None:+ """``_kompress_model_ready`` answered ``except Exception: return True``+ — reporting a policy refusal as "the model is ready"."""+ from headroom.transforms.content_router import ContentRouter++ class _Stub:+ config = SimpleNamespace(enable_kompress=True)+ _runtime_kompress_model = None+ _kompress_model_ready = ContentRouter._kompress_model_ready++ def _get_kompress(self) -> object:+ raise OfflineEgressBlocked("remote Kompress inference", "https://k.example.com")++ with pytest.raises(OfflineEgressBlocked):+ _Stub()._kompress_model_ready()++ def test_the_router_reaching_for_remote_kompress_propagates(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.transforms.content_router import ContentRouter++ monkeypatch.setenv("HEADROOM_KOMPRESS_ENDPOINT", "https://kompress.example.com")++ class _Stub:+ config = SimpleNamespace(ccr_inject_marker=True)+ _kompress_remote = None+ _get_remote_kompress = ContentRouter._get_remote_kompress++ with pytest.raises(OfflineEgressBlocked):+ _Stub()._get_remote_kompress()++ def test_the_native_detector_fallback_reraises_it(self) -> None:+ """``_detect_content``'s ``except BaseException`` degrades a native+ panic to the pure-Python detector. It re-raises the control-flow+ BaseExceptions; the air-gap refusal is now on that list."""+ from headroom.transforms import content_router++ source = Path(content_router.__file__).read_text(encoding="utf-8")+ assert (+ "except (KeyboardInterrupt, SystemExit, GeneratorExit, OfflineEgressBlocked):" in source+ )+++class TestBackgroundDownloadThreads:+ """The two daemon threads that fetch the Kompress model are the one place+ where propagating is the wrong answer.++ They are background *refreshes*, not the request path, and an unhandled+ ``BaseException`` in a thread reaches ``threading.excepthook`` as a bare+ traceback — on every air-gapped startup with a cold cache. Both handle the+ refusal explicitly and report it with the switch named, which is what+ ``is_offline()``'s "skip an optional refresh" case is for.+ """++ def test_prefetch_reports_the_refusal_and_stops(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch, caplog+ ) -> None:+ import huggingface_hub+ from huggingface_hub.errors import LocalEntryNotFoundError++ from headroom.transforms import kompress_compressor++ attempts: list[str] = []++ def fake_download(repo_id, filename, *, revision=None, local_files_only=False):+ attempts.append(filename)+ raise LocalEntryNotFoundError("cold cache")++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)+ monkeypatch.setattr(kompress_compressor, "_kompress_cache", {})++ with caplog.at_level("WARNING"):+ assert kompress_compressor.prefetch_kompress_artifacts("acme/model") is False+ assert "HEADROOM_OFFLINE" in caplog.text+ # One candidate tried, then it stops: every other candidate would be+ # refused for the same reason.+ assert len(attempts) == 1++ def test_background_download_reports_the_refusal(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch, caplog+ ) -> None:+ from headroom.transforms import kompress_compressor++ def refuse(*args: object, **kwargs: object) -> None:+ raise OfflineEgressBlocked("HuggingFace download of acme/model", "huggingface.co")++ monkeypatch.setattr(kompress_compressor, "_load_kompress", refuse)+ with caplog.at_level("WARNING"):+ kompress_compressor._background_download("acme/model", "cpu")+ assert "refused" in caplog.text+ assert "HEADROOM_OFFLINE" in caplog.text+++class TestModelLoadersDegradeExplicitly:+ """Where a refusal SHOULD become a degradation, it is written down.++ ``OfflineEgressBlocked`` escaping ``except Exception`` is the point — but+ fetching public model weights is not data leaving the box, and failing a+ user's request because an optional compressor could not reach the Hub would+ punish the request for a decision the operator made about the host. Each+ optional model loader therefore translates the refusal into its own+ "model unavailable" error, explicitly, naming the switch in the log. That+ keeps the pre-existing degradation for an air-gapped box with a cold cache,+ and keeps the translation reviewable instead of inherited.+ """++ @staticmethod+ def _cold_hub(monkeypatch: pytest.MonkeyPatch) -> None:+ import huggingface_hub+ from huggingface_hub.errors import LocalEntryNotFoundError++ def fake_download(repo_id, filename, *, revision=None, local_files_only=False):+ raise LocalEntryNotFoundError("cold cache")++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)++ def test_kompress_reports_not_cached_rather_than_a_bare_refusal(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.transforms.kompress_compressor import (+ KompressModelNotCached,+ _hf_artifact,+ )++ self._cold_hub(monkeypatch)+ with pytest.raises(KompressModelNotCached) as excinfo:+ _hf_artifact("acme/model", "model.onnx", allow_network=True)+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)++ def test_the_image_router_degrades_the_same_way_it_always_did(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.image.onnx_router import _hf_artifact++ self._cold_hub(monkeypatch)+ with pytest.raises(RuntimeError) as excinfo:+ _hf_artifact("acme/router", "model_quantized.onnx")+ assert not isinstance(excinfo.value, OfflineEgressBlocked)+ assert "HEADROOM_OFFLINE" in str(excinfo.value)+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)++ def test_the_onnx_candidate_loop_refuses_once_then_checks_the_cache(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch, caplog+ ) -> None:+ """The loader tries several ONNX filenames in turn. A refusal for the+ first says nothing about the rest, so they are still looked up — but+ cache-only, so the refusal is logged once and never retried."""+ import huggingface_hub+ from huggingface_hub.errors import LocalEntryNotFoundError++ from headroom.transforms import kompress_compressor++ attempts: list[tuple[str, bool]] = []++ def fake_download(repo_id, filename, *, revision=None, local_files_only=False):+ attempts.append((filename, local_files_only))+ raise LocalEntryNotFoundError("cold cache")++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)+ with (+ caplog.at_level("WARNING"),+ pytest.raises(kompress_compressor.KompressModelNotCached) as excinfo,+ ):+ kompress_compressor._create_onnx_session("acme/model", [], allow_download=True)+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)+ assert [f for f, _ in attempts] == list(kompress_compressor._onnx_filename_candidates())+ assert all(local for _, local in attempts), "nothing may reach the network path"+ assert caplog.text.count("HEADROOM_OFFLINE forbids fetching it") == 1++ def test_a_cached_fallback_candidate_still_loads_offline(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Devin: the first candidate uncached must not hide a cached second one."""+ import sys++ import huggingface_hub++ from headroom.transforms import kompress_compressor++ first, second = kompress_compressor._onnx_filename_candidates()[:2]++ def fake_download(repo_id, filename, *, revision=None, local_files_only=False):+ if filename == second:+ return f"/cache/{filename}"+ # A plain OSError rather than LocalEntryNotFoundError: conftest+ # turns the latter into a skip, which would hide a regression here.+ raise OSError("cold cache")++ loaded: list[str] = []++ def fake_session(path, *args, **kwargs):+ loaded.append(path)+ return SimpleNamespace(path=path)++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", fake_download)+ monkeypatch.setitem(+ sys.modules, "onnxruntime", SimpleNamespace(InferenceSession=fake_session)+ )+ monkeypatch.setattr(kompress_compressor, "_onnx_session_options", lambda ort: None)+ monkeypatch.setattr(kompress_compressor, "_smoke_run", lambda session: None)++ session = kompress_compressor._create_onnx_session("acme/model", [], allow_download=True)+ assert session.path == f"/cache/{second}"+ assert loaded == [f"/cache/{second}"]++ def test_an_uncached_tokenizer_is_refused_not_fetched(+ self, offline: None, no_sockets: None+ ) -> None:+ """Devin: cached weights plus an uncached ModernBERT tokenizer fell+ through to ``from_pretrained(local_files_only=False)`` unguarded."""+ from headroom.transforms import kompress_compressor++ calls: list[bool] = []++ class _AutoTokenizer:+ @staticmethod+ def from_pretrained(name: str, *, local_files_only: bool, **_kwargs: object) -> object:+ calls.append(local_files_only)+ if local_files_only:+ raise OSError("not cached")+ raise SocketOpened(f"would fetch {name} from the Hub")++ with pytest.raises(kompress_compressor.KompressModelNotCached) as excinfo:+ kompress_compressor._load_modernbert_tokenizer(_AutoTokenizer, allow_download=True)+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)+ assert calls == [True]++ @pytest.mark.parametrize(+ ("loader", "missing", "flag"),+ [+ ("_load_classifier", "tokenizer.json", "_classifier_session"),+ ("_load_siglip", "text_embeddings.npz", "_siglip_session"),+ ],+ )+ def test_the_image_router_is_not_left_half_loaded(+ self,+ offline: None,+ no_sockets: None,+ monkeypatch: pytest.MonkeyPatch,+ loader: str,+ missing: str,+ flag: str,+ ) -> None:+ """Devin: the session doubles as the "loaded" flag, so publishing it+ before a later artifact is refused left a router that never retried."""+ import sys++ from headroom.image import onnx_router++ def fake_artifact(repo: str, filename: str) -> str:+ if filename == missing:+ raise RuntimeError("not cached and HEADROOM_OFFLINE forbids fetching it")+ return f"/cache/{filename}"++ monkeypatch.setattr(onnx_router, "_hf_artifact", fake_artifact)+ monkeypatch.setitem(+ sys.modules, "onnxruntime", SimpleNamespace(InferenceSession=lambda *a, **k: object())+ )+ monkeypatch.setattr(onnx_router, "create_cpu_session_options", lambda *a, **k: None)+ router = onnx_router.OnnxTechniqueRouter()+ with pytest.raises(RuntimeError):+ getattr(router, loader)()+ assert getattr(router, flag) is None++ def test_a_warm_cache_is_unaffected(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """The translation must not fire when nothing was refused."""+ import huggingface_hub++ from headroom.transforms.kompress_compressor import _hf_artifact++ monkeypatch.setattr(+ huggingface_hub,+ "hf_hub_download",+ lambda *a, **k: "/cache/acme/model.onnx",+ )+ assert _hf_artifact("acme/model", "model.onnx", allow_network=True) == (+ "/cache/acme/model.onnx"+ )+++# ───────── Transformers / sentence-transformers / datasets loaders ─────────+#+# Jerrett's review of the chokepoint PR: with HEADROOM_OFFLINE=1 and an+# explicit HF_HUB_OFFLINE=0, ``apply_offline_env`` keeps the operator's value+# (it uses setdefault), huggingface_hub's offline constant stays false even+# with TRANSFORMERS_OFFLINE=1, and the public ``MLModelRegistry.get_siglip()``+# reached two ``from_pretrained`` calls with no ``local_files_only`` and no+# guard. The technique-router loaders and the Kompress PyTorch encoder had the+# same shape. Every test below runs under exactly that configuration, with+# fake loaders and the socket AND DNS entry points booby-trapped, and asserts+# that the only load attempted is the cache-only one.+++def offline_with_hf_override(monkeypatch: pytest.MonkeyPatch) -> None:+ """HEADROOM_OFFLINE=1 with the operator explicitly re-enabling the Hub."""+ from headroom.offline import apply_offline_env++ monkeypatch.setenv("HEADROOM_OFFLINE", "1")+ monkeypatch.setenv("HF_HUB_OFFLINE", "0")+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")+ apply_offline_env()+ # The premise of the review: the explicit override survives, so the+ # HuggingFace env flags are NOT what keeps these loaders off the network.+ assert os.environ["HF_HUB_OFFLINE"] == "0"+++def no_dns(monkeypatch: pytest.MonkeyPatch) -> None:+ """Fail closed on name resolution too: a loader that resolves+ huggingface.co has already decided to dial out, even if the connect is+ later refused by something else."""++ def _getaddrinfo(host: object, *args: object, **kwargs: object) -> object:+ raise SocketOpened(f"DNS lookup of {host!r} attempted")++ monkeypatch.setattr(socket, "getaddrinfo", _getaddrinfo)+++class _FakeHfLoader:+ """A ``from_pretrained``-shaped callable recording every attempt.++ ``cached`` decides the cache-only answer. A non-cache-only attempt is the+ download, so it raises :class:`SocketOpened` — the test fails at the exact+ point a real loader would have reached the Hub.+ """++ def __init__(self, *, cached: bool) -> None:+ self.cached = cached+ self.calls: list[tuple[str, bool]] = []++ def __call__(self, name: str, *, local_files_only: bool = False, **_kwargs: object) -> object:+ self.calls.append((name, local_files_only))+ if local_files_only:+ if self.cached:+ return SimpleNamespace(name=name, eval=lambda: None, to=lambda device: None)+ raise OSError(f"{name} is not in the local cache")+ raise SocketOpened(f"would download {name} from the Hub")++ @property+ def from_pretrained(self) -> _FakeHfLoader:+ return self+++def fake_transformers(monkeypatch: pytest.MonkeyPatch) -> dict[str, _FakeHfLoader]:+ """Replace ``transformers`` with cold-cache fake Auto* classes."""+ import sys++ loaders = {+ name: _FakeHfLoader(cached=False)+ for name in (+ "AutoModel",+ "AutoProcessor",+ "AutoTokenizer",+ "AutoModelForSequenceClassification",+ )+ }+ monkeypatch.setitem(sys.modules, "transformers", SimpleNamespace(**loaders))+ return loaders+++class TestHfLoaderHelper:+ """``onnx_runtime.hf_from_pretrained_local_first`` is the one place the+ order lives: cache-only first, guard_egress on a miss, remote last."""++ def test_a_cold_cache_is_refused_before_any_remote_attempt(+ self, offline_with_hf_override: None, no_sockets: None, no_dns: None+ ) -> None:+ from headroom.onnx_runtime import hf_from_pretrained_local_first++ loader = _FakeHfLoader(cached=False)+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ hf_from_pretrained_local_first(loader, "acme/model", purpose="test model")+ assert loader.calls == [("acme/model", True)]+ assert _refused_hostname(excinfo.value) == "huggingface.co"++ def test_a_warm_cache_loads_offline_without_the_network(+ self, offline_with_hf_override: None, no_sockets: None, no_dns: None+ ) -> None:+ from headroom.onnx_runtime import hf_from_pretrained_local_first++ loader = _FakeHfLoader(cached=True)+ model = hf_from_pretrained_local_first(loader, "acme/model", purpose="test model")+ assert model.name == "acme/model"+ assert loader.calls == [("acme/model", True)]++ def test_online_a_cold_cache_still_downloads(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from headroom.onnx_runtime import hf_from_pretrained_local_first++ monkeypatch.delenv("HEADROOM_OFFLINE", raising=False)+ loader = _FakeHfLoader(cached=False)+ with pytest.raises(SocketOpened):+ hf_from_pretrained_local_first(loader, "acme/model", purpose="test model")+ assert loader.calls == [("acme/model", True), ("acme/model", False)]++ def test_cache_only_mode_re_raises_the_miss(+ self, offline_with_hf_override: None, no_sockets: None, no_dns: None+ ) -> None:+ from headroom.onnx_runtime import hf_from_pretrained_local_first++ loader = _FakeHfLoader(cached=False)+ with pytest.raises(OSError, match="not in the local cache"):+ hf_from_pretrained_local_first(+ loader, "acme/model", purpose="test model", allow_network=False+ )+ assert loader.calls == [("acme/model", True)]++ def test_a_broken_local_directory_is_not_turned_into_a_download(+ self, offline_with_hf_override: None, no_sockets: None, no_dns: None, tmp_path: Path+ ) -> None:+ from headroom.onnx_runtime import hf_from_pretrained_local_first++ loader = _FakeHfLoader(cached=False)+ with pytest.raises(OSError, match="not in the local cache"):+ hf_from_pretrained_local_first(loader, str(tmp_path), purpose="test model")+ assert loader.calls == [(str(tmp_path), True)]+++class TestRegistryLoadersWithExplicitHfOverride:+ """``MLModelRegistry`` is public API; its loaders are what the review+ reproduced against."""++ def test_get_siglip_refuses_legibly(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_transformers: dict[str, _FakeHfLoader],+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ from headroom.models.ml_models import MLModelRegistry, ModelUnavailableOffline++ name = "acme/siglip-cold"+ with caplog.at_level("WARNING"), pytest.raises(ModelUnavailableOffline) as excinfo:+ MLModelRegistry.get_siglip(model_name=name, device="cpu")+ assert isinstance(excinfo.value, RuntimeError), "callers degrade on RuntimeError"+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)+ assert "HEADROOM_OFFLINE" in str(excinfo.value)+ assert "HEADROOM_OFFLINE" in caplog.text+ assert fake_transformers["AutoModel"].calls == [(name, True)]+ assert fake_transformers["AutoProcessor"].calls == []+ assert f"siglip:{name}" not in MLModelRegistry.loaded_models()++ def test_get_siglip_loads_from_a_warm_cache(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_transformers: dict[str, _FakeHfLoader],+ ) -> None:+ from headroom.models.ml_models import MLModelRegistry++ name = "acme/siglip-warm"+ fake_transformers["AutoModel"].cached = True+ fake_transformers["AutoProcessor"].cached = True+ try:+ model, processor = MLModelRegistry.get_siglip(model_name=name, device="cpu")+ assert (model.name, processor.name) == (name, name)+ assert fake_transformers["AutoModel"].calls == [(name, True)]+ assert fake_transformers["AutoProcessor"].calls == [(name, True)]+ finally:+ MLModelRegistry.unload_many([f"siglip:{name}"])++ def test_get_technique_router_refuses_legibly(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_transformers: dict[str, _FakeHfLoader],+ ) -> None:+ from headroom.models.ml_models import MLModelRegistry, ModelUnavailableOffline++ name = "acme/technique-router-cold"+ with pytest.raises(ModelUnavailableOffline) as excinfo:+ MLModelRegistry.get_technique_router(model_path=name, device="cpu")+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)+ assert fake_transformers["AutoTokenizer"].calls == [(name, True)]+ assert fake_transformers["AutoModelForSequenceClassification"].calls == []++ def test_get_technique_router_model_half_is_guarded_too(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_transformers: dict[str, _FakeHfLoader],+ ) -> None:+ """Tokenizer cached, classifier weights not: the second loader must be+ refused on its own, not ride on the first one having succeeded."""+ from headroom.models.ml_models import MLModelRegistry, ModelUnavailableOffline++ name = "acme/technique-router-half"+ fake_transformers["AutoTokenizer"].cached = True+ with pytest.raises(ModelUnavailableOffline):+ MLModelRegistry.get_technique_router(model_path=name, device="cpu")+ assert fake_transformers["AutoModelForSequenceClassification"].calls == [(name, True)]++ def test_get_sentence_transformer_refuses_legibly(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ import sys++ from headroom.models.ml_models import MLModelRegistry, ModelUnavailableOffline++ loader = _FakeHfLoader(cached=False)+ monkeypatch.setitem(+ sys.modules, "sentence_transformers", SimpleNamespace(SentenceTransformer=loader)+ )+ name = "acme/minilm-cold"+ with pytest.raises(ModelUnavailableOffline):+ MLModelRegistry.get_sentence_transformer(name, device="cpu")+ assert loader.calls == [(name, True)]++ def test_the_pytorch_image_router_is_refused_not_fetched(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_transformers: dict[str, _FakeHfLoader],+ ) -> None:+ """The degradation end to end through ``TrainedRouter``: the SigLIP+ load is refused as ``ModelUnavailableOffline`` — a RuntimeError, which+ ``ImageCompressor``'s existing ``except Exception`` turns into+ "preserve the image" — and nothing is downloaded."""+ pytest.importorskip("torch")+ from headroom.image.trained_router import TrainedRouter+ from headroom.models.ml_models import ModelUnavailableOffline++ fake_transformers["AutoTokenizer"].cached = True+ fake_transformers["AutoModelForSequenceClassification"].cached = True+ router = TrainedRouter(model_path="acme/router-warm", use_siglip=True, device="cpu")+ try:+ with pytest.raises(ModelUnavailableOffline):+ router._load_models()+ assert fake_transformers["AutoModel"].calls, "SigLIP was never attempted"+ assert all(local for _, local in fake_transformers["AutoModel"].calls)+ finally:+ router.release_models()+++class TestKompressEncoderWithExplicitHfOverride:+ def test_the_pytorch_encoder_is_refused_not_fetched(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_transformers: dict[str, _FakeHfLoader],+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ """``allow_download=True`` used to become ``local_files_only=False``+ straight away: no cache attempt, no guard."""+ pytest.importorskip("torch")+ from headroom.transforms import kompress_compressor++ model_cls = kompress_compressor._get_model_class()+ with (+ caplog.at_level("WARNING"),+ pytest.raises(kompress_compressor.KompressModelNotCached) as excinfo,+ ):+ model_cls(allow_download=True)+ assert isinstance(excinfo.value.__cause__, OfflineEgressBlocked)+ assert fake_transformers["AutoModel"].calls == [("answerdotai/ModernBERT-base", True)]+ assert "HEADROOM_OFFLINE forbids fetching it" in caplog.text++ def test_the_pytorch_backend_load_degrades_to_not_cached(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ monkeypatch: pytest.MonkeyPatch,+ fake_transformers: dict[str, _FakeHfLoader],+ ) -> None:+ """Through the real backend entry point: KompressModelNotCached is the+ error every caller already maps to the non-ML path."""+ pytest.importorskip("torch")+ from headroom.transforms import kompress_compressor++ monkeypatch.setattr(kompress_compressor, "_kompress_cache", {})+ with pytest.raises(kompress_compressor.KompressModelNotCached):+ kompress_compressor._load_kompress_pytorch(+ "acme/kompress-cold", "cpu", allow_download=True+ )+ assert fake_transformers["AutoModel"].calls+ assert all(local for _, local in fake_transformers["AutoModel"].calls)++ def test_the_tokenizer_under_the_override(+ self, offline_with_hf_override: None, no_sockets: None, no_dns: None+ ) -> None:+ from headroom.transforms import kompress_compressor++ loader = _FakeHfLoader(cached=False)+ with pytest.raises(kompress_compressor.KompressModelNotCached):+ kompress_compressor._load_modernbert_tokenizer(loader, allow_download=True)+ assert loader.calls == [("answerdotai/ModernBERT-base", True)]+++class TestEvalDatasetsWithExplicitHfOverride:+ @pytest.fixture+ def fake_datasets(self, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:+ import sys++ from huggingface_hub import constants as hf_constants++ config = SimpleNamespace(HF_HUB_OFFLINE=False)+ state = SimpleNamespace(cached=False, calls=[], config=config)++ def load_dataset(path: str, *args: object, **kwargs: object) -> object:+ forced = (config.HF_HUB_OFFLINE, hf_constants.HF_HUB_OFFLINE)+ state.calls.append((path, forced))+ if forced == (True, True):+ if state.cached:+ return [{"path": path}]+ raise FileNotFoundError(f"{path} is not in the local cache")+ raise SocketOpened(f"would download dataset {path}")++ monkeypatch.setitem(+ sys.modules, "datasets", SimpleNamespace(load_dataset=load_dataset, config=config)+ )+ monkeypatch.setitem(sys.modules, "datasets.config", config)+ return state++ def test_a_cold_dataset_is_refused(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_datasets: SimpleNamespace,+ ) -> None:+ from huggingface_hub import constants as hf_constants++ from headroom.evals.datasets import load_hf_dataset++ before = hf_constants.HF_HUB_OFFLINE+ with pytest.raises(OfflineEgressBlocked):+ load_hf_dataset("acme/qa", split="test")+ assert fake_datasets.calls == [("acme/qa", (True, True))]+ assert (fake_datasets.config.HF_HUB_OFFLINE, hf_constants.HF_HUB_OFFLINE) == (+ False,+ before,+ ), "the forced-offline constants must be restored"++ def test_a_cached_dataset_still_loads(+ self,+ offline_with_hf_override: None,+ no_sockets: None,+ no_dns: None,+ fake_datasets: SimpleNamespace,+ ) -> None:+ from headroom.evals.datasets import load_hf_dataset++ fake_datasets.cached = True+ assert load_hf_dataset("acme/qa") == [{"path": "acme/qa"}]+ assert fake_datasets.calls == [("acme/qa", (True, True))]+++class TestBroadHandlerSweep:+ """``except Exception`` can no longer swallow the refusal — the type sees+ to that. ``except BaseException`` and bare ``except:`` still can, so they+ are enumerated here and each one has to either re-raise or carry a reason.++ This is the test the brief asked for: "fails if a new broad handler+ swallows it". It is deliberately a whole-tree sweep rather than a list of+ the four handlers that were found, because the four were found by hand and+ the fifth will not be.+ """++ # file -> (line count, reason). Each of these hands the caught exception+ # back to another thread that re-raises it, so the refusal is delayed but+ # never lost.+ _ALLOWED: dict[str, tuple[int, str]] = {+ "tokenizers/huggingface.py": (+ 1,+ "relayed: the handler appends to `error` and the calling thread "+ "re-raises it after join(). Not a swallow, a hand-off.",+ ),+ "tokenizers/tiktoken_counter.py": (+ 1,+ "relayed: stores into box['err'], re-raised in the calling thread.",+ ),+ "transforms/content_router.py": (+ 2,+ "relayed: both are watchdog-thread bodies that store into a box "+ "the caller re-raises from. The third handler in this file, the "+ "native-detect degrade path, re-raises OfflineEgressBlocked "+ "explicitly and so does not appear here.",+ ),+ }++ @staticmethod+ def _broad_handlers() -> dict[str, list[tuple[int, str]]]:+ found: dict[str, list[tuple[int, str]]] = {}+ for path in sorted(PACKAGE_ROOT.rglob("*.py")):+ try:+ source = path.read_text(encoding="utf-8")+ tree = ast.parse(source)+ except (UnicodeDecodeError, SyntaxError): # pragma: no cover - defensive+ continue+ lines = source.splitlines()+ hits: list[tuple[int, str]] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Try):+ continue+ # A sibling handler that catches the refusal first makes every+ # later handler on this try safe.+ sibling_reraises = any(+ handler.type is not None+ and "OfflineEgressBlocked" in ast.unparse(handler.type)+ and any(isinstance(stmt, ast.Raise) for stmt in handler.body)+ for handler in node.handlers+ )+ for handler in node.handlers:+ caught = "" if handler.type is None else ast.unparse(handler.type)+ if handler.type is not None and "BaseException" not in caught:+ continue+ if sibling_reraises:+ continue+ if isinstance(handler.body[-1], ast.Raise):+ continue # unconditional re-raise+ if "OfflineEgressBlocked" in ast.unparse(handler):+ continue # handled explicitly inside+ hits.append((handler.lineno, lines[handler.lineno - 1].strip()))+ if hits:+ found[path.relative_to(PACKAGE_ROOT).as_posix()] = sorted(hits)+ return found++ def test_no_broad_handler_swallows_the_refusal(self) -> None:+ problems: list[str] = []+ found = self._broad_handlers()+ for relpath, hits in found.items():+ entry = self._ALLOWED.get(relpath)+ if entry is None:+ shown = "\n".join(f" line {n}: {text}" for n, text in hits)+ problems.append(f" headroom/{relpath}\n{shown}")+ elif len(hits) != entry[0]:+ shown = "\n".join(f" line {n}: {text}" for n, text in hits)+ problems.append(+ f" headroom/{relpath} — allowed {entry[0]} handler(s), found {len(hits)}"+ f"\n{shown}"+ )+ assert not problems, (+ "A broad `except BaseException:` / bare `except:` can swallow "+ "OfflineEgressBlocked.\n\n"+ + "\n".join(problems)+ + "\n\nOfflineEgressBlocked derives from BaseException so that no "+ "`except Exception:` can degrade an air-gap refusal into 'that "+ "feature stopped working'. A handler that catches BaseException "+ "undoes that. Either:\n"+ " 1. re-raise unconditionally (`raise` as the last statement), or\n"+ " 2. add `except OfflineEgressBlocked: raise` ahead of it, or\n"+ " 3. record it in _ALLOWED here with a written reason."+ )++ def test_allowed_reasons_are_written_out(self) -> None:+ for relpath, (count, reason) in self._ALLOWED.items():+ assert count > 0, relpath+ assert len(reason) >= 40, f"{relpath}: reason is too thin to review"++ def test_allowed_has_no_stale_entries(self) -> None:+ found = self._broad_handlers()+ stale = sorted(set(self._ALLOWED) - set(found))+ assert not stale, f"entries with no broad handler left; delete them: {stale}"+++# ───────────────── startup refuses a contradictory configuration ────────────+++class TestStartupRefusal:+ """An air-gap contradiction is a configuration error, so it is settled at+ startup with the same shape ``_check_rust_core`` uses: say what, say how to+ fix it, exit 78 (``EX_CONFIG``).++ Before this, ``configure_otel_metrics`` was called OUTSIDE the lifespan's+ ``try``, above the line that sets ``app.state.startup_error`` — so the+ refusal escaped as an unhandled error out of ``lifespan`` and took down a+ proxy that had been serving traffic, with a traceback instead of an+ explanation. Only operators who set ``HEADROOM_OTEL_METRICS_ENABLED=1``+ (default off) ever saw it, which is exactly the population that should not+ have to read a stack trace to learn they set two contradictory flags.+ """++ def test_remote_kompress_contradiction_exits_78(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch, capsys+ ) -> None:+ from headroom.proxy import server++ monkeypatch.setenv("HEADROOM_KOMPRESS_ENDPOINT", "https://kompress.example.com")+ with pytest.raises(SystemExit) as excinfo:+ server._preflight_offline_egress()+ assert excinfo.value.code == 78+ message = capsys.readouterr().err+ assert "HEADROOM_KOMPRESS_ENDPOINT" in message+ # Exact host, parsed out of the message, for the same reason as in+ # TestGuardEgress: a substring check would also pass for a URL that+ # merely contains the host somewhere.+ assert _hostnames_in(message) == {"kompress.example.com"}++ def test_otlp_metrics_contradiction_exits_78(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch, capsys+ ) -> None:+ from headroom.proxy import server++ monkeypatch.delenv("HEADROOM_KOMPRESS_ENDPOINT", raising=False)+ monkeypatch.setenv("HEADROOM_OTEL_METRICS_ENABLED", "1")+ with pytest.raises(SystemExit) as excinfo:+ server._configure_observability_or_refuse()+ assert excinfo.value.code == 78+ message = capsys.readouterr().err+ # The operator has to leave with a next action, not just a refusal.+ assert "HEADROOM_OTEL_METRICS_EXPORTER=console" in message++ def test_langfuse_contradiction_exits_78(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch, capsys+ ) -> None:+ from headroom.proxy import server++ monkeypatch.delenv("HEADROOM_KOMPRESS_ENDPOINT", raising=False)+ monkeypatch.delenv("HEADROOM_OTEL_METRICS_ENABLED", raising=False)+ monkeypatch.setenv("HEADROOM_LANGFUSE_ENABLED", "1")+ monkeypatch.setenv("LANGFUSE_PUBLIC_KEY", "pk")+ monkeypatch.setenv("LANGFUSE_SECRET_KEY", "sk")+ with pytest.raises(SystemExit) as excinfo:+ server._configure_observability_or_refuse()+ assert excinfo.value.code == 78+ assert "HEADROOM_LANGFUSE_ENABLED" in capsys.readouterr().err++ def test_an_air_gapped_proxy_with_no_egress_configured_starts(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """The common case must stay a no-op — this is a refusal, not a new+ reason for an air-gapped proxy to fail to boot."""+ from headroom.proxy import server++ for name in (+ "HEADROOM_KOMPRESS_ENDPOINT",+ "HEADROOM_OTEL_METRICS_ENABLED",+ "HEADROOM_LANGFUSE_ENABLED",+ ):+ monkeypatch.delenv(name, raising=False)+ assert server._configure_observability_or_refuse() is None++ def test_the_lifespan_routes_through_the_refusing_wrapper(self) -> None:+ """The defect was one of placement, not of logic: the exporter call sat+ outside the lifespan's own try. Pin that it now goes through the+ wrapper, so a future edit cannot quietly move it back."""+ from headroom.proxy import server++ source = Path(server.__file__).read_text(encoding="utf-8")+ assert "_configure_observability_or_refuse()" in source+ lifespan_at = source.index("async def lifespan(")+ body = source[lifespan_at:]+ assert "configure_otel_metrics(" not in body, (+ "lifespan calls configure_otel_metrics directly again; the "+ "OfflineEgressBlocked it can raise is a BaseException and will "+ "escape uvicorn as an unhandled error"+ )+++# ───── the nine paths the first cut of this PR blessed instead of guarding ───+#+# Each of these was in `_EGRESS_ALLOWLIST` under an `unguarded` reason that+# said, in effect, "yes, this dials the internet with the air-gap switch on,+# and that is out of scope". They are the paths an operator most obviously+# means to stop: an OAuth exchange with github.com, three pollers on a timer,+# two release downloads, a dataset fetch, and two integrations that put the+# caller's prompt content on the wire to a Headroom-operated host.+#+# Every test here traps the socket rather than only asserting "raises", for the+# reason given on the `no_sockets` fixture: a guard placed after the client is+# constructed passes a raises-check and still leaks a connection.+++class TestCopilotAuthOffline:+ """GitHub Copilot device-flow auth and token exchange.++ Four call sites, all funnelling through one `_urlopen` helper. Both layers+ guard: the helper so a fifth call site added later cannot escape, and each+ entry point so the refusal can name the step the operator was trying to+ perform instead of just "authentication".+ """++ def test_device_flow_start_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom import copilot_auth++ with pytest.raises(OfflineEgressBlocked) as excinfo:+ copilot_auth.start_copilot_device_authorization()+ assert _refused_hostname(excinfo.value) == "github.com"++ def test_device_flow_poll_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom import copilot_auth++ with pytest.raises(OfflineEgressBlocked):+ copilot_auth.poll_copilot_device_authorization("device-code")++ def test_token_exchange_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom import copilot_auth++ with pytest.raises(OfflineEgressBlocked) as excinfo:+ copilot_auth.CopilotTokenProvider._exchange_token_sync({"Authorization": "token x"})+ assert "HEADROOM_OFFLINE" in str(excinfo.value)++ def test_user_info_lookup_is_not_swallowed(self, offline: None, no_sockets: None) -> None:+ """`_fetch_copilot_user_info` wraps its request in `except Exception`+ and returns None, which is right for "GitHub is down" and wrong for+ "the operator air-gapped this box": a None here is read as "this token+ is not a Copilot token" and sends the caller down a different path."""+ from headroom import copilot_auth++ with pytest.raises(OfflineEgressBlocked):+ copilot_auth._fetch_copilot_user_info("gho_sometoken")++ def test_the_shared_helper_guards_even_an_unguarded_caller(+ self, offline: None, no_sockets: None+ ) -> None:+ """The backstop, exercised directly: a future fifth call site that+ forgets its own guard still cannot open a socket."""+ from urllib import request as urllib_request++ from headroom import copilot_auth++ with pytest.raises(OfflineEgressBlocked) as excinfo:+ copilot_auth._urlopen(urllib_request.Request("https://api.github.com/x"), timeout=1.0)+ assert _refused_hostname(excinfo.value) == "api.github.com"+++class TestSubscriptionPollersRefuseLegibly:+ """The three subscription pollers.++ These run on a timer inside the proxy, so "refuse" cannot mean "raise".+ An un-caught BaseException out of a background task surfaces as "Task+ exception was never retrieved" at whatever point the GC gets to it — a+ traceback with no explanation and no timestamp anyone can correlate. But it+ also cannot mean "return quietly": a usage panel that silently stops+ updating is the confusion this switch was meant to end.++ So each one catches the refusal specifically, reports it once at WARNING+ with the switch named, and returns its ordinary "no data" value.+ """++ def test_anthropic_poller_returns_none_and_says_why(+ self, offline: None, no_sockets: None, caplog: pytest.LogCaptureFixture+ ) -> None:+ import asyncio++ from headroom.offline import _REPORTED_REFUSALS+ from headroom.subscription.client import SubscriptionClient++ _REPORTED_REFUSALS.clear()+ with caplog.at_level("WARNING"):+ result = asyncio.run(SubscriptionClient().fetch(token="oauth-token"))+ assert result is None+ assert "HEADROOM_OFFLINE" in caplog.text+ assert "subscription" in caplog.text.lower()++ def test_codex_poller_does_not_raise_out_of_its_task(+ self, offline: None, no_sockets: None, caplog: pytest.LogCaptureFixture+ ) -> None:+ import asyncio++ from headroom.offline import _REPORTED_REFUSALS+ from headroom.subscription import codex_rate_limits++ _REPORTED_REFUSALS.clear()+ with caplog.at_level("WARNING"):+ asyncio.run(+ codex_rate_limits._fetch_and_store_usage(+ codex_rate_limits.CODEX_USAGE_URL, {"Authorization": "Bearer x"}+ )+ )+ assert "HEADROOM_OFFLINE" in caplog.text++ def test_codex_poller_is_not_even_scheduled(self, offline: None, no_sockets: None) -> None:+ """Cheap pre-check: an air-gapped proxy should not spawn a doomed task+ on every Codex request just to log the same refusal again."""+ import asyncio++ from headroom.subscription import codex_rate_limits++ async def run() -> bool:+ return codex_rate_limits.maybe_schedule_usage_poll(+ {"authorization": "Bearer x", "chatgpt-account-id": "acct"}+ )++ assert asyncio.run(run()) is False++ def test_copilot_quota_reports_into_its_own_error_slot(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ import asyncio++ from headroom.offline import _REPORTED_REFUSALS+ from headroom.subscription.copilot_quota import _CopilotQuotaTracker++ # A token has to be discoverable or the poller returns before it would+ # ever have dialled, and the test would pass without exercising+ # anything.+ monkeypatch.setenv("GITHUB_TOKEN", "gho_test")+ _REPORTED_REFUSALS.clear()+ tracker = _CopilotQuotaTracker()+ asyncio.run(tracker._maybe_poll())+ assert "HEADROOM_OFFLINE" in (tracker._state.last_error or "")+++class TestDoctorNetworkOffline:+ """`headroom doctor --network` and the TLS-error chain re-probe.++ Both live in ``proxy/tls_diagnostics.py``: a certificate-chain handshake+ plus an HTTP GET against hard-coded provider, HuggingFace and tiktoken+ hosts, and the same chain handshake again on the request path whenever an+ upstream fails TLS verification. Headroom opens every one of those+ connections on its own initiative, so the air-gap switch refuses them.+ """++ def test_endpoint_check_refuses_before_any_connection(+ self, offline: None, no_sockets: None+ ) -> None:+ from headroom.proxy import tls_diagnostics++ with pytest.raises(OfflineEgressBlocked) as caught:+ tls_diagnostics.probe_endpoint(+ "api.anthropic.com", "https://api.anthropic.com/v1/models"+ )+ assert _refused_hostname(caught.value) == "api.anthropic.com"++ def test_doctor_reports_the_network_checks_as_skipped(+ self, offline: None, no_sockets: None+ ) -> None:+ from headroom.cli import doctor++ rows = doctor.network_checks(["https://llm.internal.example/v1"])+ assert [(row.name, row.status) for row in rows] == [("network", doctor.SKIP)]+ assert "HEADROOM_OFFLINE" in rows[0].summary++ def test_chain_probe_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ """Its own ``except Exception`` would hide a trapped connect as an+ ordinary probe error, so assert on the reason, not on "no raise"."""+ from headroom.proxy import tls_diagnostics++ info = tls_diagnostics.probe_presented_chain(+ "api.anthropic.com", use_cache=False, allow_private=True+ )+ assert info.reachable is False+ assert (info.error or "").startswith("skipped: HEADROOM_OFFLINE")++ def test_tls_failure_is_still_explained_without_the_reprobe(+ self, offline: None, no_sockets: None+ ) -> None:+ import ssl++ from headroom.proxy import tls_diagnostics++ exc = ssl.SSLCertVerificationError(1, "certificate verify failed")+ message = tls_diagnostics.describe_upstream_failure(+ exc, "https://offline-reprobe.example/v1/messages"+ )+ assert message is not None+ assert "could not verify the TLS certificate for offline-reprobe.example" in message+++class TestInstallDownloadsOffline:+ """`headroom install`'s two release downloads.++ `binaries.py` already had `HEADROOM_BINARIES_OFFLINE`, which is exactly the+ kind of second, differently-named flag an operator should not have to+ discover after setting an air-gap switch.+ """++ def test_release_binary_download_opens_no_socket(+ self, offline: None, no_sockets: None, tmp_path: Path+ ) -> None:+ from headroom import binaries++ with pytest.raises(OfflineEgressBlocked) as excinfo:+ binaries._download(+ "https://github.com/headroomlabs-ai/headroom/releases/download/v1/x",+ tmp_path / "x",+ progress=False,+ )+ assert _refused_hostname(excinfo.value) == "github.com"++ def test_cbm_download_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom.graph import installer++ with pytest.raises(OfflineEgressBlocked) as excinfo:+ installer.download_cbm()+ assert "HEADROOM_OFFLINE" in str(excinfo.value)++ def test_the_binaries_specific_switch_still_wins_first(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ """Adding the air-gap guard must not change what a user of the narrow+ flag already sees."""+ monkeypatch.delenv("HEADROOM_OFFLINE", raising=False)+ monkeypatch.setenv("HEADROOM_BINARIES_OFFLINE", "1")+ from headroom import binaries++ with pytest.raises(binaries.OfflineError):+ binaries._download("https://example.invalid/x", tmp_path / "x", progress=False)+++class TestEvalDownloadsOffline:+ def test_bfcl_dataset_download_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ from headroom.evals import datasets++ with pytest.raises(OfflineEgressBlocked) as excinfo:+ datasets.load_bfcl(n=1)+ assert _refused_hostname(excinfo.value) == "huggingface.co"+++class TestEvalRunnerLocalProvider:+ """Devin: the before/after runner refused its local Ollama provider."""++ def test_ollama_is_not_refused(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ import sys++ from headroom.evals.runners.before_after import BeforeAfterRunner, LLMConfig++ monkeypatch.setitem(sys.modules, "ollama", SimpleNamespace(Client=lambda: "ollama"))+ runner = BeforeAfterRunner.__new__(BeforeAfterRunner)+ runner.llm_config = LLMConfig(provider="ollama")+ assert runner._init_llm_client() == "ollama"++ def test_a_hosted_provider_is_still_refused(self, offline: None, no_sockets: None) -> None:+ from headroom.evals.runners.before_after import BeforeAfterRunner, LLMConfig++ runner = BeforeAfterRunner.__new__(BeforeAfterRunner)+ runner.llm_config = LLMConfig(provider="openai")+ with pytest.raises(OfflineEgressBlocked):+ runner._init_llm_client()+++class TestHeadroomCloudCompressionOffline:+ """Both Headroom Cloud integrations.++ These are the only paths in the tree that ship the caller's prompt content+ to a Headroom-operated host. "Opt-in by configuration, so an air-gapped+ deployment would not have configured it" was the old reason for leaving+ them open, and it inverts the precedence: an operator who sets an air-gap+ switch is overriding earlier configuration on purpose.+ """++ def test_asgi_middleware_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ import asyncio++ from headroom.integrations.asgi import CompressionMiddleware++ middleware = CompressionMiddleware(app=None, api_key="hdr_test")+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ asyncio.run(middleware._cloud_compress([{"role": "user", "content": "x"}], "m"))+ assert _refused_hostname(excinfo.value) == "api.headroomlabs.ai"++ def test_litellm_callback_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ import asyncio++ from headroom.integrations.litellm_callback import HeadroomCallback++ callback = HeadroomCallback(api_key="hdr_test")+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ asyncio.run(callback._cloud_compress([{"role": "user", "content": "x"}], "m"))+ assert _refused_hostname(excinfo.value) == "api.headroomlabs.ai"+++class TestCloudEmbeddersOffline:+ """The OpenAI embedders in the memory layer.++ Embedding a memory means sending its text to api.openai.com. Configured or+ not, that is Headroom putting the user's data on the wire, which is the+ distinction the whole policy turns on — unlike the Ollama embedder beside+ it, whose address comes from the operator and defaults to loopback.+ """++ def test_openai_embedder_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ pytest.importorskip("openai")+ from headroom.memory.adapters.embedders import OpenAIEmbedder++ embedder = OpenAIEmbedder(api_key="sk-test")+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ _ = embedder._async_client+ assert _refused_hostname(excinfo.value) == "api.openai.com"++ def test_direct_mem0_backend_opens_no_socket(self, offline: None, no_sockets: None) -> None:+ import asyncio++ from headroom.memory.backends.direct_mem0 import DirectMem0Adapter++ adapter = DirectMem0Adapter()+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ asyncio.run(adapter._ensure_initialized())+ assert _refused_hostname(excinfo.value) == "api.openai.com"++ def test_the_ollama_embedder_is_deliberately_untouched(+ self, offline: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """The permitted `operator-endpoint` case, pinned as a behaviour.++ If a later change "tidies up" by guarding every embedder, the on-prem+ embedding setup an air-gapped deployment is most likely to be running+ stops working, and this says so before the customer does.+ """+ pytest.importorskip("httpx")+ import asyncio++ from headroom.memory.adapters.embedders import OllamaEmbedder++ embedder = OllamaEmbedder()+ client = asyncio.run(embedder._get_client())+ assert str(client.base_url).startswith("http://localhost:11434")+++class TestFastembedWeightsOffline:+ """The fastembed relevance model.++ The reason this one stayed open was real: fastembed's constructor has no+ `local_files_only` flag to hang the guard on, so an unconditional guard+ would also refuse a warm, pre-seeded cache — which is precisely the setup+ an air-gapped deployment ships. `_load_text_embedding` makes the split by+ forcing HF_HUB_OFFLINE for a first, cache-only attempt.+ """++ @staticmethod+ def _fake_fastembed(monkeypatch: pytest.MonkeyPatch, *, cached: bool) -> list[str | None]:+ """Install a stub fastembed whose constructor honours HF_HUB_OFFLINE."""+ import sys++ seen: list[str | None] = []++ class _TextEmbedding:+ def __init__(self, **kwargs: object) -> None:+ seen.append(os.environ.get("HF_HUB_OFFLINE"))+ if os.environ.get("HF_HUB_OFFLINE") == "1" and not cached:+ raise OSError("not cached locally")++ monkeypatch.setitem(sys.modules, "fastembed", SimpleNamespace(TextEmbedding=_TextEmbedding))+ return seen++ def test_a_warm_cache_still_loads_offline(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.relevance import embedding++ seen = self._fake_fastembed(monkeypatch, cached=True)+ assert embedding._load_text_embedding({"model_name": "m"}) is not None+ assert seen == ["1"], "the cache-only attempt must force HF_HUB_OFFLINE"++ def test_a_cold_cache_refuses_instead_of_dialling(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from headroom.relevance import embedding++ self._fake_fastembed(monkeypatch, cached=False)+ with pytest.raises(OfflineEgressBlocked) as excinfo:+ embedding._load_text_embedding({"model_name": "m"})+ assert _refused_hostname(excinfo.value) == "huggingface.co"++ def test_the_env_var_is_restored(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setenv("HF_HUB_OFFLINE", "0")+ from headroom.relevance import embedding++ self._fake_fastembed(monkeypatch, cached=True)+ embedding._load_text_embedding({"model_name": "m"})+ assert os.environ["HF_HUB_OFFLINE"] == "0"++ def test_an_already_imported_hub_is_forced_offline_too(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Devin: huggingface_hub reads HF_HUB_OFFLINE once, at import. If it+ was imported while the variable was unset, flipping the env var alone+ leaves the Hub online for the "cache-only" attempt."""+ import sys++ from huggingface_hub import constants as hf_constants++ from headroom.relevance import embedding++ monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)+ monkeypatch.setattr(hf_constants, "HF_HUB_OFFLINE", False)++ class _TextEmbedding:+ def __init__(self, **kwargs: object) -> None:+ if not hf_constants.HF_HUB_OFFLINE:+ raise SocketOpened("cache-only attempt would have reached the Hub")++ monkeypatch.setitem(sys.modules, "fastembed", SimpleNamespace(TextEmbedding=_TextEmbedding))+ assert embedding._load_text_embedding({"model_name": "m"}) is not None+ assert hf_constants.HF_HUB_OFFLINE is False, "the constant must be restored"++ def test_the_scorer_reports_a_model_not_an_air_gap_type(+ self, offline: None, no_sockets: None, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Same translation the Kompress and ONNX loaders do: public weights+ are not data leaving the box, so the caller should hear "this model is+ unavailable, and here is why" rather than a BaseException it has never+ seen."""+ from headroom.relevance.embedding import EmbeddingScorer++ self._fake_fastembed(monkeypatch, cached=False)+ scorer = EmbeddingScorer(model_name="m")+ with pytest.raises(RuntimeError) as excinfo:+ scorer._get_model()+ assert "unavailable" in str(excinfo.value)+ assert "HEADROOM_OFFLINE" in str(excinfo.value)+++class TestCliTranslatesTheRefusal:+ """The refusal has to arrive as a sentence, not a stack trace.++ `OfflineEgressBlocked` is a BaseException so that no `except Exception`+ can downgrade it — which also means Click's own error handling, which+ knows only about ClickException and Abort, would have printed a traceback+ ending in a type the operator has never heard of. One translation at the+ outermost boundary fixes that for every subcommand at once.+ """++ def test_a_refusal_becomes_a_click_error(self, offline: None, no_sockets: None) -> None:+ import click+ from click.testing import CliRunner++ from headroom.cli.main import OfflineAwareGroup++ @click.group(cls=OfflineAwareGroup)+ def cli() -> None:+ pass++ @cli.command()+ def dial() -> None:+ guard_egress("widget sync", "https://widgets.example.com")++ result = CliRunner().invoke(cli, ["dial"])+ assert result.exit_code == 1+ assert result.exception is None or isinstance(result.exception, SystemExit)+ assert "HEADROOM_OFFLINE" in result.output+ assert "widget sync" in result.output+ assert "Traceback" not in result.output++ def test_the_real_cli_group_uses_it(self) -> None:+ from headroom.cli.main import OfflineAwareGroup, main++ assert isinstance(main, OfflineAwareGroup), (+ "headroom.cli.main.main is no longer an OfflineAwareGroup, so an "+ "air-gap refusal reaches the operator as a traceback again"+ )+++# ──────────────────────────────── meta-test ─────────────────────────────────+#+# The per-path tests above only cover the paths we already know about. This+# half is the standing guarantee: a NEW egress path cannot land without either+# calling the guard or being written into the allowlist with a reason.+#+# It decides per **egress site**, not per file. The first cut of this test+# skipped any file whose text contained "guard_egress" anywhere — including in+# a docstring — which made every allowlist count unreachable for guarded files+# and let a second, unguarded client slip into an already-guarded module. The+# scan is therefore built on the AST (so comments and docstrings cannot vouch+# for anything) and a site counts as guarded only when a guard_egress call+# DOMINATES it: same block or an enclosing block, textually earlier, in the+# same function. A guard in a sibling branch, in a nested function, or in an+# except: arm the site does not sit in is not a guard for that site.+++@dataclass(frozen=True)+class _Site:+ """One place that can open an outbound connection."""++ line: int+ text: str+ callee: str+ guarded: bool+++# Callee names, resolved back through the module's imports, that can open a+# connection. Matched against the whole dotted name, so ``self.client.post``+# does not match ``requests.post`` and a local variable named ``urlopen`` does.+#+# "Resolved back through the imports" is load-bearing and was the scanner's+# second blind spot. It matched the text ``ast.unparse`` produced, which is+# whatever local name the module bound — so ``import httpx as h`` followed by+# ``h.Client()`` was invisible, and so was the real case in+# ``headroom/copilot_auth.py``: ``from urllib import request as urllib_request``+# makes every GitHub call render as ``urllib_request.urlopen``, which this+# pattern never matched. A scanner that can be defeated by a rename is a+# scanner that reports what people happened to type. :func:`_canonical_callee`+# rewrites the leading name through the module's own import table first.+_EGRESS_CALLEES = re.compile(+ r"""^(?:+ httpx\.(?:Async)?Client # httpx sync/async client+ | httpx\.(?:get|post|put|patch|delete|head|request|stream) # module-level verbs+ | requests\.(?:get|post|put|patch|delete|head|request|Session)+ | (?:urllib\.request\.)?urlopen | _urlopen # urllib, bare or wrapped+ | aiohttp\.ClientSession+ | urllib3\.PoolManager+ | (?:huggingface_hub\.)?hf_hub_download # the Python half of the HF fetch+ | (?:huggingface_hub\.)?snapshot_download # whole-repo HF fetch+ | (?:[\w.]+\.)?from_pretrained # transformers/tokenizers loaders+ | (?:sentence_transformers\.)?(?:SentenceTransformer|CrossEncoder|SparseEncoder)+ | (?:datasets\.)?load_dataset # HF datasets (eval harness)+ | (?:fastembed\.)?TextEmbedding # fastembed pulls ONNX weights from HF+ | OTLP(?:Metric|Span|Log)Exporter # OTEL export, incl. its background timer+ | (?:openai\.)?(?:Async)?(?:OpenAI|AzureOpenAI) # provider SDKs build their own+ | (?:anthropic\.)?(?:Async)?Anthropic(?:Bedrock|Vertex)?+ )$""",+ re.VERBOSE,+)++# Statement fields that hold a nested block. ``handlers``/``cases`` hold nodes+# that own a block rather than a block, so they are unwrapped separately.+_BLOCK_OWNERS: tuple[type, ...] = (ast.excepthandler,) + (+ (ast.match_case,) if hasattr(ast, "match_case") else ()+)++# A position in the statement tree: one (block identity, index) pair per level+# of nesting. Comparing two of these is how dominance is decided.+_Chain = tuple[tuple[int, int], ...]+++def _child_blocks(node: ast.AST) -> Iterator[list[ast.stmt]]:+ """Yield the statement lists nested directly inside ``node``."""+ for _field, value in ast.iter_fields(node):+ if not isinstance(value, list) or not value:+ continue+ if isinstance(value[0], ast.stmt):+ yield value # type: ignore[misc]+ else:+ for item in value:+ if isinstance(item, _BLOCK_OWNERS):+ yield from _child_blocks(item)+++def _statement_chains(module: ast.Module) -> list[tuple[ast.stmt, _Chain]]:+ """Every statement in the module, paired with its position chain."""+ out: list[tuple[ast.stmt, _Chain]] = []++ def walk(block: list[ast.stmt], prefix: _Chain) -> None:+ for index, statement in enumerate(block):+ chain: _Chain = (*prefix, (id(block), index))+ out.append((statement, chain))+ for nested in _child_blocks(statement):+ walk(nested, chain)++ walk(module.body, ())+ return out+++def _own_expressions(statement: ast.stmt) -> Iterator[ast.AST]:+ """Expression nodes belonging to ``statement`` itself, not to its block.++ Descending into nested statements here would attribute an inner call to+ the outer compound statement and give it the wrong position, which is what+ dominance is computed from.+ """+ stack: list[ast.AST] = []+ for _field, value in ast.iter_fields(statement):+ for item in value if isinstance(value, list) else [value]:+ if isinstance(item, ast.AST) and not isinstance(item, (ast.stmt, *_BLOCK_OWNERS)):+ stack.append(item)+ while stack:+ node = stack.pop()+ yield node+ for child in ast.iter_child_nodes(node):+ if not isinstance(child, (ast.stmt, *_BLOCK_OWNERS)):+ stack.append(child)+++def _dominates(guard: _Chain, site: _Chain) -> bool:+ """True when a guard at ``guard`` always runs before a site at ``site``.++ The guard's own block must be the site's block or an ancestor of it, and+ the guard must come earlier in that block. That rejects, on purpose:++ * a guard inside an ``if``/``except``/nested ``def`` the site is not in —+ the guard's block is not on the site's ancestor chain;+ * a guard that appears later in the same block;+ * a guard anywhere in the file that simply shares a module with the site,+ which is all the first version of this test ever checked.++ It also (conservatively) rejects a guard that lives in a helper the site's+ function calls. That is the intended trade: the guard is cheap, and+ "somebody up the stack probably guards this" is how egress paths get lost.+ """+ if len(guard) > len(site):+ return False+ depth = len(guard) - 1+ if guard[:depth] != site[:depth]:+ return False+ guard_block, guard_index = guard[depth]+ site_block, site_index = site[depth]+ return guard_block == site_block and guard_index < site_index+++def _import_aliases(module: ast.Module) -> dict[str, str]:+ """Map every name the module binds by import to its canonical dotted name.++ Collected from the whole tree, not just module level, because half the+ egress in this package is imported inside the function that uses it+ (``from openai import AsyncOpenAI`` in a property, ``import httpx`` in a+ method). Over-reach — an alias bound in one function applied to a name in+ another — is deliberate: it can only cause the scanner to look at MORE+ call sites, and a false positive here costs one allowlist entry while a+ false negative costs an air-gap guarantee.+ """+ aliases: dict[str, str] = {}+ for node in ast.walk(module):+ if isinstance(node, ast.Import):+ for name in node.names:+ # ``import urllib.request`` binds "urllib"; ``import httpx as h``+ # binds "h" -> "httpx".+ bound = name.asname or name.name.split(".")[0]+ aliases[bound] = name.name if name.asname else bound+ elif isinstance(node, ast.ImportFrom):+ if node.level or not node.module:+ continue # relative import: not a third-party egress client+ for name in node.names:+ if name.name == "*":+ continue+ aliases[name.asname or name.name] = f"{node.module}.{name.name}"+ return aliases+++def _canonical_callee(name: str, aliases: dict[str, str]) -> str:+ """Rewrite a dotted call target through the module's import table."""+ head, _, rest = name.partition(".")+ target = aliases.get(head)+ if target is None:+ return name+ return f"{target}.{rest}" if rest else target+++def _is_egress_call(call: ast.Call, aliases: dict[str, str]) -> str | None:+ """The matched callee name, or None when this call cannot leave the box."""+ try:+ raw = ast.unparse(call.func)+ except Exception: # pragma: no cover - defensive+ return None+ canonical = _canonical_callee(raw, aliases)+ # The canonical name is the one the patterns are written against. The raw+ # name is still tried because a few egress classes are only ever named by+ # their leaf (the OTLP exporters live at a module path far too long and too+ # version-dependent to pin), and those are imported, so canonicalising+ # lengthens rather than normalises them.+ local_files_only = next(+ (keyword.value for keyword in call.keywords if keyword.arg == "local_files_only"),+ None,+ )+ if isinstance(local_files_only, ast.Constant) and local_files_only.value is True:+ # ``local_files_only=True`` is a pure cache lookup for every+ # HuggingFace loader: it raises rather than dialling, so it opens no+ # socket and needs no guard. Counting it would force a guard onto the+ # cache-hit path and break exactly the pre-seeded air-gapped deployment+ # we want to keep working. (The network fallback beside it still+ # counts.) Only the literal ``True`` qualifies: ``not allow_download``+ # is a download whenever the expression is false.+ return None+ if _EGRESS_CALLEES.match(canonical):+ return canonical+ if _EGRESS_CALLEES.match(raw):+ return raw+ if local_files_only is not None:+ # Any call that takes ``local_files_only`` and is not pinned to+ # ``True`` is a HuggingFace loader that can download, whatever the+ # callable is named — including one passed in as a parameter+ # (``loader(name, local_files_only=False)`` inside+ # ``onnx_runtime.hf_from_pretrained_local_first``). A name-based regex+ # alone would never see that indirection.+ return raw+ return None+++def _python_egress_sites(source: str) -> list[_Site]:+ """Every egress site in one Python module, each marked guarded or not."""+ module = ast.parse(source)+ aliases = _import_aliases(module)+ lines = source.splitlines()+ guards: list[_Chain] = []+ candidates: list[tuple[ast.Call, str, _Chain]] = []++ for statement, chain in _statement_chains(module):+ for node in _own_expressions(statement):+ if not isinstance(node, ast.Call):+ continue+ try:+ func_name = ast.unparse(node.func)+ except Exception: # pragma: no cover - defensive+ func_name = ""+ canonical = _canonical_callee(func_name, aliases)+ if "guard_egress" in (func_name.split(".")[-1], canonical.split(".")[-1]):+ guards.append(chain)+ continue+ callee = _is_egress_call(node, aliases)+ if callee is not None:+ candidates.append((node, callee, chain))++ sites: list[_Site] = []+ for node, callee, chain in candidates:+ guarded = any(_dominates(guard, chain) for guard in guards)+ text = lines[node.lineno - 1].strip() if node.lineno <= len(lines) else ""+ sites.append(_Site(line=node.lineno, text=text, callee=callee, guarded=guarded))+ return sorted(sites, key=lambda site: site.line)+++# Every file below has at least one egress site that does NOT call+# guard_egress. There are exactly five reasons that can be true and still be+# correct, and the category prefix has to be one of them:+#+# loopback talks only to 127.0.0.1 / the operator's own local proxy.+# It never leaves the box, so the air-gap switch has+# nothing to protect.+# gated an is_offline() check upstream makes this code+# unreachable, so the connection is never built. Routing it+# through guard_egress as well would be redundant.+# user-traffic the caller's own request being forwarded to the upstream+# the operator configured — the proxy's actual job, and+# the reason an air-gapped deployment runs one at all.+# operator-endpoint Headroom dialling an address that comes entirely from+# operator configuration and defaults to loopback. Exactly+# one thing qualifies today (the Ollama embedder). A+# hard-coded internet host may never hide behind this.+# cache-only the call provably cannot reach the network because the+# surrounding code forces the HuggingFace stack offline for+# its duration; the network fallback beside it IS guarded.+#+# There is deliberately NO "known violation" category. The first version of+# this allowlist had one — `unguarded`, "out of scope for A-2" — and it held+# nine files including Copilot auth, three subscription pollers, the release+# binary and codebase-memory-mcp downloads, the eval dataset fetch and both+# Headroom Cloud compression integrations. Recording that a switch does not do+# what it says is not the same as making it do it, and an allowlist that can+# absorb a violation stops being a list of exceptions and becomes a list of+# bugs nobody has to fix. Those nine are now guarded; the category is gone;+# `test_no_category_permits_a_known_violation` keeps it gone.+#+# Value is (number of UNGUARDED egress sites in the file, reason). Guarded+# sites are not counted and do not need an entry, so a file can legitimately+# appear here and still route some of its egress through the chokepoint. The+# count is part of the assertion: adding a second unguarded client to a listed+# file trips this test, and so does adding one to a file that is fully guarded+# today — that file simply has no entry, so the new site is unallowlisted.+# The complete set of reasons an egress site may skip the guard. Pinned by+# `test_no_category_permits_a_known_violation`; see the comment above.+_PERMITTED_CATEGORIES = frozenset(+ {"loopback", "gated", "user-traffic", "operator-endpoint", "cache-only"}+)++_EGRESS_ALLOWLIST: dict[str, tuple[int, str]] = {+ "proxy/server.py": (+ 2,+ "user-traffic: the proxy forwarding the caller's request to the "+ "upstream they configured. Blocking this would break every air-gapped "+ "deployment that points Headroom at an on-prem model endpoint, which "+ "is the main reason such a deployment exists.",+ ),+ "update_check.py": (+ 1,+ "gated: is_update_check_enabled() returns False when is_offline(), so "+ "the request is never built. See headroom/update_check.py.",+ ),+ "telemetry/session.py": (+ 1,+ "gated: the beacon upload is reached only via is_telemetry_enabled(), "+ "which returns False when is_offline(). See headroom/telemetry/beacon.py.",+ ),+ "telemetry/reporter.py": (+ 1,+ "gated: UsageReporter is only constructed and started when "+ "`not (config.offline or is_offline())` — see the license-key branch "+ "in headroom/proxy/server.py.",+ ),+ "install/health.py": (+ 1,+ "loopback: readiness/health probes against the operator's own proxy "+ "URL, used by the installers and `headroom doctor`.",+ ),+ "cli/wrap.py": (+ 2,+ "loopback: both sites are hard-coded http://127.0.0.1:<port> calls to "+ "the locally running proxy (/health and /admin/runtime-env).",+ ),+ "cli/learn.py": (+ 1,+ "loopback: hard-coded http://127.0.0.1:<port>/admin/runtime-env on the local proxy.",+ ),+ "cli/mcp.py": (+ 1,+ "loopback: `headroom mcp status` probing <proxy_url>/health, which is "+ "the operator's own local proxy (defaults to 127.0.0.1:8787).",+ ),+ "providers/copilot/wrap.py": (+ 1,+ "loopback: hard-coded http://127.0.0.1:<port>/health on the local proxy.",+ ),+ "testing/harness.py": (+ 1,+ "loopback: the test harness waiting for its own subprocess proxy on "+ "127.0.0.1 to become ready. Test-only code.",+ ),+ "ccr/mcp_server.py": (+ 3,+ "loopback: retrieval and liveness calls against the operator's local "+ "proxy_url (defaults to 127.0.0.1). The MCP server is a sidecar to the "+ "proxy, not an internet client.",+ ),+ "memory/adapters/embedders.py": (+ 1,+ "operator-endpoint: OllamaEmbedder against the base_url the operator "+ "configured, defaulting to http://localhost:11434. Headroom ships no "+ "internet host for this path, and refusing it would break the on-prem "+ "embedding setup an air-gapped deployment is most likely to run. The "+ "OpenAI embedder in the same file reaches api.openai.com and IS "+ "guarded; so are the HuggingFace fetches, via "+ "onnx_runtime.hf_hub_download_local_first.",+ ),+ "evals/datasets.py": (+ 1,+ "cache-only: the first load_dataset in load_hf_dataset runs only "+ "under is_offline(), with datasets.config.HF_HUB_OFFLINE and "+ "huggingface_hub's HF_HUB_OFFLINE constant both forced to True for "+ "its duration, so a pre-seeded eval dataset loads from the cache and a "+ "cold one raises without opening a socket. The network load below it "+ "calls guard_egress first.",+ ),+ "relevance/embedding.py": (+ 1,+ "cache-only: the first of the two fastembed loads in "+ "_load_text_embedding runs with HF_HUB_OFFLINE forced to 1, so "+ "huggingface_hub resolves from the local cache or raises without "+ "opening a socket. The network retry directly below it calls "+ "guard_egress, which is why a pre-seeded air-gapped host still loads "+ "the model and a cold one refuses instead of dialling.",+ ),+}+++def _python_sites_by_file() -> dict[str, list[_Site]]:+ """Map ``headroom/``-relative path -> egress sites, guarded or not."""+ found: dict[str, list[_Site]] = {}+ for path in sorted(PACKAGE_ROOT.rglob("*.py")):+ try:+ source = path.read_text(encoding="utf-8")+ except UnicodeDecodeError: # pragma: no cover - defensive+ continue+ try:+ sites = _python_egress_sites(source)+ except SyntaxError: # pragma: no cover - defensive+ continue+ if sites:+ found[path.relative_to(PACKAGE_ROOT).as_posix()] = sites+ return found+++def _unguarded_by_file() -> dict[str, list[_Site]]:+ out = {}+ for relpath, sites in _python_sites_by_file().items():+ unguarded = [site for site in sites if not site.guarded]+ if unguarded:+ out[relpath] = unguarded+ return out+++def _render(relpath: str, sites: list[_Site], *, root: str = "headroom") -> str:+ shown = "\n".join(f" line {site.line}: {site.text}" for site in sites)+ return f" {root}/{relpath}\n{shown}"+++_RESOLUTIONS = (+ "\n\nHEADROOM_OFFLINE=1 is documented as an air-gap switch, so every path "+ "that opens a connection must either:\n"+ " 1. call guard_egress(purpose, destination) BEFORE the client is "+ "constructed, in a position that dominates the call site (same block or "+ "an enclosing one, earlier in that block), or\n"+ " 2. be added to the allowlist in this file with a written reason under "+ "one of the five permitted categories (loopback / gated / user-traffic / "+ "operator-endpoint / cache-only) and the number of UNGUARDED egress sites "+ "in the file. There is no category for 'known violation': if the path can "+ "dial the internet under HEADROOM_OFFLINE, it is a bug, not an entry.\n"+ "Do not silence this by widening the regex, and do not rely on a guard "+ "somewhere else in the same file — it has to dominate the site."+)+++class TestEgressChokepointCoverage:+ """Fails when someone adds an outbound client that nothing checked.++ The failure message names the file and the exact lines, and tells the+ author the two acceptable resolutions, so the test is a code-review aid+ rather than a puzzle.+ """++ def test_every_egress_site_is_guarded_or_allowlisted(self) -> None:+ problems: list[str] = []+ unguarded = _unguarded_by_file()+ for relpath, sites in unguarded.items():+ entry = _EGRESS_ALLOWLIST.get(relpath)+ if entry is None:+ problems.append(+ _render(relpath, sites) + "\n (not guarded, not allowlisted)"+ )+ continue+ expected, _reason = entry+ if len(sites) != expected:+ problems.append(+ _render(relpath, sites)+ + f"\n (allowlist records {expected} unguarded egress "+ f"site(s), found {len(sites)})"+ )++ assert not problems, (+ "New or changed outbound egress found in headroom/.\n\n"+ + "\n".join(problems)+ + _RESOLUTIONS+ )++ def test_allowlist_has_no_stale_entries(self) -> None:+ """A stale entry is worse than a missing one: it reads as a reviewed+ decision about code that no longer exists, and it hides the next real+ addition to that file behind a count that was never re-checked."""+ unguarded = _unguarded_by_file()+ stale = sorted(set(_EGRESS_ALLOWLIST) - set(unguarded))+ assert not stale, (+ "allowlist entries no longer have any UNGUARDED egress site; "+ f"delete them (or they were just fixed — delete them anyway): {stale}"+ )++ def test_allowlist_reasons_are_written_out(self) -> None:+ """Guards the guard: an entry with an empty or placeholder reason is an+ exemption nobody justified."""+ for relpath, (count, reason) in _EGRESS_ALLOWLIST.items():+ assert count > 0, f"{relpath}: egress-site count must be positive"+ assert len(reason) >= 40, f"{relpath}: allowlist reason is too thin to review"+ assert reason.split(":")[0] in _PERMITTED_CATEGORIES, (+ f"{relpath}: reason must start with one of the permitted "+ f"categories {sorted(_PERMITTED_CATEGORIES)}, got {reason!r}"+ )++ def test_no_category_permits_a_known_violation(self) -> None:+ """The category list itself is the thing under review here.++ The first version of this allowlist carried an `unguarded` category+ meaning "yes, this really does dial the internet under+ HEADROOM_OFFLINE, and we are writing that down instead of fixing it".+ Nine files sat in it, including GitHub Copilot auth, three subscription+ pollers, two binary downloads and both Headroom Cloud compression+ integrations — the Headroom-initiated traffic an operator sets an+ air-gap switch specifically to stop.++ A table that can absorb a violation turns a policy into a changelog.+ So the permitted categories are pinned by name: each of the five states+ a reason the connection is either impossible or is not Headroom phoning+ home, and adding a sixth that means "we know, and we left it" has to be+ a deliberate edit to this test with a reviewer looking at it.+ """+ assert _PERMITTED_CATEGORIES == {+ "loopback",+ "gated",+ "user-traffic",+ "operator-endpoint",+ "cache-only",+ }, (+ "the permitted allowlist categories changed. Every one of them has "+ "to mean 'this connection cannot leave the box' or 'this is not "+ "Headroom-initiated traffic'. A category that means 'reachable "+ "under HEADROOM_OFFLINE, out of scope' is what this test exists to "+ "refuse — guard the path instead."+ )+ for relpath, (_count, reason) in _EGRESS_ALLOWLIST.items():+ assert "out of scope" not in reason.lower(), (+ f"{relpath}: 'out of scope' is not a reason an operator can "+ "act on. Guard the path or state which permitted category "+ "makes the connection legitimate."+ )++ def test_the_guarded_paths_are_actually_seen_as_guarded(self) -> None:+ """The scanner has to recognise the guards this PR added, or "no+ unguarded sites" would be a vacuous pass for those files."""+ sites = _python_sites_by_file()+ for relpath in (+ "transforms/kompress_remote.py",+ "observability/metrics.py",+ "onnx_runtime.py",+ "tokenizers/huggingface.py",+ "evals/datasets.py",+ ):+ assert relpath in sites, f"{relpath} has no detected egress site at all"+ assert any(site.guarded for site in sites[relpath]), (+ f"{relpath} routes through guard_egress but the scanner does not "+ "see any site as guarded — the dominance check has drifted"+ )+++# ───────────────── the meta-test's own dominance rules ──────────────────────+++class TestSiteScannerRules:+ """Tests for the scanner itself.++ The defect this replaces was not a missing rule, it was a rule that never+ ran: a file-wide ``"guard_egress" in source`` check meant the word in a+ docstring exempted the whole module. A meta-test nobody tests is just a+ comment, so each bypass that was demonstrated against the old version is+ pinned here.+ """++ def test_a_guard_in_a_docstring_guards_nothing(self) -> None:+ source = '"""This module would call guard_egress if it were real."""\nimport httpx\nc = httpx.Client()\n'+ sites = _python_egress_sites(source)+ assert [site.guarded for site in sites] == [False]++ def test_a_second_client_in_a_guarded_file_is_unguarded(self) -> None:+ source = (+ "def one():\n"+ " guard_egress('a', 'b')\n"+ " return httpx.Client()\n"+ "\n"+ "def two():\n"+ " return httpx.Client()\n"+ )+ sites = _python_egress_sites(source)+ assert [site.guarded for site in sites] == [True, False]++ def test_a_guard_in_a_sibling_branch_does_not_count(self) -> None:+ source = (+ "def f(flag):\n"+ " if flag:\n"+ " guard_egress('a', 'b')\n"+ " return httpx.Client()\n"+ )+ assert [site.guarded for site in _python_egress_sites(source)] == [False]++ def test_a_guard_in_an_enclosing_block_does_count(self) -> None:+ source = (+ "def f(flag):\n"+ " guard_egress('a', 'b')\n"+ " if flag:\n"+ " with open('x') as fh:\n"+ " return httpx.Client()\n"+ )+ assert [site.guarded for site in _python_egress_sites(source)] == [True]++ def test_a_guard_in_a_nested_function_does_not_count(self) -> None:+ source = (+ "def f():\n"+ " def inner():\n"+ " guard_egress('a', 'b')\n"+ " return httpx.Client()\n"+ )+ assert [site.guarded for site in _python_egress_sites(source)] == [False]++ def test_a_guard_after_the_site_does_not_count(self) -> None:+ source = "def f():\n c = httpx.Client()\n guard_egress('a', 'b')\n return c\n"+ assert [site.guarded for site in _python_egress_sites(source)] == [False]++ def test_a_one_line_def_is_not_invisible(self) -> None:+ """The previous scanner skipped any line starting with ``def``/``async+ def`` to avoid counting a ``def _urlopen(...)`` wrapper, which also hid+ every egress packed onto a one-line body."""+ source = "def f(): return httpx.Client().post('https://x')\n"+ assert [site.guarded for site in _python_egress_sites(source)] == [False]++ def test_a_urlopen_wrapper_definition_is_still_not_a_call_site(self) -> None:+ source = "def _urlopen(url):\n return urllib.request.urlopen(url)\n"+ sites = _python_egress_sites(source)+ assert [site.callee for site in sites] == ["urllib.request.urlopen"]++ def test_a_commented_out_client_is_not_a_site(self) -> None:+ source = "# c = httpx.Client()\nx = 1\n"+ assert _python_egress_sites(source) == []++ def test_a_cache_only_hf_download_is_not_a_site(self) -> None:+ source = (+ "def f():\n"+ " a = hf_hub_download(r, f, local_files_only=True)\n"+ " return hf_hub_download(r, f)\n"+ )+ sites = _python_egress_sites(source)+ assert [site.line for site in sites] == [3]++ def test_transformers_from_pretrained_is_a_site(self) -> None:+ source = (+ "from transformers import AutoModel\n"+ "def f(name):\n"+ " return AutoModel.from_pretrained(name)\n"+ )+ assert [site.callee for site in _python_egress_sites(source)] == [+ "transformers.AutoModel.from_pretrained"+ ]++ def test_a_cache_only_from_pretrained_is_not_a_site(self) -> None:+ source = (+ "def f(name):\n return AutoProcessor.from_pretrained(name, local_files_only=True)\n"+ )+ assert _python_egress_sites(source) == []++ def test_a_computed_local_files_only_is_still_a_site(self) -> None:+ """``local_files_only=not allow_download`` is a download whenever the+ expression is false — the Kompress encoder's exact unguarded shape."""+ source = (+ "def f(name, allow_download):\n"+ " return AutoModel.from_pretrained(name, local_files_only=not allow_download)\n"+ )+ assert [site.guarded for site in _python_egress_sites(source)] == [False]++ def test_an_indirect_loader_is_caught_by_its_keyword(self) -> None:+ """A loader passed in as a parameter has no recognisable name; taking+ ``local_files_only`` at all is what marks it as a HuggingFace load."""+ source = (+ "def f(loader, name):\n"+ " loader(name, local_files_only=True)\n"+ " return loader(name, local_files_only=False)\n"+ )+ sites = _python_egress_sites(source)+ assert [(site.line, site.guarded) for site in sites] == [(3, False)]++ def test_a_guarded_remote_fallback_counts_as_guarded(self) -> None:+ source = (+ "def f(loader, name):\n"+ " try:\n"+ " return loader(name, local_files_only=True)\n"+ " except OSError:\n"+ " pass\n"+ " guard_egress('model', 'huggingface.co')\n"+ " return loader(name, local_files_only=False)\n"+ )+ assert [site.guarded for site in _python_egress_sites(source)] == [True]++ @pytest.mark.parametrize(+ "call",+ [+ "SentenceTransformer(name, device='cpu')",+ "snapshot_download(name)",+ "load_dataset(name, split='test')",+ "AutoTokenizer.from_pretrained(name, trust_remote_code=False)",+ ],+ )+ def test_other_hf_download_apis_are_sites(self, call: str) -> None:+ source = f"def f(name):\n return {call}\n"+ assert [site.guarded for site in _python_egress_sites(source)] == [False]++ def test_a_method_named_post_is_not_requests_post(self) -> None:+ source = "def f(self):\n return self.client.post('/x')\n"+ assert _python_egress_sites(source) == []++ def test_an_aliased_module_import_is_not_invisible(self) -> None:+ """``import httpx as h`` used to defeat the scanner completely.++ It matched the text ``ast.unparse`` produced, which is the local name,+ so a one-word rename hid an outbound client from a test whose entire+ job is to notice outbound clients.+ """+ source = "import httpx as h\n\ndef f():\n return h.Client()\n"+ sites = _python_egress_sites(source)+ assert [site.callee for site in sites] == ["httpx.Client"]++ def test_an_aliased_from_import_is_not_invisible(self) -> None:+ """The real instance of the bug, from headroom/copilot_auth.py:+ ``from urllib import request as urllib_request`` makes every GitHub+ call in that module render as ``urllib_request.urlopen``, which the+ pattern never matched — so four Copilot auth call sites and the shared+ helper underneath them were all invisible."""+ source = (+ "from urllib import request as urllib_request\n"+ "\n"+ "def f(req):\n"+ " return urllib_request.urlopen(req)\n"+ )+ sites = _python_egress_sites(source)+ assert [site.callee for site in sites] == ["urllib.request.urlopen"]++ def test_an_aliased_class_import_is_not_invisible(self) -> None:+ source = "from openai import AsyncOpenAI as AO\n\ndef f():\n return AO()\n"+ sites = _python_egress_sites(source)+ assert [site.callee for site in sites] == ["openai.AsyncOpenAI"]++ def test_an_alias_bound_inside_a_function_still_resolves(self) -> None:+ """Half the egress in this package is imported inside the function+ that uses it, so import collection cannot stop at module level."""+ source = "def f():\n import httpx as h\n\n return h.AsyncClient()\n"+ sites = _python_egress_sites(source)+ assert [site.callee for site in sites] == ["httpx.AsyncClient"]++ def test_an_aliased_guard_still_counts_as_a_guard(self) -> None:+ """The rename defence has to cut both ways, or the fix for the blind+ spot becomes a new false positive."""+ source = (+ "import httpx\n"+ "from headroom.offline import guard_egress as ge\n"+ "\n"+ "def f():\n"+ " ge('a', 'b')\n"+ " return httpx.Client()\n"+ )+ assert [site.guarded for site in _python_egress_sites(source)] == [True]++ def test_canonicalisation_does_not_invent_an_alias(self) -> None:+ """Only names the module actually bound by import are rewritten.++ Without that constraint the rewrite would be a guess, and a guess that+ turns arbitrary locals into egress sites makes the allowlist grow for+ no reason — which is how a tripwire stops being read.+ """+ source = "def f(h):\n return h.Client()\n"+ assert _python_egress_sites(source) == []++ def test_module_level_httpx_verbs_are_sites(self) -> None:+ source = "def f():\n return httpx.get('https://x')\n"+ assert [site.callee for site in _python_egress_sites(source)] == ["httpx.get"]+++# ───────────────── the documented claim vs the actual guarantee ─────────────++_AIR_GAP_DOCS = (+ "docs/metrics-technical-guide.md",+ "docs/content/docs/proxy.mdx",+ # Not a doc, but the same promise made to the same reader: the startup+ # banner an operator sees when they turn the switch on.+ "headroom/proxy/server.py",+)++# Phrases that promise a whole-process egress kill switch with no exceptions.+# The switch has four stated exceptions (see _EGRESS_ALLOWLIST), all of them+# either physically incapable of leaving the box or not Headroom-initiated, so+# these sentences are still wrong — an operator who reads one and skips the+# firewall rule has been told the wrong thing about forwarded upstream traffic.+_OVERCLAIMS = (+ "disables all outbound traffic",+ "disables all egress",+ "blocks all outbound",+ "hard-disable **all** egress",+ "hard-disables all egress",+ "no outbound traffic at all",+ "all outbound egress disabled",+)++# What an operator has to be told instead of the sentence above: which traffic+# survives the switch. Each doc must name the exceptions, not just the switch.+_REQUIRED_POLICY_TERMS = ("HEADROOM_OFFLINE", "upstream")+++class TestDocsMatchTheGuarantee:+ """The docs and the allowlist have to agree about what the switch does.++ The change that introduced the chokepoint also strengthened+ `docs/metrics-technical-guide.md` to say `HEADROOM_OFFLINE=1` "disables all+ outbound traffic" — while its own allowlist recorded nine paths as+ reachable anyway, plus two Rust downloads and the Python HuggingFace fetch.+ Those nine are now guarded, but the sentence is *still* wrong, for a+ smaller and more permanent reason: the proxy goes on forwarding the+ caller's own requests to the operator's configured upstream, because that+ is what a proxy is. "All outbound traffic" is not a promise this switch can+ keep without ceasing to be a proxy.++ So this test has two halves. No doc may make the absolute claim, and every+ doc must state the exception that replaces it — otherwise the cheap way to+ pass the first half is to say nothing at all, which leaves the operator+ exactly as misinformed and with less to read.+ """++ def test_no_doc_makes_the_absolute_claim(self) -> None:+ for relative in _AIR_GAP_DOCS:+ text = (REPO_ROOT / relative).read_text(encoding="utf-8")+ for claim in _OVERCLAIMS:+ assert claim not in text, (+ f"{relative} says {claim!r}. HEADROOM_OFFLINE refuses every "+ "Headroom-initiated connection, but the proxy still "+ "forwards the caller's own requests to the operator's "+ "configured upstream — state that exception instead of "+ "making a promise the switch cannot keep."+ )++ def test_every_doc_states_the_exception(self) -> None:+ """The cheap way to pass the test above is to delete the paragraph."""+ for relative in _AIR_GAP_DOCS:+ text = (REPO_ROOT / relative).read_text(encoding="utf-8")+ for term in _REQUIRED_POLICY_TERMS:+ assert term in text, (+ f"{relative} no longer states the {term!r} half of the "+ "offline policy. An operator needs both what the switch "+ "refuses and what it deliberately still allows."+ )+++# ─────────────────────── the Rust half of the same sweep ────────────────────+#+# `crates/` was outside the Python scan entirely, which is how two Rust+# downloads (the Kompress model and the fastembed weights) sat unguarded in the+# same PR that guarded the Rust tokenizer for exactly the stated reason. This+# is a text scan, not an AST one: there is no Rust parser here, so "guarded"+# means a guard_egress call earlier in the same `fn` at no deeper indentation.+# Weaker than the Python dominance check, and deliberately so — it is a+# review-time tripwire for a new egress path, and the runtime assertions live+# in each crate's own `#[test]`s.++_RUST_EGRESS_PATTERNS = re.compile(+ r"""+ hf_hub::api::(?:sync|tokio)::Api(?:Builder)?::new\(+ | (?<![\w:])Api(?:Builder)?::new\(+ | (?<![\w:])TextEmbedding::try_new\w*\(+ | (?<![\w:])reqwest::(?:Client::(?:new|builder)|get|post)\(+ | (?<![\w:])ureq::(?:agent|builder|get|post|put|delete|request)\(+ """,+ re.VERBOSE,+)++_RUST_FN = re.compile(+ r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:default\s+)?(?:const\s+)?"+ r"(?:async\s+)?(?:unsafe\s+)?(?:extern\s+\"[^\"]*\"\s+)?fn\s+\w"+)++_RUST_ALLOWLIST: dict[str, tuple[int, str]] = {+ "headroom-proxy/src/proxy.rs": (+ 1,+ "user-traffic: the reqwest client the Rust proxy forwards the caller's "+ "own request through, the exact counterpart of the Python proxy's "+ "allowlist entry. An air-gapped deployment points it at an on-prem "+ "endpoint and still needs it to work.",+ ),+}+++def _rust_egress_sites() -> dict[str, list[_Site]]:+ """Map ``crates/``-relative path -> egress sites, guarded or not."""+ crates_root = REPO_ROOT / "crates"+ found: dict[str, list[_Site]] = {}+ for path in sorted(crates_root.glob("*/src/**/*.rs")):+ lines = path.read_text(encoding="utf-8").splitlines()+ # Everything from the module-level `#[cfg(test)] mod tests` on is test+ # code: it is expected to build clients, and it never ships. Match the+ # `mod` too — a bare `#[cfg(test)]` also decorates test-only `use`+ # lines near the top of a file, and truncating there would blind the+ # sweep to the entire module (it did, for headroom-proxy/src/proxy.rs).+ for index, line in enumerate(lines):+ if line.rstrip() != "#[cfg(test)]":+ continue+ following = next((nxt for nxt in lines[index + 1 :] if nxt.strip()), "")+ if following.lstrip().startswith("mod "):+ lines = lines[:index]+ break+ sites: list[_Site] = []+ for number, line in enumerate(lines, start=1):+ stripped = line.strip()+ if stripped.startswith(("//", "*", "#[")):+ continue+ match = _RUST_EGRESS_PATTERNS.search(line)+ if not match:+ continue+ start = _enclosing_rust_fn(lines, number)+ if start is None:+ continue+ body = lines[start : number - 1]+ indent = len(line) - len(line.lstrip())+ guarded = any(+ "guard_egress(" in candidate+ and (len(candidate) - len(candidate.lstrip())) <= indent+ for candidate in body+ )+ sites.append(_Site(line=number, text=stripped, callee=match.group(0), guarded=guarded))+ if sites:+ found[path.relative_to(crates_root).as_posix()] = sites+ return found+++def _enclosing_rust_fn(lines: list[str], number: int) -> int | None:+ """Index of the line after the `fn` header enclosing line ``number``.++ None when the site is inside a `#[test]`/`#[cfg(test)]` function, which the+ sweep ignores, or when no `fn` header precedes it at all.+ """+ for index in range(number - 1, -1, -1):+ if not _RUST_FN.match(lines[index]):+ continue+ attributes = "\n".join(lines[max(0, index - 5) : index])+ if "#[test]" in attributes or "#[tokio::test]" in attributes:+ return None+ if "#[cfg(test)]" in attributes:+ return None+ return index + 1+ return None+++class TestRustEgressChokepointCoverage:+ def test_every_rust_egress_site_is_guarded_or_allowlisted(self) -> None:+ problems: list[str] = []+ unguarded = {+ relpath: [site for site in sites if not site.guarded]+ for relpath, sites in _rust_egress_sites().items()+ }+ unguarded = {relpath: sites for relpath, sites in unguarded.items() if sites}+ for relpath, sites in unguarded.items():+ entry = _RUST_ALLOWLIST.get(relpath)+ if entry is None:+ problems.append(+ _render(relpath, sites, root="crates")+ + "\n (not guarded, not allowlisted)"+ )+ continue+ expected, _reason = entry+ if len(sites) != expected:+ problems.append(+ _render(relpath, sites, root="crates")+ + f"\n (allowlist records {expected}, found {len(sites)})"+ )+ assert not problems, (+ "New or changed outbound egress found in crates/.\n\n"+ + "\n".join(problems)+ + _RESOLUTIONS+ )++ def test_the_guarded_rust_paths_are_seen_as_guarded(self) -> None:+ sites = _rust_egress_sites()+ for relpath in (+ "headroom-core/src/tokenizer/hf_impl.rs",+ "headroom-core/src/transforms/kompress.rs",+ "headroom-core/src/relevance/embedding.rs",+ ):+ assert relpath in sites, f"{relpath} has no detected egress site at all"+ assert all(site.guarded for site in sites[relpath]), (+ f"{relpath} has an egress site the Rust sweep does not see as guarded"+ )++ def test_rust_allowlist_has_no_stale_entries(self) -> None:+ unguarded = {+ relpath+ for relpath, sites in _rust_egress_sites().items()+ if any(not site.guarded for site in sites)+ }+ stale = sorted(set(_RUST_ALLOWLIST) - unguarded)+ assert not stale, f"Rust allowlist entries with no unguarded site; delete them: {stale}"