From 8def1cae7bb28b5d0f7ee427b7ef95f21bf141ab Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 11 Sep 2026 11:18:08 -0500 Subject: [PATCH 1/7] fix(gl): refuse signed requests to a plaintext remote --- crates/gl/src/http.rs | 197 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 197 insertions(+) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index 7a28c6f7b..a22f02ab6 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -19,6 +19,74 @@ const MAX_ICAPTCHA_RETRIES: usize = 2; /// response body, so it bounds a slow download and not just a slow handshake. const TOTAL_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +/// Whether `url` would send a signed request off this machine in cleartext. +/// +/// True only for `http://` to a non-loopback host. RFC 9421 signs the request +/// but does not encrypt it, so on a plaintext hop the `Signature` header and +/// the body are both readable, and a captured signature is replayable for its +/// freshness window against any host. +/// +/// Loopback is decided from the parsed address rather than a string match, so +/// `127.0.0.2`, `[::1]` and an IPv4-mapped `[::ffff:127.0.0.1]` are all +/// recognised as this machine. A value that does not parse, or that is not +/// http(s), is not this guard's business and returns false: it fails later with +/// its own error, and naming it a TLS problem would misdirect the reader. +fn is_insecure_remote(url: &str) -> bool { + let Ok(parsed) = reqwest::Url::parse(url.trim()) else { + return false; + }; + if parsed.scheme() != "http" { + return false; + } + let Some(host) = parsed.host_str() else { + return false; + }; + let host = host.trim_end_matches('.').to_ascii_lowercase(); + if host == "localhost" { + return false; + } + // host_str() keeps the brackets on an IPv6 literal. + let bare = host.trim_start_matches('[').trim_end_matches(']'); + if let Ok(ip) = bare.parse::() { + if ip.is_loopback() { + return false; + } + // An IPv4-mapped IPv6 literal hides a v4 loopback from is_loopback(). + if let std::net::IpAddr::V6(v6) = ip { + if let Some(v4) = v6.to_ipv4_mapped() { + if v4.is_loopback() { + return false; + } + } + } + } + true +} + +/// Refuse to sign a request destined for a cleartext hop off this machine +/// unless the operator has opted in. `GITLAWB_ALLOW_INSECURE_HTTP` exists for a +/// private LAN where the operator has decided that is acceptable; its presence +/// alone opts in, matching git-remote-gitlawb's guard for the same hop. +fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> { + if allow_insecure || !is_insecure_remote(node_base) { + return Ok(()); + } + anyhow::bail!( + "refusing to send a signed request to {node_base} over plaintext http.\n\ + The request is signed but not encrypted, so the Signature header and \ + the body are readable by anyone on the path, and a captured signature \ + can be replayed.\n\ + Use https://, or set GITLAWB_ALLOW_INSECURE_HTTP=1 to accept the risk \ + (for a trusted private network only)." + ) +} + +/// The operator opt-in for a plaintext remote, read at request time so a test +/// or shell can set it without rebuilding the client. +fn insecure_http_allowed() -> bool { + std::env::var_os("GITLAWB_ALLOW_INSECURE_HTTP").is_some() +} + /// Follow a redirect only when it stays on the origin that issued it AND re-issues the /// identical request-target, and only for as long as the chain bound allows. /// @@ -115,6 +183,7 @@ impl NodeClient { .keypair .as_ref() .context("get_signed requires an identity keypair")?; + ensure_signing_transport(&self.node_url, insecure_http_allowed())?; let signed = sign_request(kp, "GET", path, b""); let req = self .inner @@ -133,6 +202,7 @@ impl NodeClient { let url = format!("{}{}", self.node_url, path); let mut req = self.inner.get(&url); if let Some(kp) = &self.keypair { + ensure_signing_transport(&self.node_url, insecure_http_allowed())?; let signed = sign_request(kp, "GET", path, b""); req = req .header("Content-Digest", signed.content_digest) @@ -214,6 +284,7 @@ impl NodeClient { .body(body.to_vec()); if let Some(kp) = &self.keypair { + ensure_signing_transport(&self.node_url, insecure_http_allowed())?; let signed = sign_request(kp, method, path, body); req = req .header("Content-Digest", signed.content_digest) @@ -1268,4 +1339,130 @@ mod tests { let out = sanitize_node_msg("ok \u{0627}\u{200D}b"); assert_eq!(out, "ok \u{0627}\u{200D}b"); } + + // ── #413 plaintext-remote signing guard ────────────────────────────── + + /// Holds [`ICAPTCHA_ENV_LOCK`] while it points `GITLAWB_ALLOW_INSECURE_HTTP` + /// at `value` (or removes it), restoring the prior value on drop. + struct InsecureHttpEnv { + _lock: MutexGuard<'static, ()>, + prev: Option, + } + + impl InsecureHttpEnv { + fn set(value: Option<&str>) -> Self { + let lock = ICAPTCHA_ENV_LOCK.lock().unwrap(); + let prev = std::env::var_os("GITLAWB_ALLOW_INSECURE_HTTP"); + match value { + Some(v) => std::env::set_var("GITLAWB_ALLOW_INSECURE_HTTP", v), + None => std::env::remove_var("GITLAWB_ALLOW_INSECURE_HTTP"), + } + InsecureHttpEnv { _lock: lock, prev } + } + } + + impl Drop for InsecureHttpEnv { + fn drop(&mut self) { + match self.prev.take() { + Some(v) => std::env::set_var("GITLAWB_ALLOW_INSECURE_HTTP", v), + None => std::env::remove_var("GITLAWB_ALLOW_INSECURE_HTTP"), + } + } + } + + #[test] + fn insecure_remote_flags_only_plaintext_off_machine() { + // Loopback of every spelling is this machine and exempt. + for url in [ + "http://localhost", + "http://localhost:7545", + "http://127.0.0.1:7545", + "http://127.0.0.2", + "http://[::1]", + "http://[::ffff:127.0.0.1]", + // https to anywhere is encrypted; the guard is not its business. + "https://node.gitlawb.com", + // Not a URL: unparseable input fails later with its own error. + "not a url", + ] { + assert!(!is_insecure_remote(url), "{url} must not be flagged"); + } + // Plaintext http off this machine is the flagged shape. + for url in [ + "http://10.0.0.36:7777", + "http://node.example.com", + "http://[fd00::1]", + "http://127.0.0.1.evil.example", + ] { + assert!(is_insecure_remote(url), "{url} must be flagged"); + } + } + + #[test] + fn signing_transport_refuses_plaintext_remote() { + let err = ensure_signing_transport("http://10.0.0.36:7777", false).unwrap_err(); + assert!( + err.to_string().contains("plaintext http") + && err.to_string().contains("GITLAWB_ALLOW_INSECURE_HTTP"), + "the refusal names the risk and the opt-in: {err}" + ); + // Opted in, loopback, and https all pass. + assert!(ensure_signing_transport("http://10.0.0.36:7777", true).is_ok()); + assert!(ensure_signing_transport("http://localhost:7545", false).is_ok()); + assert!(ensure_signing_transport("https://node.gitlawb.com", false).is_ok()); + } + + /// A signed call against a plaintext remote errors out before any request + /// leaves; the refusal must beat the send. `.invalid` NXDOMAINs fast, so a + /// missed guard surfaces as a DNS error rather than a slow timeout. + #[tokio::test] + async fn get_signed_refuses_plaintext_remote_before_sending() { + let _env = InsecureHttpEnv::set(None); + let client = NodeClient::new("http://gl-nonexistent-node.invalid", Some(test_keypair())); + let err = client.get_signed("/api/v1/x").await.unwrap_err(); + assert!( + err.to_string().contains("plaintext http"), + "expected the transport refusal, got: {err}" + ); + } + + /// With the opt-in set, the same call passes the guard and fails later on + /// the unresolvable host, proving the env var unblocks the send rather than + /// merely being read. + #[tokio::test] + async fn get_signed_proceeds_when_insecure_http_opted_in() { + let _env = InsecureHttpEnv::set(Some("1")); + let client = NodeClient::new("http://gl-nonexistent-node.invalid", Some(test_keypair())); + let err = client.get_signed("/api/v1/x").await.unwrap_err(); + assert!( + !err.to_string().contains("plaintext http"), + "the opt-in should let the request attempt the hop, got: {err}" + ); + } + + /// Unsigned calls are not this guard's business: no keypair means no + /// signature to leak, and the request proceeds to its own failure. + #[tokio::test] + async fn unsigned_call_to_plaintext_remote_is_ungated() { + let _env = InsecureHttpEnv::set(None); + let client = NodeClient::new("http://gl-nonexistent-node.invalid", None); + let err = client.post("/api/v1/x", b"{}").await.unwrap_err(); + assert!( + !err.to_string().contains("plaintext http"), + "an unsigned request should not hit the signing guard, got: {err}" + ); + } + + /// The opt-in is presence-based, matching the remote helper's read. + #[test] + fn insecure_http_allowed_reads_the_env_var() { + { + let _env = InsecureHttpEnv::set(Some("1")); + assert!(insecure_http_allowed()); + } + { + let _env = InsecureHttpEnv::set(None); + assert!(!insecure_http_allowed()); + } + } } From 9ed392f91fc87a88dd4e169eba56e2293b6b5d81 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 11 Sep 2026 11:53:28 -0500 Subject: [PATCH 2/7] fix(gl): refuse signed loopback http when a proxy carries it off-machine --- crates/gl/src/http.rs | 143 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 141 insertions(+), 2 deletions(-) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index a22f02ab6..edf60774b 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -63,12 +63,75 @@ fn is_insecure_remote(url: &str) -> bool { true } +/// True when `no_proxy` covers `host`: a `*` entry, an exact match, or a +/// domain suffix match (`example.com` covers `a.example.com`). +fn no_proxy_covers(host: &str, no_proxy: &str) -> bool { + no_proxy + .split(',') + .map(str::trim) + .map(|e| e.trim_start_matches('.')) + .filter(|e| !e.is_empty()) + .any(|e| e == "*" || host == e || host.ends_with(&format!(".{e}"))) +} + +/// True when a plaintext request to a loopback `host` would still leave this +/// machine. reqwest reads HTTP_PROXY/ALL_PROXY (and lowercase) at client +/// build; a configured proxy without a NO_PROXY entry for the host carries the +/// signed request off-machine in cleartext, which is the leak this module +/// guards against. +fn loopback_goes_off_machine(host: &str) -> bool { + let proxied = ["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"] + .iter() + .any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty())); + if !proxied { + return false; + } + let no_proxy = std::env::var("NO_PROXY") + .or_else(|_| std::env::var("no_proxy")) + .unwrap_or_default(); + !no_proxy_covers(host, &no_proxy) +} + +/// The normalized host when `url` is an `http://` loopback address, else None. +/// Same loopback rules as [`is_insecure_remote`]. +fn loopback_http_host(url: &str) -> Option { + let parsed = reqwest::Url::parse(url.trim()).ok()?; + if parsed.scheme() != "http" { + return None; + } + let host = parsed + .host_str()? + .trim_end_matches('.') + .to_ascii_lowercase(); + if host == "localhost" { + return Some(host); + } + let bare = host + .trim_start_matches('[') + .trim_end_matches(']') + .to_string(); + let ip = bare.parse::().ok()?; + if ip.is_loopback() { + return Some(bare); + } + if let std::net::IpAddr::V6(v6) = ip { + if v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()) { + return Some(bare); + } + } + None +} + /// Refuse to sign a request destined for a cleartext hop off this machine /// unless the operator has opted in. `GITLAWB_ALLOW_INSECURE_HTTP` exists for a /// private LAN where the operator has decided that is acceptable; its presence -/// alone opts in, matching git-remote-gitlawb's guard for the same hop. +/// alone opts in, matching git-remote-gitlawb's guard for the same hop. The +/// loopback exemption does not apply when a proxy would carry the request +/// off-machine anyway. fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> { - if allow_insecure || !is_insecure_remote(node_base) { + let insecure = is_insecure_remote(node_base) + || loopback_http_host(node_base).is_some_and(|h| loopback_goes_off_machine(&h)); + if allow_insecure || !insecure { return Ok(()); } anyhow::bail!( @@ -1465,4 +1528,80 @@ mod tests { assert!(!insecure_http_allowed()); } } + + #[test] + fn no_proxy_covers_matches_exact_suffix_and_star() { + assert!(no_proxy_covers("localhost", "localhost,127.0.0.1")); + assert!(no_proxy_covers("127.0.0.1", "localhost, 127.0.0.1")); + assert!(no_proxy_covers("a.example.com", ".example.com")); + assert!(no_proxy_covers("a.example.com", "example.com")); + assert!(no_proxy_covers("anything", "*")); + assert!(!no_proxy_covers("localhost", "127.0.0.1")); + assert!(!no_proxy_covers("127.0.0.1", "")); + assert!(!no_proxy_covers("notevil.com", "evil.com")); + } + + /// A proxied loopback plaintext hop must be refused. The env plumbing is + /// checked in a re-execed child so the process-global proxy vars never + /// touch sibling tests' reqwest clients. + #[test] + fn proxied_loopback_http_is_refused() { + if std::env::var_os("GL_PROXY_CHILD").is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tests::http::tests::proxied_loopback_http_is_refused", + ]) + .env("GL_PROXY_CHILD", "1") + .env("HTTP_PROXY", "http://10.9.9.9:3128") + .env_remove("http_proxy") + .env_remove("ALL_PROXY") + .env_remove("all_proxy") + .env_remove("NO_PROXY") + .env_remove("no_proxy") + .env_remove("GITLAWB_ALLOW_INSECURE_HTTP") + .output() + .unwrap(); + assert!( + out.status.success(), + "child failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + return; + } + let err = + ensure_signing_transport("http://127.0.0.1:1", insecure_http_allowed()).unwrap_err(); + assert!( + err.to_string().contains("plaintext http"), + "a proxy without NO_PROXY carries the signed request off-machine: {err}" + ); + } + + /// And NO_PROXY covering the host restores the loopback exemption. + #[test] + fn proxied_loopback_with_no_proxy_is_allowed() { + if std::env::var_os("GL_PROXY_CHILD2").is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tests::http::tests::proxied_loopback_with_no_proxy_is_allowed", + ]) + .env("GL_PROXY_CHILD2", "1") + .env("HTTP_PROXY", "http://10.9.9.9:3128") + .env("NO_PROXY", "localhost,127.0.0.1") + .env_remove("GITLAWB_ALLOW_INSECURE_HTTP") + .output() + .unwrap(); + assert!( + out.status.success(), + "child failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + return; + } + assert!( + ensure_signing_transport("http://127.0.0.1:1", insecure_http_allowed()).is_ok(), + "NO_PROXY covering the host keeps the request on this machine" + ); + } } From 07b8234b9b6ed5c7a6240199efda1f2b44dee512 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 11 Sep 2026 12:14:49 -0500 Subject: [PATCH 3/7] fix(gl): judge the client's build-time proxy state, and prove the env tests run --- crates/gl/src/http.rs | 164 ++++++++++++++++++++++++------------------ 1 file changed, 95 insertions(+), 69 deletions(-) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index edf60774b..b5ccbaeb8 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -64,32 +64,23 @@ fn is_insecure_remote(url: &str) -> bool { } /// True when `no_proxy` covers `host`: a `*` entry, an exact match, or a -/// domain suffix match (`example.com` covers `a.example.com`). +/// domain suffix match (`example.com` covers `a.example.com`). Entries match +/// case-insensitively, as DNS names are. fn no_proxy_covers(host: &str, no_proxy: &str) -> bool { no_proxy .split(',') .map(str::trim) - .map(|e| e.trim_start_matches('.')) + .map(|e| e.trim_start_matches('.').to_ascii_lowercase()) .filter(|e| !e.is_empty()) .any(|e| e == "*" || host == e || host.ends_with(&format!(".{e}"))) } /// True when a plaintext request to a loopback `host` would still leave this -/// machine. reqwest reads HTTP_PROXY/ALL_PROXY (and lowercase) at client -/// build; a configured proxy without a NO_PROXY entry for the host carries the -/// signed request off-machine in cleartext, which is the leak this module -/// guards against. -fn loopback_goes_off_machine(host: &str) -> bool { - let proxied = ["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"] - .iter() - .any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty())); - if !proxied { - return false; - } - let no_proxy = std::env::var("NO_PROXY") - .or_else(|_| std::env::var("no_proxy")) - .unwrap_or_default(); - !no_proxy_covers(host, &no_proxy) +/// machine under the proxy env the client was built with. A configured proxy +/// without a NO_PROXY entry for the host carries the signed request +/// off-machine in cleartext, which is the leak this module guards against. +fn loopback_goes_off_machine(host: &str, proxy_env: &(bool, String)) -> bool { + proxy_env.0 && !no_proxy_covers(host, &proxy_env.1) } /// The normalized host when `url` is an `http://` loopback address, else None. @@ -127,10 +118,15 @@ fn loopback_http_host(url: &str) -> Option { /// private LAN where the operator has decided that is acceptable; its presence /// alone opts in, matching git-remote-gitlawb's guard for the same hop. The /// loopback exemption does not apply when a proxy would carry the request -/// off-machine anyway. -fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> { +/// off-machine anyway; `proxy_env` is the proxy state the client was built +/// with, so the guard judges the same routing the client will use. +fn ensure_signing_transport( + node_base: &str, + allow_insecure: bool, + proxy_env: &(bool, String), +) -> Result<()> { let insecure = is_insecure_remote(node_base) - || loopback_http_host(node_base).is_some_and(|h| loopback_goes_off_machine(&h)); + || loopback_http_host(node_base).is_some_and(|h| loopback_goes_off_machine(&h, proxy_env)); if allow_insecure || !insecure { return Ok(()); } @@ -189,6 +185,11 @@ fn same_origin_redirect(attempt: reqwest::redirect::Attempt<'_>) -> reqwest::red pub struct NodeClient { inner: reqwest::Client, + /// Proxy env state captured at client build, so the transport guard judges + /// the same routing the client was built with. `(proxied, no_proxy)` where + /// `proxied` means HTTP_PROXY/ALL_PROXY was set and `no_proxy` is the raw + /// NO_PROXY value. + proxy_env: (bool, String), pub node_url: String, keypair: Option, } @@ -212,10 +213,17 @@ impl NodeClient { .user_agent(format!("gl/{} gitlawb-cli", env!("CARGO_PKG_VERSION"))) .build() .expect("failed to build HTTP client"); + let proxied = ["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"] + .iter() + .any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty())); + let no_proxy = std::env::var("NO_PROXY") + .or_else(|_| std::env::var("no_proxy")) + .unwrap_or_default(); Self { inner, node_url: node_url.into(), keypair, + proxy_env: (proxied, no_proxy), } } @@ -246,7 +254,7 @@ impl NodeClient { .keypair .as_ref() .context("get_signed requires an identity keypair")?; - ensure_signing_transport(&self.node_url, insecure_http_allowed())?; + ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; let signed = sign_request(kp, "GET", path, b""); let req = self .inner @@ -265,7 +273,7 @@ impl NodeClient { let url = format!("{}{}", self.node_url, path); let mut req = self.inner.get(&url); if let Some(kp) = &self.keypair { - ensure_signing_transport(&self.node_url, insecure_http_allowed())?; + ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; let signed = sign_request(kp, "GET", path, b""); req = req .header("Content-Digest", signed.content_digest) @@ -347,7 +355,7 @@ impl NodeClient { .body(body.to_vec()); if let Some(kp) = &self.keypair { - ensure_signing_transport(&self.node_url, insecure_http_allowed())?; + ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; let signed = sign_request(kp, method, path, body); req = req .header("Content-Digest", signed.content_digest) @@ -1463,16 +1471,18 @@ mod tests { #[test] fn signing_transport_refuses_plaintext_remote() { - let err = ensure_signing_transport("http://10.0.0.36:7777", false).unwrap_err(); + let no_proxy_env = (false, String::new()); + let err = + ensure_signing_transport("http://10.0.0.36:7777", false, &no_proxy_env).unwrap_err(); assert!( err.to_string().contains("plaintext http") && err.to_string().contains("GITLAWB_ALLOW_INSECURE_HTTP"), "the refusal names the risk and the opt-in: {err}" ); // Opted in, loopback, and https all pass. - assert!(ensure_signing_transport("http://10.0.0.36:7777", true).is_ok()); - assert!(ensure_signing_transport("http://localhost:7545", false).is_ok()); - assert!(ensure_signing_transport("https://node.gitlawb.com", false).is_ok()); + assert!(ensure_signing_transport("http://10.0.0.36:7777", true, &no_proxy_env).is_ok()); + assert!(ensure_signing_transport("http://localhost:7545", false, &no_proxy_env).is_ok()); + assert!(ensure_signing_transport("https://node.gitlawb.com", false, &no_proxy_env).is_ok()); } /// A signed call against a plaintext remote errors out before any request @@ -1541,36 +1551,58 @@ mod tests { assert!(!no_proxy_covers("notevil.com", "evil.com")); } + /// Re-exec this test binary running exactly `child_test` under the given + /// env, and prove the child actually ran one test rather than filter- + /// matching nothing (a wrong `--exact` path exits 0 vacuously). + fn run_env_child(child_test: &str, envs: &[(&str, &str)]) { + let mut cmd = std::process::Command::new(std::env::current_exe().unwrap()); + cmd.args(["--exact", child_test, "--nocapture"]); + // Clear any inherited proxy state first, then apply the case's env; + // env_remove after envs would silently undo a provided NO_PROXY. + for k in [ + "HTTP_PROXY", + "http_proxy", + "ALL_PROXY", + "all_proxy", + "NO_PROXY", + "no_proxy", + "GITLAWB_ALLOW_INSECURE_HTTP", + ] { + cmd.env_remove(k); + } + cmd.envs(envs.iter().copied()); + let out = cmd.output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + stdout.contains("1 passed"), + "the child must run the test, not exit green on a filter miss. \ + stdout:\n{stdout}\nstderr:\n{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!( + out.status.success(), + "child failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + } + /// A proxied loopback plaintext hop must be refused. The env plumbing is /// checked in a re-execed child so the process-global proxy vars never /// touch sibling tests' reqwest clients. - #[test] - fn proxied_loopback_http_is_refused() { + #[tokio::test] + async fn proxied_loopback_http_is_refused() { if std::env::var_os("GL_PROXY_CHILD").is_none() { - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "tests::http::tests::proxied_loopback_http_is_refused", - ]) - .env("GL_PROXY_CHILD", "1") - .env("HTTP_PROXY", "http://10.9.9.9:3128") - .env_remove("http_proxy") - .env_remove("ALL_PROXY") - .env_remove("all_proxy") - .env_remove("NO_PROXY") - .env_remove("no_proxy") - .env_remove("GITLAWB_ALLOW_INSECURE_HTTP") - .output() - .unwrap(); - assert!( - out.status.success(), - "child failed: {}", - String::from_utf8_lossy(&out.stderr) + run_env_child( + "http::tests::proxied_loopback_http_is_refused", + &[ + ("GL_PROXY_CHILD", "1"), + ("HTTP_PROXY", "http://10.9.9.9:3128"), + ], ); return; } - let err = - ensure_signing_transport("http://127.0.0.1:1", insecure_http_allowed()).unwrap_err(); + let client = NodeClient::new("http://127.0.0.1:1", Some(test_keypair())); + let err = client.get_signed("/api/v1/x").await.unwrap_err(); assert!( err.to_string().contains("plaintext http"), "a proxy without NO_PROXY carries the signed request off-machine: {err}" @@ -1578,30 +1610,24 @@ mod tests { } /// And NO_PROXY covering the host restores the loopback exemption. - #[test] - fn proxied_loopback_with_no_proxy_is_allowed() { + #[tokio::test] + async fn proxied_loopback_with_no_proxy_is_allowed() { if std::env::var_os("GL_PROXY_CHILD2").is_none() { - let out = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "tests::http::tests::proxied_loopback_with_no_proxy_is_allowed", - ]) - .env("GL_PROXY_CHILD2", "1") - .env("HTTP_PROXY", "http://10.9.9.9:3128") - .env("NO_PROXY", "localhost,127.0.0.1") - .env_remove("GITLAWB_ALLOW_INSECURE_HTTP") - .output() - .unwrap(); - assert!( - out.status.success(), - "child failed: {}", - String::from_utf8_lossy(&out.stderr) + run_env_child( + "http::tests::proxied_loopback_with_no_proxy_is_allowed", + &[ + ("GL_PROXY_CHILD2", "1"), + ("HTTP_PROXY", "http://10.9.9.9:3128"), + ("NO_PROXY", "localhost,127.0.0.1"), + ], ); return; } + let client = NodeClient::new("http://127.0.0.1:1", Some(test_keypair())); + let err = client.get_signed("/api/v1/x").await.unwrap_err(); assert!( - ensure_signing_transport("http://127.0.0.1:1", insecure_http_allowed()).is_ok(), - "NO_PROXY covering the host keeps the request on this machine" + !err.to_string().contains("plaintext http"), + "NO_PROXY covering the host keeps the request on this machine: {err}" ); } } From 935d98544d6bc2211951a615ae978220b234b6f1 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 11 Sep 2026 12:31:04 -0500 Subject: [PATCH 4/7] refactor(gl): run the transport guard before request construction --- crates/gl/src/http.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index b5ccbaeb8..5d1fe765a 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -271,9 +271,11 @@ impl NodeClient { /// to be authenticated. Mirrors the conditional signing of post/put/delete. pub async fn get_maybe_signed(&self, path: &str) -> Result { let url = format!("{}{}", self.node_url, path); + if self.keypair.is_some() { + ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; + } let mut req = self.inner.get(&url); if let Some(kp) = &self.keypair { - ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; let signed = sign_request(kp, "GET", path, b""); req = req .header("Content-Digest", signed.content_digest) @@ -348,6 +350,9 @@ impl NodeClient { proof: Option<&str>, ) -> Result { let url = format!("{}{}", self.node_url, path); + if self.keypair.is_some() { + ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; + } let mut req = self .inner .request(method.parse().expect("valid HTTP method"), &url) @@ -355,7 +360,6 @@ impl NodeClient { .body(body.to_vec()); if let Some(kp) = &self.keypair { - ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; let signed = sign_request(kp, method, path, body); req = req .header("Content-Digest", signed.content_digest) From d6ffeaf9fa8648a0f6d0fac9b039060665069967 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 11 Sep 2026 13:02:32 -0500 Subject: [PATCH 5/7] docs(gl): the guard is stricter than the helper's, not identical --- crates/gl/src/http.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index 5d1fe765a..ca6e26023 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -116,9 +116,10 @@ fn loopback_http_host(url: &str) -> Option { /// Refuse to sign a request destined for a cleartext hop off this machine /// unless the operator has opted in. `GITLAWB_ALLOW_INSECURE_HTTP` exists for a /// private LAN where the operator has decided that is acceptable; its presence -/// alone opts in, matching git-remote-gitlawb's guard for the same hop. The +/// alone opts in, matching the variable git-remote-gitlawb's guard uses for +/// the same hop. This guard is stricter than the helper's in one respect: the /// loopback exemption does not apply when a proxy would carry the request -/// off-machine anyway; `proxy_env` is the proxy state the client was built +/// off-machine anyway. `proxy_env` is the proxy state the client was built /// with, so the guard judges the same routing the client will use. fn ensure_signing_transport( node_base: &str, From f77c236ec5636380951378aa1f2ed687fe3575cd Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:52:28 -0600 Subject: [PATCH 6/7] fix(gl): route a loopback node direct so the signing guard and the transport agree The guard reimplemented NO_PROXY matching and could disagree with reqwest about where a request goes: a wildcard, a dotted host or a dotted entry let signing proceed while the proxy still carried the request, and CIDR, IPv6 and trailing-dot entries were refused although they bypass the proxy. A loopback http node is now built with no_proxy(), so a proxy cannot carry its signed requests and the guard no longer models the proxy environment. The matcher, the captured proxy state and their tests are removed. Routing tests put a real listener where the proxy would be and another where the node is, and check the three signing sites reach the node signed and never the proxy. Also drops the comment comparing the guard to git-remote-gitlawb. --- crates/gl/src/http.rs | 318 ++++++++++++++++++++++++------------------ 1 file changed, 185 insertions(+), 133 deletions(-) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index fe427bccb..590f1118a 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -78,72 +78,30 @@ fn is_insecure_remote(url: &str) -> bool { true } -/// True when `no_proxy` covers `host`: a `*` entry, an exact match, or a -/// domain suffix match (`example.com` covers `a.example.com`). Entries match -/// case-insensitively, as DNS names are. -fn no_proxy_covers(host: &str, no_proxy: &str) -> bool { - no_proxy - .split(',') - .map(str::trim) - .map(|e| e.trim_start_matches('.').to_ascii_lowercase()) - .filter(|e| !e.is_empty()) - .any(|e| e == "*" || host == e || host.ends_with(&format!(".{e}"))) -} - -/// True when a plaintext request to a loopback `host` would still leave this -/// machine under the proxy env the client was built with. A configured proxy -/// without a NO_PROXY entry for the host carries the signed request -/// off-machine in cleartext, which is the leak this module guards against. -fn loopback_goes_off_machine(host: &str, proxy_env: &(bool, String)) -> bool { - proxy_env.0 && !no_proxy_covers(host, &proxy_env.1) -} - -/// The normalized host when `url` is an `http://` loopback address, else None. -/// Same loopback rules as [`is_insecure_remote`]. -fn loopback_http_host(url: &str) -> Option { - let parsed = reqwest::Url::parse(url.trim()).ok()?; - if parsed.scheme() != "http" { - return None; - } - let host = parsed - .host_str()? - .trim_end_matches('.') - .to_ascii_lowercase(); - if host == "localhost" { - return Some(host); - } - let bare = host - .trim_start_matches('[') - .trim_end_matches(']') - .to_string(); - let ip = bare.parse::().ok()?; - if ip.is_loopback() { - return Some(bare); - } - if let std::net::IpAddr::V6(v6) = ip { - if v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()) { - return Some(bare); - } - } - None +/// True when `url` is an `http://` address on this machine. Same loopback +/// rules as [`is_insecure_remote`]. +/// +/// The client does not use the proxy environment for such a node: reqwest's +/// own `NO_PROXY` matching differs from any string matcher written here (it +/// parses addresses and CIDR blocks apart from domains, and a wildcard is only +/// a domain entry), so deciding "would this go through the proxy" ourselves +/// can disagree with where the request actually goes. Routing a loopback node +/// directly makes the answer true by construction. See `NodeClient::with_timeout`. +fn is_loopback_http(url: &str) -> bool { + let Ok(parsed) = reqwest::Url::parse(url.trim()) else { + return false; + }; + parsed.scheme() == "http" && parsed.host_str().is_some() && !is_insecure_remote(url) } /// Refuse to sign a request destined for a cleartext hop off this machine /// unless the operator has opted in. `GITLAWB_ALLOW_INSECURE_HTTP` exists for a -/// private LAN where the operator has decided that is acceptable; its presence -/// alone opts in, matching the variable git-remote-gitlawb's guard uses for -/// the same hop. This guard is stricter than the helper's in one respect: the -/// loopback exemption does not apply when a proxy would carry the request -/// off-machine anyway. `proxy_env` is the proxy state the client was built -/// with, so the guard judges the same routing the client will use. -fn ensure_signing_transport( - node_base: &str, - allow_insecure: bool, - proxy_env: &(bool, String), -) -> Result<()> { - let insecure = is_insecure_remote(node_base) - || loopback_http_host(node_base).is_some_and(|h| loopback_goes_off_machine(&h, proxy_env)); - if allow_insecure || !insecure { +/// private LAN where the operator has decided that is acceptable; any value, +/// including `0`, opts in. A loopback node is never proxied (see +/// [`is_loopback_http`]), so a proxy cannot carry its signed requests +/// off-machine and the loopback exemption holds under any proxy environment. +fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> { + if allow_insecure || !is_insecure_remote(node_base) { return Ok(()); } anyhow::bail!( @@ -201,11 +159,6 @@ fn same_origin_redirect(attempt: reqwest::redirect::Attempt<'_>) -> reqwest::red pub struct NodeClient { inner: reqwest::Client, - /// Proxy env state captured at client build, so the transport guard judges - /// the same routing the client was built with. `(proxied, no_proxy)` where - /// `proxied` means HTTP_PROXY/ALL_PROXY was set and `no_proxy` is the raw - /// NO_PROXY value. - proxy_env: (bool, String), pub node_url: String, keypair: Option, } @@ -223,23 +176,23 @@ impl NodeClient { keypair: Option, timeout: std::time::Duration, ) -> Self { - let inner = reqwest::Client::builder() + let node_url = node_url.into(); + let mut builder = reqwest::Client::builder() .timeout(timeout) .redirect(reqwest::redirect::Policy::custom(same_origin_redirect)) - .user_agent(format!("gl/{} gitlawb-cli", env!("CARGO_PKG_VERSION"))) - .build() - .expect("failed to build HTTP client"); - let proxied = ["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"] - .iter() - .any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty())); - let no_proxy = std::env::var("NO_PROXY") - .or_else(|_| std::env::var("no_proxy")) - .unwrap_or_default(); + .user_agent(format!("gl/{} gitlawb-cli", env!("CARGO_PKG_VERSION"))); + // A loopback node is reached directly, ignoring HTTP_PROXY/ALL_PROXY, so + // a proxy can never carry its signed requests off this machine and the + // guard needs no model of the proxy environment. Redirects cannot leave + // the origin (`same_origin_redirect`), so the direct route covers them. + if is_loopback_http(&node_url) { + builder = builder.no_proxy(); + } + let inner = builder.build().expect("failed to build HTTP client"); Self { inner, - node_url: node_url.into(), + node_url, keypair, - proxy_env: (proxied, no_proxy), } } @@ -270,7 +223,7 @@ impl NodeClient { .keypair .as_ref() .context("get_signed requires an identity keypair")?; - ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; + ensure_signing_transport(&self.node_url, insecure_http_allowed())?; let signed = sign_request(kp, "GET", path, b""); let req = self .inner @@ -288,7 +241,7 @@ impl NodeClient { pub async fn get_maybe_signed(&self, path: &str) -> Result { let url = format!("{}{}", self.node_url, path); if self.keypair.is_some() { - ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; + ensure_signing_transport(&self.node_url, insecure_http_allowed())?; } let mut req = self.inner.get(&url); if let Some(kp) = &self.keypair { @@ -401,7 +354,7 @@ impl NodeClient { ) -> Result { let url = format!("{}{}", self.node_url, path); if self.keypair.is_some() { - ensure_signing_transport(&self.node_url, insecure_http_allowed(), &self.proxy_env)?; + ensure_signing_transport(&self.node_url, insecure_http_allowed())?; } let mut req = self .inner @@ -2226,18 +2179,16 @@ mod tests { #[test] fn signing_transport_refuses_plaintext_remote() { - let no_proxy_env = (false, String::new()); - let err = - ensure_signing_transport("http://10.0.0.36:7777", false, &no_proxy_env).unwrap_err(); + let err = ensure_signing_transport("http://10.0.0.36:7777", false).unwrap_err(); assert!( err.to_string().contains("plaintext http") && err.to_string().contains("GITLAWB_ALLOW_INSECURE_HTTP"), "the refusal names the risk and the opt-in: {err}" ); // Opted in, loopback, and https all pass. - assert!(ensure_signing_transport("http://10.0.0.36:7777", true, &no_proxy_env).is_ok()); - assert!(ensure_signing_transport("http://localhost:7545", false, &no_proxy_env).is_ok()); - assert!(ensure_signing_transport("https://node.gitlawb.com", false, &no_proxy_env).is_ok()); + assert!(ensure_signing_transport("http://10.0.0.36:7777", true).is_ok()); + assert!(ensure_signing_transport("http://localhost:7545", false).is_ok()); + assert!(ensure_signing_transport("https://node.gitlawb.com", false).is_ok()); } /// A signed call against a plaintext remote errors out before any request @@ -2281,7 +2232,7 @@ mod tests { ); } - /// The opt-in is presence-based, matching the remote helper's read. + /// The opt-in is presence-based: any value, including `0`, enables it. #[test] fn insecure_http_allowed_reads_the_env_var() { { @@ -2294,18 +2245,6 @@ mod tests { } } - #[test] - fn no_proxy_covers_matches_exact_suffix_and_star() { - assert!(no_proxy_covers("localhost", "localhost,127.0.0.1")); - assert!(no_proxy_covers("127.0.0.1", "localhost, 127.0.0.1")); - assert!(no_proxy_covers("a.example.com", ".example.com")); - assert!(no_proxy_covers("a.example.com", "example.com")); - assert!(no_proxy_covers("anything", "*")); - assert!(!no_proxy_covers("localhost", "127.0.0.1")); - assert!(!no_proxy_covers("127.0.0.1", "")); - assert!(!no_proxy_covers("notevil.com", "evil.com")); - } - /// Re-exec this test binary running exactly `child_test` under the given /// env, and prove the child actually ran one test rather than filter- /// matching nothing (a wrong `--exact` path exits 0 vacuously). @@ -2341,48 +2280,161 @@ mod tests { ); } - /// A proxied loopback plaintext hop must be refused. The env plumbing is - /// checked in a re-execed child so the process-global proxy vars never - /// touch sibling tests' reqwest clients. + // ── #413 routing observed, not asserted ───────────────────────────── + // + // The guard and the client must agree on where a signed request goes. These + // tests put a real listener where a proxy would be and a real listener where + // the node is, run each signing site, and read off which one was contacted. + + /// Accept connections on `listener` for the rest of the process, recording + /// each one's raw request head and answering `status_line` with an empty + /// JSON body. Returns the shared record. + fn serve_recording( + listener: std::net::TcpListener, + status_line: &'static str, + ) -> std::sync::Arc>> { + use std::io::{Read, Write}; + let seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let rec = seen.clone(); + std::thread::spawn(move || { + for conn in listener.incoming() { + let Ok(mut conn) = conn else { continue }; + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + while !buf.windows(4).any(|w| w == b"\r\n\r\n") { + match conn.read(&mut chunk) { + Ok(0) | Err(_) => break, + Ok(n) => buf.extend_from_slice(&chunk[..n]), + } + } + rec.lock() + .unwrap() + .push(String::from_utf8_lossy(&buf).to_ascii_lowercase()); + let _ = conn.write_all( + format!("{status_line}\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{{}}") + .as_bytes(), + ); + } + }); + seen + } + + /// Body of the child process: `GL_ROUTE_HOST` is the node host as written + /// in the URL, `GL_ROUTE_NO_PROXY` the NO_PROXY value (empty means unset). + /// A listener stands in for the proxy and another for the node; the proxy + /// env is pointed at the first before the client is built. Every signing + /// site must reach the node, signed, and never touch the proxy. #[tokio::test] - async fn proxied_loopback_http_is_refused() { - if std::env::var_os("GL_PROXY_CHILD").is_none() { - run_env_child( - "http::tests::proxied_loopback_http_is_refused", - &[ - ("GL_PROXY_CHILD", "1"), - ("HTTP_PROXY", "http://10.9.9.9:3128"), - ], - ); - return; + async fn route_child_signed_requests_stay_off_the_proxy() { + let Some(host) = std::env::var_os("GL_ROUTE_HOST") else { + return; // only meaningful as a re-execed child + }; + let host = host.to_string_lossy().into_owned(); + let no_proxy = std::env::var("GL_ROUTE_NO_PROXY").unwrap_or_default(); + + let bind = if host.starts_with('[') { + "[::1]:0" + } else { + "127.0.0.1:0" + }; + let node = std::net::TcpListener::bind(bind).expect("bind node listener"); + let node_port = node.local_addr().unwrap().port(); + let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let proxy_port = proxy.local_addr().unwrap().port(); + let node_seen = serve_recording(node, "HTTP/1.1 200 OK"); + let proxy_seen = serve_recording(proxy, "HTTP/1.1 502 Bad Gateway"); + + std::env::set_var("HTTP_PROXY", format!("http://127.0.0.1:{proxy_port}")); + if !no_proxy.is_empty() { + std::env::set_var("NO_PROXY", &no_proxy); } - let client = NodeClient::new("http://127.0.0.1:1", Some(test_keypair())); - let err = client.get_signed("/api/v1/x").await.unwrap_err(); + let client = NodeClient::new(format!("http://{host}:{node_port}"), Some(test_keypair())); + + let r = client.get_signed("/api/v1/a").await; + assert!(r.is_ok(), "get_signed: {:?}", r.err()); + let r = client.get_maybe_signed("/api/v1/b").await; + assert!(r.is_ok(), "get_maybe_signed: {:?}", r.err()); + let r = client.post("/api/v1/c", b"{}").await; + assert!(r.is_ok(), "send_once via post: {:?}", r.err()); + + let proxy_seen = proxy_seen.lock().unwrap(); assert!( - err.to_string().contains("plaintext http"), - "a proxy without NO_PROXY carries the signed request off-machine: {err}" + proxy_seen.is_empty(), + "the proxy must see no request, got: {proxy_seen:?}" + ); + let node_seen = node_seen.lock().unwrap(); + assert_eq!(node_seen.len(), 3, "node requests: {node_seen:?}"); + assert!( + node_seen.iter().all(|r| r.contains("\r\nsignature:")), + "every request to the node is signed: {node_seen:?}" ); } - /// And NO_PROXY covering the host restores the loopback exemption. - #[tokio::test] - async fn proxied_loopback_with_no_proxy_is_allowed() { - if std::env::var_os("GL_PROXY_CHILD2").is_none() { + /// The table from the review, plus the bare proxied case. Each row is a + /// loopback node reached with `HTTP_PROXY` set, the override unset, and a + /// different `NO_PROXY`; every one must go straight to the node. + #[test] + fn signed_loopback_requests_never_reach_the_proxy() { + let rows: &[(&str, &str)] = &[ + ("127.0.0.1", ""), + ("127.0.0.1", "*"), + ("localhost.", "localhost"), + ("127.0.0.1", ".127.0.0.1"), + ("127.0.0.1", "127.0.0.0/8"), + ("[::1]", "0:0:0:0:0:0:0:1"), + ("localhost.", "localhost."), + ("127.0.0.1", "127.0.0.1"), + ]; + for (host, no_proxy) in rows { + if host.starts_with('[') && std::net::TcpListener::bind("[::1]:0").is_err() { + eprintln!("skipping {host}: no IPv6 loopback on this machine"); + continue; + } run_env_child( - "http::tests::proxied_loopback_with_no_proxy_is_allowed", - &[ - ("GL_PROXY_CHILD2", "1"), - ("HTTP_PROXY", "http://10.9.9.9:3128"), - ("NO_PROXY", "localhost,127.0.0.1"), - ], + "http::tests::route_child_signed_requests_stay_off_the_proxy", + &[("GL_ROUTE_HOST", host), ("GL_ROUTE_NO_PROXY", no_proxy)], ); + } + } + + /// Body of the child process: a plaintext node that is NOT on this machine, + /// reached through a proxy. Without the override the guard refuses before + /// anything is sent; with it, the request goes via the proxy as configured. + #[tokio::test] + async fn route_child_remote_node_follows_the_override() { + if std::env::var_os("GL_ROUTE_REMOTE").is_none() { return; } - let client = NodeClient::new("http://127.0.0.1:1", Some(test_keypair())); - let err = client.get_signed("/api/v1/x").await.unwrap_err(); - assert!( - !err.to_string().contains("plaintext http"), - "NO_PROXY covering the host keeps the request on this machine: {err}" + let allow = std::env::var_os("GL_ROUTE_ALLOW").is_some(); + let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let proxy_port = proxy.local_addr().unwrap().port(); + let proxy_seen = serve_recording(proxy, "HTTP/1.1 502 Bad Gateway"); + std::env::set_var("HTTP_PROXY", format!("http://127.0.0.1:{proxy_port}")); + let client = NodeClient::new("http://gl-remote-node.invalid:7777", Some(test_keypair())); + let r = client.get_signed("/api/v1/a").await; + let seen = proxy_seen.lock().unwrap(); + if allow { + assert_eq!(seen.len(), 1, "the override sends via the proxy: {seen:?}"); + } else { + let err = r.unwrap_err().to_string(); + assert!(err.contains("plaintext http"), "refusal expected: {err}"); + assert!(seen.is_empty(), "nothing may reach the proxy: {seen:?}"); + } + } + + #[test] + fn signed_remote_plaintext_is_refused_unless_overridden() { + run_env_child( + "http::tests::route_child_remote_node_follows_the_override", + &[("GL_ROUTE_REMOTE", "1")], + ); + run_env_child( + "http::tests::route_child_remote_node_follows_the_override", + &[ + ("GL_ROUTE_REMOTE", "1"), + ("GL_ROUTE_ALLOW", "1"), + ("GITLAWB_ALLOW_INSECURE_HTTP", "1"), + ], ); } From 4d87be9f7d25c0b6a243f732a583621185d02e14 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:57:31 -0600 Subject: [PATCH 7/7] fix(gl): read GITLAWB_ALLOW_INSECURE_HTTP as a value, not as presence Only 1 or true opens the gate, matching git-remote-gitlawb and icaptcha-client. =0, =false and an empty value previously enabled plaintext signing; a non-empty non-truthy value now warns and stays closed. --- crates/gl/src/http.rs | 69 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index 590f1118a..f5a3fd18b 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -96,8 +96,8 @@ fn is_loopback_http(url: &str) -> bool { /// Refuse to sign a request destined for a cleartext hop off this machine /// unless the operator has opted in. `GITLAWB_ALLOW_INSECURE_HTTP` exists for a -/// private LAN where the operator has decided that is acceptable; any value, -/// including `0`, opts in. A loopback node is never proxied (see +/// private LAN where the operator has decided that is acceptable; only `1` or +/// `true` opts in. A loopback node is never proxied (see /// [`is_loopback_http`]), so a proxy cannot carry its signed requests /// off-machine and the loopback exemption holds under any proxy environment. fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> { @@ -114,10 +114,46 @@ fn ensure_signing_transport(node_base: &str, allow_insecure: bool) -> Result<()> ) } +/// Parse a `GITLAWB_ALLOW_INSECURE_HTTP` value. Only `1` or `true` +/// (case-insensitive, after trim) opens the gate. Presence alone is not +/// consent: `=0`, `=false` and an empty value read as "not opting in" to the +/// operator, and the README and the refusal message document `=1`. A non-empty +/// value that is not truthy warns, so a misspelling is neither a silent yes nor +/// a silent no. Same contract as `git-remote-gitlawb` and `icaptcha-client`. +fn allow_insecure_http_from_str(raw: Option<&str>) -> bool { + let Some(v) = raw else { + return false; + }; + let t = v.trim(); + if t.eq_ignore_ascii_case("1") || t.eq_ignore_ascii_case("true") { + return true; + } + if !t.is_empty() { + warn_allow_insecure_http_non_truthy(); + } + false +} + +/// Fixed warning for a set but non-truthy value. The raw value is never printed. +fn warn_allow_insecure_http_non_truthy() { + eprintln!( + "warning: GITLAWB_ALLOW_INSECURE_HTTP is set but not truthy (expected 1 or true); \ + plaintext http to a remote node remains refused" + ); +} + /// The operator opt-in for a plaintext remote, read at request time so a test -/// or shell can set it without rebuilding the client. +/// or shell can set it without rebuilding the client. A non-UTF-8 value fails +/// closed and warns like any other non-truthy one. fn insecure_http_allowed() -> bool { - std::env::var_os("GITLAWB_ALLOW_INSECURE_HTTP").is_some() + match std::env::var("GITLAWB_ALLOW_INSECURE_HTTP") { + Ok(v) => allow_insecure_http_from_str(Some(&v)), + Err(std::env::VarError::NotUnicode(_)) => { + warn_allow_insecure_http_non_truthy(); + false + } + Err(std::env::VarError::NotPresent) => false, + } } /// Follow a redirect only when it stays on the origin that issued it AND re-issues the @@ -2232,17 +2268,26 @@ mod tests { ); } - /// The opt-in is presence-based: any value, including `0`, enables it. + /// The opt-in is read as a value, not as presence, with the same contract as + /// `git-remote-gitlawb` and `icaptcha-client`: `1` or `true`, case-insensitive + /// after trim. `0`, `false`, empty and anything else leave the gate closed. #[test] - fn insecure_http_allowed_reads_the_env_var() { - { - let _env = InsecureHttpEnv::set(Some("1")); - assert!(insecure_http_allowed()); + fn insecure_http_opt_in_is_truthy_only() { + for on in ["1", "true", "TRUE", "True", " 1 ", "\ttrue\n"] { + assert!(allow_insecure_http_from_str(Some(on)), "{on:?} must opt in"); } - { - let _env = InsecureHttpEnv::set(None); - assert!(!insecure_http_allowed()); + for off in ["0", "false", "", " ", "yes", "on", "2", "truee"] { + assert!( + !allow_insecure_http_from_str(Some(off)), + "{off:?} must not opt in" + ); } + assert!(!allow_insecure_http_from_str(None)); + let _env = InsecureHttpEnv::set(Some("0")); + assert!(!insecure_http_allowed(), "=0 must not open the gate"); + drop(_env); + let _env = InsecureHttpEnv::set(Some("1")); + assert!(insecure_http_allowed()); } /// Re-exec this test binary running exactly `child_test` under the given