From 1e5b262016d4d6833384be3afbc93527e9b9374c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Tue, 1 Sep 2026 09:53:56 -0500 Subject: [PATCH 1/6] fix(gl): make doctor diagnose the node the git transport will use `gl doctor` reported a healthy node and exited 0 on a stock install whose `git push` and `git clone` could not reach anything. `gl`'s `--node` defaults to https://node.gitlawb.com while `git-remote-gitlawb` fell back to http://127.0.0.1:7545, so with GITLAWB_NODE unset the check validated a URL the transport never contacts. An explicit `--node` outranks the environment, so the two could disagree even when the variable was set. Both binaries now resolve through `gitlawb_core::resolve_transport_node`, and doctor probes whatever that returns whenever it differs from its own node, folding the result into the existing GITLAWB_NODE row rather than adding a second row for the same condition. Three things the probe does that the first attempt did not. It requires a `did` in the response before reporting the transport usable, because any local service answering 200 on that port otherwise read as a working transport, which is the same false green this change exists to remove. It uses a dedicated client with `no_proxy` and a 3s timeout, since the shared client routes a loopback probe through HTTP_PROXY and inherits a 30s timeout that stalled every stock run behind a hung listener. And it sanitizes the node URL and single-quotes it in the suggested-fix line, which is printed for the user to paste. A blank or whitespace-only GITLAWB_NODE now resolves to the local default in both binaries. It previously gave the helper an empty base, so every clone URL lost its scheme and host. Tiering follows who chose the broken value: an unset variable stays advisory because `gl` itself still works and #357 requires a stock install to keep exiting 0, while a variable the user set to something unusable fails. --- crates/git-remote-gitlawb/src/main.rs | 27 ++- crates/gitlawb-core/src/lib.rs | 45 +++++ crates/gl/src/doctor.rs | 127 +++++++++++--- crates/gl/tests/doctor_transport_node.rs | 204 +++++++++++++++++++++++ 4 files changed, 377 insertions(+), 26 deletions(-) create mode 100644 crates/gl/tests/doctor_transport_node.rs diff --git a/crates/git-remote-gitlawb/src/main.rs b/crates/git-remote-gitlawb/src/main.rs index 738839c11..657d6d43d 100644 --- a/crates/git-remote-gitlawb/src/main.rs +++ b/crates/git-remote-gitlawb/src/main.rs @@ -25,6 +25,7 @@ use anyhow::{bail, Context, Result}; use gitlawb_core::http_sig::sign_request; use gitlawb_core::identity::Keypair; +use gitlawb_core::{resolve_transport_node, DEFAULT_LOCAL_NODE}; use std::io::{self, BufRead, Read, Write}; fn main() -> Result<()> { @@ -63,9 +64,9 @@ fn main() -> Result<()> { let (_, short_owner, repo_name) = parse_gitlawb_url(url)?; - // v0.1: default to localhost. Override with GITLAWB_NODE env var. - let node_base = - std::env::var("GITLAWB_NODE").unwrap_or_else(|_| "http://127.0.0.1:7545".to_string()); + // v0.1: default to localhost. Override with GITLAWB_NODE env var. Shared with + // `gl doctor` so the diagnostic reports the URL this actually resolves. + let node_base = node_base_from_env(); let repo_base = format!("{}/{}/{}", node_base, short_owner, repo_name); tracing::debug!("repo_base: {repo_base}"); @@ -78,6 +79,12 @@ fn main() -> Result<()> { run_helper(&repo_base, keypair.as_ref()) } +/// The node base URL this helper will contact, resolved through the same function +/// `gl doctor` reports on so the diagnostic cannot describe a different node. +fn node_base_from_env() -> String { + resolve_transport_node(std::env::var("GITLAWB_NODE").ok().as_deref()) +} + // ── CLI argument handling ────────────────────────────────────────────────────── /// How the binary was invoked, derived from its CLI arguments. @@ -123,7 +130,7 @@ fn help_text() -> String { \x20 git clone gitlawb://did:key:z6Mk.../\n\ \n\ ENVIRONMENT:\n\ - \x20 GITLAWB_NODE Node base URL (default: http://127.0.0.1:7545)\n\ + \x20 GITLAWB_NODE Node base URL (default: {DEFAULT_LOCAL_NODE})\n\ \x20 GITLAWB_KEY Identity PEM path for signed fetch/push (default: ~/.gitlawb/identity.pem)\n\ \x20 GITLAWB_LOG Log filter (default: warn)\n\ \n\ @@ -2014,9 +2021,21 @@ mod tests { assert!(help.contains("--version")); assert!(help.contains("--help")); assert!(help.contains("GITLAWB_NODE")); + // The advertised default must be the value the helper actually resolves. + assert!(help.contains(DEFAULT_LOCAL_NODE)); assert!(help.ends_with('\n')); } + /// The helper's own resolution must stay the shared one; a site walking back to + /// a private literal is exactly the drift the shared function exists to stop. + #[test] + fn node_base_matches_the_shared_resolver() { + // No env manipulation: assert the call site delegates, for the default case. + let expected = resolve_transport_node(std::env::var("GITLAWB_NODE").ok().as_deref()); + assert_eq!(node_base_from_env(), expected); + assert_eq!(resolve_transport_node(None), DEFAULT_LOCAL_NODE); + } + // ── #117 multi-round fetch negotiation ─────────────────────────────────── /// Encode a git pkt-line: 4-byte hex length (incl. the 4 bytes) + data. diff --git a/crates/gitlawb-core/src/lib.rs b/crates/gitlawb-core/src/lib.rs index d0edec0ae..997197392 100644 --- a/crates/gitlawb-core/src/lib.rs +++ b/crates/gitlawb-core/src/lib.rs @@ -17,5 +17,50 @@ pub mod sanitize; pub mod scan_token; pub mod ucan; +/// Node URL the git transport falls back to when `GITLAWB_NODE` is unset. +/// +/// `gl` defaults to the public node instead, so the two disagree on an install +/// that never sets the variable. +pub const DEFAULT_LOCAL_NODE: &str = "http://127.0.0.1:7545"; + +/// The node `git clone` and `git push` will contact, given the raw `GITLAWB_NODE` +/// value (`None` when the variable is absent). +/// +/// `git-remote-gitlawb` calls this to pick its base URL and `gl doctor` calls it +/// to report that URL, so a diagnostic cannot describe a node the transport will +/// not use. A blank or whitespace-only value is not a configured node: treating +/// it as one gave the helper an empty base and every clone URL a missing scheme +/// and host. +pub fn resolve_transport_node(env_value: Option<&str>) -> String { + match env_value.map(str::trim) { + Some(v) if !v.is_empty() => v.to_string(), + _ => DEFAULT_LOCAL_NODE.to_string(), + } +} + pub use error::Error; pub type Result = std::result::Result; + +#[cfg(test)] +mod transport_node_tests { + use super::*; + + #[test] + fn absent_or_blank_resolves_to_the_local_default() { + for raw in [None, Some(""), Some(" "), Some("\t\n")] { + assert_eq!(resolve_transport_node(raw), DEFAULT_LOCAL_NODE, "{raw:?}"); + } + } + + #[test] + fn a_configured_value_wins_and_is_trimmed() { + assert_eq!( + resolve_transport_node(Some("https://n.example")), + "https://n.example" + ); + assert_eq!( + resolve_transport_node(Some(" https://n.example ")), + "https://n.example" + ); + } +} diff --git a/crates/gl/src/doctor.rs b/crates/gl/src/doctor.rs index 86f503344..80a34ce9b 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -13,7 +13,9 @@ use anyhow::Result; use clap::Args; use std::path::PathBuf; -use crate::http::NodeClient; +use gitlawb_core::resolve_transport_node; + +use crate::http::{sanitize_node_msg, NodeClient}; const PUBLIC_NODE: &str = "https://node.gitlawb.com"; const GITHUB_API_BASE: &str = "https://api.github.com"; @@ -141,27 +143,51 @@ pub async fn run(args: DoctorArgs) -> Result<()> { } // ── 3. GITLAWB_NODE env var ─────────────────────────────────────────── - match std::env::var("GITLAWB_NODE") { - // A loopback host is a legitimate setup (self-hosted node, dev - // harness) — the connectivity check below fails loudly if it is not - // actually reachable, so don't red-flag the configuration itself. - Ok(v) if is_loopback_url(&v) => { - checks.push(Check::pass( - "GITLAWB_NODE", - format!( - "{v} (local node — intentional for self-hosting/dev; unset to target the public network)" - ), - )); - } - Ok(v) if !v.is_empty() => { - checks.push(Check::pass("GITLAWB_NODE", v.to_string())); - } - _ => { - checks.push(Check::fail( - "GITLAWB_NODE", - "not set — git-remote-gitlawb will fall back to http://127.0.0.1:7545", - "export GITLAWB_NODE=https://node.gitlawb.com", - )); + // The node `git clone` / `git push` will contact is not always the node `gl` + // contacts: `--node` defaults to the public node and an explicit flag outranks + // the environment, so the two diverge whenever the variable is unset, blank, or + // overridden. Probing only `gl`'s node is what let doctor greenlight an install + // whose transport was dead, so resolve the transport's node through the same + // function the helper uses and report on that one. + let env_node = std::env::var("GITLAWB_NODE").ok(); + let transport_node = resolve_transport_node(env_node.as_deref()); + let gl_node = sanitize_node_msg(&args.node); + + if transport_node == args.node { + // gl and the transport agree, so one row covers both. A loopback host is a + // legitimate setup (self-hosted node, dev harness) and the connectivity + // check below fails loudly if it is not actually reachable, so don't + // red-flag the configuration itself. + let detail = if is_loopback_url(&transport_node) { + format!( + "{gl_node} (local node, intentional for self-hosting/dev; unset to target the public network)" + ) + } else { + gl_node.clone() + }; + checks.push(Check::pass("GITLAWB_NODE", detail)); + } else { + let verdict = probe_transport(&transport_node).await; + let detail = format!( + "git push/clone will use {} ({}); gl targets {gl_node}", + sanitize_node_msg(&transport_node), + verdict.detail + ); + // Single-quote the value: this line is printed under "Suggested fixes" for + // the user to paste into a shell, and the URL is caller-supplied. + let fix = format!("export GITLAWB_NODE='{gl_node}'"); + // Tiering follows who chose the broken value. An unset variable on a stock + // install is advisory: `gl` works, only `git push`/`git clone` do not, and + // #357 requires that install to keep exiting 0. A variable the user set to + // something unusable is a real misconfiguration. + let env_was_set = env_node + .as_deref() + .map(str::trim) + .is_some_and(|v| !v.is_empty()); + if verdict.usable || !env_was_set { + checks.push(Check::warn("GITLAWB_NODE", detail, fix)); + } else { + checks.push(Check::fail("GITLAWB_NODE", detail, fix)); } } @@ -319,6 +345,63 @@ pub async fn run(args: DoctorArgs) -> Result<()> { Ok(()) } +/// Outcome of probing the node the git transport will use. +struct TransportVerdict { + /// True only when the endpoint identified itself as a gitlawb node. A bare 200 + /// is not enough: any local service answering on that port would otherwise be + /// reported as a working transport, which is the false green this check exists + /// to catch. + usable: bool, + detail: String, +} + +/// Probe `url` and describe what is actually there. +/// +/// Deliberately not `NodeClient`: this call must not follow the user's proxy +/// (a proxy swallows a loopback probe and reports a running local node as dead) +/// and must not inherit the 30s request timeout, which stalls every stock +/// `gl doctor` run behind a hung listener. +async fn probe_transport(url: &str) -> TransportVerdict { + let client = match reqwest::Client::builder() + .no_proxy() + .timeout(std::time::Duration::from_secs(3)) + .build() + { + Ok(c) => c, + Err(e) => { + return TransportVerdict { + usable: false, + detail: format!("probe failed: {}", sanitize_node_msg(&e.to_string())), + } + } + }; + let target = format!("{}/", url.trim_end_matches('/')); + match client.get(&target).send().await { + Ok(resp) if resp.status().is_success() => { + let info = resp.json::().await.unwrap_or_default(); + if info["did"].as_str().is_some() { + TransportVerdict { + usable: true, + detail: "reachable".to_string(), + } + } else { + TransportVerdict { + usable: false, + detail: "something is listening but it is not a gitlawb node".to_string(), + } + } + } + Ok(resp) => TransportVerdict { + usable: false, + detail: format!("returned HTTP {}", resp.status()), + }, + Err(e) => TransportVerdict { + usable: false, + detail: format!("unreachable: {}", sanitize_node_msg(&e.to_string())), + }, + } +} + /// Check if a binary name exists anywhere on PATH. /// True when the rc file contains a real `unalias` command naming `gl` — /// not a comment, and not a longer word like `unalias global`. Ordering diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs new file mode 100644 index 000000000..e302e4afe --- /dev/null +++ b/crates/gl/tests/doctor_transport_node.rs @@ -0,0 +1,204 @@ +//! `gl doctor` must diagnose the node the git transport will actually use. +//! +//! `gl`'s `--node` defaults to the public node while `git-remote-gitlawb` falls +//! back to a local one, and an explicit `--node` outranks the environment. So the +//! two disagree whenever GITLAWB_NODE is unset, blank, or overridden, and doctor's +//! own `node` row describes a URL `git clone` and `git push` never contact. + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::process::Command; + +/// Substring that marks the divergence clause. Present only when gl and the git +/// transport resolve different nodes. +const DIVERGENCE: &str = "git push/clone will use"; + +struct Run { + stdout: String, + code: Option, +} + +impl Run { + /// The single output line carrying the divergence clause, so an assertion + /// cannot be satisfied by an unrelated row that happens to print the same URL. + fn divergence_line(&self) -> Option<&str> { + self.stdout.lines().find(|l| l.contains(DIVERGENCE)) + } +} + +fn doctor(env_node: Option<&str>, gl_node: &str) -> Run { + let dir = tempfile::tempdir().unwrap(); + let mut cmd = Command::new(env!("CARGO_BIN_EXE_gl")); + cmd.args(["doctor", "--node", gl_node]) + .arg("--dir") + .arg(dir.path().join("gitlawb")) + // Keep the run off the network: doctor also probes iCaptcha and the + // GitHub release API, neither of which this test is about. + .env("GITLAWB_ICAPTCHA_URL", "http://127.0.0.1:1"); + match env_node { + Some(v) => cmd.env("GITLAWB_NODE", v), + None => cmd.env_remove("GITLAWB_NODE"), + }; + let out = cmd.output().unwrap(); + Run { + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + code: out.status.code(), + } +} + +/// GITLAWB_NODE unset: the helper falls back to the local node, gl targets the +/// public one, so the row must name the local node as the transport target. +#[test] +fn unset_env_reports_the_transport_node() { + let r = doctor(None, "http://127.0.0.1:1"); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no divergence row, got:\n{}", r.stdout)); + assert!( + line.contains(gitlawb_core::DEFAULT_LOCAL_NODE), + "divergence row must name the helper's node, got: {line}" + ); +} + +/// A blank value is not a configured node. The helper must fall back exactly as +/// it does when the variable is absent, and doctor must say so. +#[test] +fn blank_env_is_treated_as_unset() { + for blank in ["", " ", "\t"] { + let r = doctor(Some(blank), "http://127.0.0.1:1"); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no divergence row for {blank:?}, got:\n{}", r.stdout)); + assert!( + line.contains(gitlawb_core::DEFAULT_LOCAL_NODE), + "blank env must resolve to the local default, got: {line}" + ); + } +} + +/// An explicit `--node` outranks the environment, so the transport still goes +/// somewhere gl never probes. This state produced no row at all before. +#[test] +fn explicit_node_flag_overriding_env_is_still_reported() { + let r = doctor(Some("http://127.0.0.1:2"), "http://127.0.0.1:1"); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no divergence row, got:\n{}", r.stdout)); + assert!( + line.contains("127.0.0.1:2"), + "row must name the env-configured transport node, got: {line}" + ); +} + +/// No divergence when both resolve the same node: one row, no clause. +#[test] +fn agreeing_env_and_flag_produce_no_divergence_row() { + let r = doctor(Some("http://127.0.0.1:1"), "http://127.0.0.1:1"); + assert!( + r.divergence_line().is_none(), + "gl and the transport agree; expected no divergence row, got:\n{}", + r.stdout + ); +} + +/// The bug this check exists to prevent, one level down: something answering 200 +/// on the transport port is not proof a gitlawb node is there. Reporting it as a +/// healthy transport is the same false green doctor already shipped once. +#[test] +fn a_non_gitlawb_200_is_not_a_healthy_transport() { + let Ok(listener) = TcpListener::bind("127.0.0.1:0") else { + return; + }; + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming().take(1) { + let Ok(mut s) = stream else { continue }; + // Read the request first. Writing the response without draining the + // request leaves the client seeing a reset rather than a 200, which + // silently turns this test into a probe of the unreachable path. + let mut buf = [0u8; 1024]; + let _ = s.read(&mut buf); + let body = b"not a node"; + let _ = write!( + s, + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = s.write_all(body); + let _ = s.flush(); + } + }); + let r = doctor( + Some(&format!("http://127.0.0.1:{port}")), + "http://127.0.0.1:1", + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no divergence row, got:\n{}", r.stdout)); + // Positive assertion: only the identity check can produce this text, so the + // test cannot pass by the probe quietly failing instead. + assert!( + line.contains("not a gitlawb node"), + "a non-gitlawb 200 must be called out, not reported reachable, got: {line}" + ); +} + +/// Control characters from an attacker-influenceable node URL must not reach the +/// terminal raw, including inside the paste-ready remedy line. +/// +/// Scoped to the rows this check owns. The unchanged `node` row at doctor.rs:180, +/// :199 and :206 still interpolates the raw URL and is a separate pre-existing +/// leak, so asserting over the whole of stdout would fail for a reason this +/// change did not introduce and cannot fix without touching adjacent code. +#[test] +fn control_characters_in_the_node_url_are_stripped() { + let r = doctor(None, "http://127.0.0.1:1/\u{1b}[31m\u{7}\u{202e}"); + let owned: String = r + .stdout + .lines() + .filter(|l| l.contains(DIVERGENCE) || l.trim_start().starts_with("GITLAWB_NODE:")) + .collect::>() + .join("\n"); + assert!( + owned.contains(DIVERGENCE), + "expected the divergence row and its remedy, got:\n{}", + r.stdout + ); + assert!( + !owned.contains('\u{1b}') && !owned.contains('\u{7}') && !owned.contains('\u{202e}'), + "raw control characters reached stdout:\n{owned:?}" + ); +} + +/// #357's tiering: an unset variable is advisory (gl still works), a variable the +/// user set to something unusable is a real failure. Nothing pinned this, and the +/// difference decides whether a stock install exits non-zero once #391 lands. +#[test] +fn unset_env_warns_while_a_broken_configured_node_fails() { + let stock = doctor(None, "http://127.0.0.1:1"); + let line = stock.divergence_line().unwrap(); + assert!( + line.trim_start().starts_with('\u{26a0}'), + "an unset variable must stay advisory on a stock install, got: {line}" + ); + + let misconfigured = doctor(Some("http://127.0.0.1:2"), "http://127.0.0.1:1"); + let line = misconfigured.divergence_line().unwrap(); + assert!( + line.trim_start().starts_with('\u{2717}'), + "a configured but unusable node must fail, got: {line}" + ); +} + +/// #357's constraint: doctor must not start failing a stock install just because +/// it now says more. Nothing pinned this before. +#[test] +fn doctor_still_exits_zero() { + let r = doctor(None, "http://127.0.0.1:1"); + assert_eq!( + r.code, + Some(0), + "doctor must keep exiting 0, got:\n{}", + r.stdout + ); +} From e3359e2dc10a3c4df58ee0355e93a48c3603ccce Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:49:39 -0600 Subject: [PATCH 2/6] fix(gl): probe a prefixed transport base verbatim and sanitize the release tag The transport probe appended a slash to the configured base, so a reverse-proxied https://host/mount that serves identity at /mount failed the new GITLAWB_NODE row. It now requests the base as configured. The release tag from the GITLAWB_GITHUB_API_URL source now goes through the shared terminal sanitizer before it reaches the version row. --- crates/gl/src/doctor.rs | 8 +-- crates/gl/tests/doctor_transport_node.rs | 65 +++++++++++++++++++++++- 2 files changed, 69 insertions(+), 4 deletions(-) diff --git a/crates/gl/src/doctor.rs b/crates/gl/src/doctor.rs index a62d88e56..09c7e3363 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -457,8 +457,10 @@ async fn probe_transport(url: &str) -> TransportVerdict { } } }; - let target = format!("{}/", url.trim_end_matches('/')); - match client.get(&target).send().await { + // Request the configured base verbatim, as the helper's identity lookup does: + // a reverse-proxied `https://host/mount` serves identity at exactly `/mount`, + // and reqwest supplies the `/` for an origin-only URL. + match client.get(url).send().await { Ok(resp) if resp.status().is_success() => { let body = crate::http::read_body_capped(resp, PROBE_BODY_CAP).await; if body.truncated || body.read_failed { @@ -679,7 +681,7 @@ async fn check_version(current: &'static str, github_api_base: &str) -> Check { if is_newer(tag, current) { Check::warn( "version", - format!("v{current} → v{tag} available"), + format!("v{current} → v{} available", sanitize_node_msg(tag)), "curl -sSf https://twigpine.com/install.sh | sh", ) } else { diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs index f323a2f6a..7dbede1fc 100644 --- a/crates/gl/tests/doctor_transport_node.rs +++ b/crates/gl/tests/doctor_transport_node.rs @@ -117,7 +117,9 @@ fn doctor_with(env_node: Option<&str>, node_flag: Option<&str>, extra_env: &[(&s let out = cmd.output().unwrap(); // Under a configured proxy the lookup goes to the proxy fixture, not this one, // so the fixture-boundary check only applies to the unproxied runs. - let proxied = extra_env.iter().any(|(k, _)| *k == "HTTP_PROXY"); + let proxied = extra_env + .iter() + .any(|(k, _)| *k == "HTTP_PROXY" || *k == "GITLAWB_GITHUB_API_URL"); assert!( proxied || release_hits.load(Ordering::SeqCst) >= 1, "the release lookup never reached the fixture, so it went to the public API" @@ -462,3 +464,64 @@ fn an_apostrophe_in_the_node_value_cannot_break_out_of_the_remedy() { "apostrophes must be escaped, got: {fix:?}" ); } + +/// `GITLAWB_NODE` may carry a path prefix (a reverse-proxied `https://host/mount`), +/// with identity served at exactly that prefix and nothing at `/mount/`. The probe +/// must request the configured base verbatim, as the helper does. +#[test] +fn a_path_prefixed_transport_node_is_probed_at_its_exact_base() { + let (port, _) = serve(|_, head| { + if head.starts_with("GET /mount HTTP/1.1") { + did_ok() + } else { + http("404 Not Found", "", b"{}") + } + }); + let r = doctor( + Some(&format!("http://127.0.0.1:{port}/mount")), + "http://127.0.0.1:1", + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no divergence row, got:\n{}", r.stdout)); + assert!(line.contains("(reachable)"), "got: {line}"); +} + +/// A release tag from the configurable API source is untrusted text bound for the +/// terminal. Controls and line breaks in it must not reach stdout. +#[test] +fn a_hostile_release_tag_cannot_reach_the_terminal_raw() { + let body = r#"{"tag_name":"v999.0.0\u001b]0;RELEASE-CONTROL\u0007\nspoofed-row\u202e"}"#; + let (api, hits) = serve(move |_, _| { + http( + "200 OK", + "Content-Type: application/json\r\n", + body.as_bytes(), + ) + }); + let r = doctor_with( + None, + Some("http://127.0.0.1:1"), + &[("GITLAWB_GITHUB_API_URL", &format!("http://127.0.0.1:{api}"))], + ); + assert!(hits.load(Ordering::SeqCst) >= 1, "fixture never hit"); + assert!( + r.stdout.contains("v999.0.0"), + "the version row must still show the tag:\n{}", + r.stdout + ); + for bad in ['\u{1b}', '\u{7}', '\u{202e}'] { + assert!( + !r.stdout.contains(bad), + "control {bad:?} reached stdout:\n{:?}", + r.stdout + ); + } + assert!( + !r.stdout + .lines() + .any(|l| l.trim_start().starts_with("spoofed-row")), + "tag forged an output line:\n{}", + r.stdout + ); +} From 1d6d18126a13d585f3d4990ba11d5a46e58bad76 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:12:13 -0600 Subject: [PATCH 3/6] fix(gl): classify the GITLAWB_NODE row from the env var when gl and transport agree With GITLAWB_NODE unset and --node equal to the transport default, the row passed as a configured loopback node. It now reads the variable itself, so an unset env stays the advisory 'not set' warning. --- crates/gl/src/doctor.rs | 11 +++++++++-- crates/gl/tests/doctor_transport_node.rs | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/gl/src/doctor.rs b/crates/gl/src/doctor.rs index 09c7e3363..d657ef801 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -196,8 +196,15 @@ pub async fn run(args: DoctorArgs) -> Result<()> { let gl_node = sanitize_node_msg(&args.node); if transport_node == args.node { - // gl and the transport agree, so one row covers both. - checks.push(gitlawb_node_env_check(Some(&gl_node))); + // gl and the transport agree, so one row covers both. Classify the row from + // the variable itself: `--node` matching the transport default does not mean + // the user set `GITLAWB_NODE`. + let env_val = env_node + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(sanitize_node_msg); + checks.push(gitlawb_node_env_check(env_val.as_deref())); } else { let verdict = probe_transport(&transport_node).await; let detail = format!( diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs index 7dbede1fc..cbdc419e6 100644 --- a/crates/gl/tests/doctor_transport_node.rs +++ b/crates/gl/tests/doctor_transport_node.rs @@ -184,6 +184,28 @@ fn agreeing_env_and_flag_produce_no_divergence_row() { ); } +/// `--node` equal to the transport default says nothing about whether the user +/// set `GITLAWB_NODE`. With the variable unset the row must stay the advisory +/// "not set" Warn, not a Pass describing a configured loopback node. +#[test] +fn unset_env_with_flag_equal_to_transport_default_still_warns_not_set() { + let r = doctor(None, "http://127.0.0.1:7545"); + let row = r + .stdout + .lines() + .find(|l| l.contains("GITLAWB_NODE")) + .unwrap_or_else(|| panic!("no GITLAWB_NODE row in:\n{}", r.stdout)); + assert!( + row.contains("not set"), + "unset env must report 'not set', got row {row:?} in:\n{}", + r.stdout + ); + assert!( + !row.contains("intentional for self-hosting/dev"), + "unset env must not read as a configured loopback node: {row:?}" + ); +} + /// The bug this check exists to prevent, one level down: something answering 200 /// on the transport port is not proof a gitlawb node is there. Reporting it as a /// healthy transport is the same false green doctor already shipped once. From d2767358fae1877c667011b21ec9754cec963e1b Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:30:52 -0600 Subject: [PATCH 4/6] fix(gl): parse the transport probe body as bytes and dial a trimmed node URL probe_transport read the identity body through the lossy text reader, so a 200 with invalid UTF-8 inside a JSON string parsed and was reported reachable while the helper's strict lookup rejects it. It now parses the original bytes. effective_node_url returned a padded GITLAWB_NODE untrimmed, so the connectivity row dialed ' http://host:port /' while the transport used the trimmed URL. --- crates/gl/src/doctor.rs | 6 +-- crates/gl/tests/doctor_transport_node.rs | 52 ++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/gl/src/doctor.rs b/crates/gl/src/doctor.rs index d657ef801..2f83813fc 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -469,14 +469,14 @@ async fn probe_transport(url: &str) -> TransportVerdict { // and reqwest supplies the `/` for an origin-only URL. match client.get(url).send().await { Ok(resp) if resp.status().is_success() => { - let body = crate::http::read_body_capped(resp, PROBE_BODY_CAP).await; + let body = crate::http::read_body_capped_bytes(resp, PROBE_BODY_CAP).await; if body.truncated || body.read_failed { return TransportVerdict { usable: false, detail: "response too large or incomplete for a gitlawb node".to_string(), }; } - let info = serde_json::from_str::(&body.text).unwrap_or_default(); + let info = serde_json::from_slice::(&body.bytes).unwrap_or_default(); if info["did"].as_str().is_some() { TransportVerdict { usable: true, @@ -540,7 +540,7 @@ fn effective_node_url(node: &str) -> &str { if node.trim().is_empty() { PUBLIC_NODE } else { - node + node.trim() } } diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs index cbdc419e6..de41ad6ff 100644 --- a/crates/gl/tests/doctor_transport_node.rs +++ b/crates/gl/tests/doctor_transport_node.rs @@ -547,3 +547,55 @@ fn a_hostile_release_tag_cannot_reach_the_terminal_raw() { r.stdout ); } + +/// The probe validates the bytes the endpoint sent, not a lossy rendering of them. +/// A 200 whose JSON string carries invalid UTF-8 is not a document the helper's +/// strict identity lookup can read, so it must not be called reachable. A valid +/// control confirms the fixture reaches the identity check at all. +#[test] +fn invalid_utf8_in_the_identity_body_is_not_a_reachable_node() { + let cases: [(&[u8], bool); 3] = [ + (br#"{"did":"did:key:z6MkTestNode","pad":"ok"}"#, true), + ( + b"{\"did\":\"did:key:z6MkTestNode\",\"pad\":\"\xff\"}", + false, + ), + (b"{\"did\":\"did:key:z6Mk\xfeTestNode\"}", false), + ]; + for (body, reachable) in cases { + let served = body.to_vec(); + let (port, _) = + serve(move |_, _| http("200 OK", "Content-Type: application/json\r\n", &served)); + let r = doctor( + Some(&format!("http://127.0.0.1:{port}")), + "http://127.0.0.1:1", + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no divergence row, got:\n{}", r.stdout)); + assert_eq!( + line.contains("(reachable)"), + reachable, + "body {:?}: got: {line}", + String::from_utf8_lossy(body) + ); + } +} + +/// A padded `GITLAWB_NODE` with no `--node` resolves to the trimmed URL for the +/// transport, so the connectivity row must dial the trimmed URL too instead of +/// failing to parse ` http://host:port /`. +#[test] +fn a_padded_env_node_is_dialed_trimmed_by_the_connectivity_row() { + let (port, _) = serve(|_, _| did_ok()); + let r = doctor_with(Some(&format!(" http://127.0.0.1:{port} ")), None, &[]); + let node_row = r + .stdout + .lines() + .find(|l| l.contains("v0.0.0")) + .unwrap_or_else(|| panic!("no passing node row, got:\n{}", r.stdout)); + assert!( + node_row.contains(&format!("http://127.0.0.1:{port}")), + "got: {node_row}" + ); +} From 53aff7de4110563f5cddfe6d4372ca66e905bb66 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:53:24 -0600 Subject: [PATCH 5/6] fix(gl): compare the transport node to the trimmed --node before calling it a divergence --- crates/gl/src/doctor.rs | 4 ++- crates/gl/tests/doctor_transport_node.rs | 31 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/gl/src/doctor.rs b/crates/gl/src/doctor.rs index 2f83813fc..e44bf012a 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -195,7 +195,9 @@ pub async fn run(args: DoctorArgs) -> Result<()> { let transport_node = resolve_transport_node(env_node.as_deref()); let gl_node = sanitize_node_msg(&args.node); - if transport_node == args.node { + // clap binds `args.node` from the environment verbatim, while the resolver + // trims, so compare against the trimmed value or padding alone reads as a split. + if transport_node == args.node.trim() { // gl and the transport agree, so one row covers both. Classify the row from // the variable itself: `--node` matching the transport default does not mean // the user set `GITLAWB_NODE`. diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs index de41ad6ff..94deea7e2 100644 --- a/crates/gl/tests/doctor_transport_node.rs +++ b/crates/gl/tests/doctor_transport_node.rs @@ -599,3 +599,34 @@ fn a_padded_env_node_is_dialed_trimmed_by_the_connectivity_row() { "got: {node_row}" ); } + +/// clap binds `--node` from `GITLAWB_NODE` verbatim, while the transport resolver +/// trims it. A padded value therefore resolves to the same node on both sides, and +/// doctor must not read the whitespace difference as a divergence: no divergence +/// clause, and the env row classified as the configured loopback node (Pass), +/// whether or not that node is up. +#[test] +fn a_padded_env_node_is_not_a_divergence() { + for up in [true, false] { + let port = if up { serve(|_, _| did_ok()).0 } else { 1 }; + let r = doctor_with(Some(&format!(" http://127.0.0.1:{port} ")), None, &[]); + assert!( + r.divergence_line().is_none(), + "padding alone is not a divergence (node up: {up}), got:\n{}", + r.stdout + ); + let row = r + .stdout + .lines() + .find(|l| l.contains("GITLAWB_NODE") && !l.trim_start().starts_with("GITLAWB_NODE:")) + .unwrap_or_else(|| panic!("no GITLAWB_NODE row, got:\n{}", r.stdout)); + assert!( + !row.trim_start().starts_with('\u{2717}'), + "padding alone must not fail the env row (node up: {up}): {row}" + ); + assert!( + row.contains("intentional for self-hosting/dev"), + "a padded loopback env must classify as the configured loopback node (node up: {up}): {row}" + ); + } +} From 6809c602c848d47f9265b60ee17feab5a0d7cddb Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:51:38 -0600 Subject: [PATCH 6/6] fix(gl): make the transport probe take the helper's plaintext, proxy and DID gates probe_transport now refuses a plaintext http node off this machine unless GITLAWB_ALLOW_INSECURE_HTTP opts in, dials a loopback http node without a proxy, and requires the identity to parse as a DID, matching git-remote-gitlawb. The http policy moves to gitlawb_core::transport_policy so both binaries share it. The non-gitlawb-200 test now fails on a bind error, and the shell round-trip test is unix-only. --- crates/git-remote-gitlawb/src/main.rs | 57 +------ crates/gitlawb-core/src/lib.rs | 2 + crates/gitlawb-core/src/transport_policy.rs | 102 ++++++++++++ crates/gl/src/doctor.rs | 42 +++-- crates/gl/tests/doctor_transport_node.rs | 168 ++++++++++++++++++-- 5 files changed, 296 insertions(+), 75 deletions(-) create mode 100644 crates/gitlawb-core/src/transport_policy.rs diff --git a/crates/git-remote-gitlawb/src/main.rs b/crates/git-remote-gitlawb/src/main.rs index 5868ceb74..a80d060e3 100644 --- a/crates/git-remote-gitlawb/src/main.rs +++ b/crates/git-remote-gitlawb/src/main.rs @@ -25,6 +25,7 @@ use anyhow::{bail, Context, Result}; use gitlawb_core::http_sig::sign_request; use gitlawb_core::identity::Keypair; +use gitlawb_core::transport_policy::{allow_insecure_http_value, is_http, is_insecure_remote}; use gitlawb_core::{resolve_transport_node, DEFAULT_LOCAL_NODE}; use std::io::{self, BufRead, Read, Write}; @@ -86,57 +87,6 @@ fn node_base_from_env() -> String { resolve_transport_node(std::env::var("GITLAWB_NODE").ok().as_deref()) } -/// Whether `url` is plaintext http, regardless of where it points. -fn is_http(url: &str) -> bool { - reqwest::Url::parse(url.trim()) - .map(|u| u.scheme() == "http") - .unwrap_or(false) -} - -/// Whether `url` would send git data 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 pack contents and the -/// `Signature` header 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 -} - /// Fixed warning for a `GITLAWB_ALLOW_INSECURE_HTTP` value that is set but not /// truthy. The raw value is never logged. fn warn_allow_insecure_http_non_truthy() { @@ -156,11 +106,10 @@ 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") { + if allow_insecure_http_value(v) { true } else { - if !t.is_empty() { + if !v.trim().is_empty() { warn_allow_insecure_http_non_truthy(); } false diff --git a/crates/gitlawb-core/src/lib.rs b/crates/gitlawb-core/src/lib.rs index 7e262c282..6712b49df 100644 --- a/crates/gitlawb-core/src/lib.rs +++ b/crates/gitlawb-core/src/lib.rs @@ -17,6 +17,8 @@ pub mod node_denial; pub mod redirect; pub mod sanitize; pub mod scan_token; +#[cfg(any(feature = "redirect", test))] +pub mod transport_policy; pub mod ucan; /// Node URL the git transport falls back to when `GITLAWB_NODE` is unset. diff --git a/crates/gitlawb-core/src/transport_policy.rs b/crates/gitlawb-core/src/transport_policy.rs new file mode 100644 index 000000000..0e7e08b33 --- /dev/null +++ b/crates/gitlawb-core/src/transport_policy.rs @@ -0,0 +1,102 @@ +//! The plaintext-http policy the git transport applies to a node URL, shared with +//! `gl doctor` so the diagnostic refuses exactly what the helper refuses. + +/// Whether `url` is plaintext http, regardless of where it points. +pub fn is_http(url: &str) -> bool { + url::Url::parse(url.trim()) + .map(|u| u.scheme() == "http") + .unwrap_or(false) +} + +/// Whether `url` would send git data 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 pack contents and the +/// `Signature` header 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. +pub fn is_insecure_remote(url: &str) -> bool { + let Ok(parsed) = url::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 +} + +/// Whether a non-empty `GITLAWB_ALLOW_INSECURE_HTTP` value opts in: only `1` or +/// `true` (case-insensitive, after trim). Presence alone is not consent. +pub fn allow_insecure_http_value(raw: &str) -> bool { + let t = raw.trim(); + t.eq_ignore_ascii_case("1") || t.eq_ignore_ascii_case("true") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn insecure_remote_is_plaintext_off_this_machine_only() { + for u in [ + "http://node.example.com:7545", + "http://10.0.0.5", + "http://[2001:db8::1]", + ] { + assert!(is_insecure_remote(u), "{u}"); + } + for u in [ + "http://127.0.0.1:7545", + "http://localhost:7545", + "http://[::1]:7545", + "http://[::ffff:127.0.0.1]:7545", + "https://node.example.com", + "not a url", + ] { + assert!(!is_insecure_remote(u), "{u}"); + } + } + + #[test] + fn only_one_or_true_opts_in() { + for v in ["1", " TRUE ", "true"] { + assert!(allow_insecure_http_value(v), "{v:?}"); + } + for v in ["", "0", "false", "yes", "11"] { + assert!(!allow_insecure_http_value(v), "{v:?}"); + } + } + + #[test] + fn is_http_reads_the_scheme_only() { + assert!(is_http("http://127.0.0.1")); + assert!(!is_http("https://127.0.0.1")); + } +} diff --git a/crates/gl/src/doctor.rs b/crates/gl/src/doctor.rs index e44bf012a..5e8f728e9 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -14,6 +14,7 @@ use clap::Args; use std::path::PathBuf; use gitlawb_core::resolve_transport_node; +use gitlawb_core::transport_policy; use crate::http::{sanitize_node_msg, NodeClient}; @@ -443,15 +444,34 @@ fn recovery_target(node: &str) -> String { /// Probe `url` and describe what is actually there. /// -/// This models the git helper, so it takes the helper's network policy: the shared -/// same-origin redirect decision and chain bound, and reqwest's default environment -/// proxy discovery (the helper does not opt out of it either, so a node reachable -/// only through the configured proxy is reachable here, and a loopback node behind a -/// dead proxy is not). It is deliberately not `NodeClient`, because it must not -/// inherit the 30s request timeout, which stalls every stock `gl doctor` run behind -/// a hung listener, and it sends no credentials. +/// This models the git helper, so it takes the helper's transport policy: a +/// plaintext http node off this machine is refused without a request unless +/// `GITLAWB_ALLOW_INSECURE_HTTP` opts in; a loopback http node is dialed directly, +/// never through a proxy; every other node uses reqwest's default environment proxy +/// discovery, as the helper does; redirects follow the shared same-origin decision +/// and chain bound; and the identity must parse as a DID, which the helper requires +/// before it builds a delegation. It is deliberately not `NodeClient`, because it +/// must not inherit the 30s request timeout, which stalls every stock `gl doctor` +/// run behind a hung listener, and it sends no credentials. async fn probe_transport(url: &str) -> TransportVerdict { - let client = match reqwest::Client::builder() + let allow_insecure = std::env::var("GITLAWB_ALLOW_INSECURE_HTTP") + .is_ok_and(|v| transport_policy::allow_insecure_http_value(&v)); + if !allow_insecure && transport_policy::is_insecure_remote(url) { + return TransportVerdict { + usable: false, + detail: "refused: plaintext http to a remote node (use https://, or set \ + GITLAWB_ALLOW_INSECURE_HTTP=1 for a trusted private network)" + .to_string(), + }; + } + let builder = reqwest::Client::builder(); + // The helper's own condition: a loopback http node is never proxied. + let builder = if transport_policy::is_http(url) && !transport_policy::is_insecure_remote(url) { + builder.no_proxy() + } else { + builder + }; + let client = match builder .redirect(reqwest::redirect::Policy::custom( crate::http::same_origin_redirect, )) @@ -479,7 +499,10 @@ async fn probe_transport(url: &str) -> TransportVerdict { }; } let info = serde_json::from_slice::(&body.bytes).unwrap_or_default(); - if info["did"].as_str().is_some() { + if info["did"] + .as_str() + .is_some_and(|d| d.parse::().is_ok()) + { TransportVerdict { usable: true, detail: "reachable".to_string(), @@ -715,6 +738,7 @@ fn is_newer(latest: &str, current: &str) -> bool { mod tests { /// The quoted word must reach a real shell as exactly one value and run nothing /// else, for the inputs that break naive single-quoting. + #[cfg(unix)] #[test] fn shell_single_quote_round_trips_through_sh() { let marker = std::env::temp_dir().join(format!("gl-doctor-quote-{}", std::process::id())); diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs index 94deea7e2..80045f30d 100644 --- a/crates/gl/tests/doctor_transport_node.rs +++ b/crates/gl/tests/doctor_transport_node.rs @@ -53,6 +53,21 @@ fn did_ok() -> Vec { ) } +/// A proxy fixture that answers every request with a DID and counts only the +/// requests naming `target`. Doctor's other rows go through the same proxy +/// variable, so a raw hit count cannot tell the transport probe apart. +fn counting_proxy(target: String) -> (u16, Arc) { + let to_target = Arc::new(AtomicUsize::new(0)); + let counter = to_target.clone(); + let (port, _) = serve(move |_, head| { + if head.lines().next().is_some_and(|l| l.contains(&target)) { + counter.fetch_add(1, Ordering::SeqCst); + } + did_ok() + }); + (port, to_target) +} + /// Substring that marks the divergence clause. Present only when gl and the git /// transport resolve different nodes. const DIVERGENCE: &str = "git push/clone will use"; @@ -211,9 +226,7 @@ fn unset_env_with_flag_equal_to_transport_default_still_warns_not_set() { /// healthy transport is the same false green doctor already shipped once. #[test] fn a_non_gitlawb_200_is_not_a_healthy_transport() { - let Ok(listener) = TcpListener::bind("127.0.0.1:0") else { - return; - }; + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); let port = listener.local_addr().unwrap().port(); std::thread::spawn(move || { for stream in listener.incoming().take(1) { @@ -398,11 +411,14 @@ fn a_request_target_changing_redirect_is_refused() { /// reachable here. #[test] fn a_node_reachable_only_through_the_configured_proxy_is_reachable() { - let (proxy, proxy_hits) = serve(|_, _| did_ok()); + let (proxy, proxy_hits) = counting_proxy("node.invalid".to_string()); let r = doctor_with( Some("http://node.invalid:7545"), Some("http://127.0.0.1:1"), - &[("HTTP_PROXY", &format!("http://127.0.0.1:{proxy}"))], + &[ + ("HTTP_PROXY", &format!("http://127.0.0.1:{proxy}")), + ("GITLAWB_ALLOW_INSECURE_HTTP", "1"), + ], ); let line = r .divergence_line() @@ -414,11 +430,12 @@ fn a_node_reachable_only_through_the_configured_proxy_is_reachable() { ); } -/// Loopback is not exempt from a configured proxy for the helper, so a listener -/// that answers directly but sits behind a dead proxy fails clone/push and must -/// not read as healthy here. +/// The helper builds its client with `no_proxy()` for a loopback http node, so +/// clone/push dial it directly whatever proxy is configured. Doctor must take the +/// same path: a dead proxy cannot make a reachable loopback node read as down, and +/// a live proxy that answers with a DID cannot make an unreachable one read as up. #[test] -fn a_loopback_node_behind_a_dead_proxy_is_not_reported_healthy() { +fn a_loopback_node_is_probed_directly_behind_a_dead_proxy() { let (node, node_hits) = serve(|_, _| did_ok()); let r = doctor_with( Some(&format!("http://127.0.0.1:{node}")), @@ -428,12 +445,139 @@ fn a_loopback_node_behind_a_dead_proxy_is_not_reported_healthy() { let line = r .divergence_line() .unwrap_or_else(|| panic!("no row:\n{}", r.stdout)); - assert!(line.contains("unreachable"), "got: {line}"); + assert!(line.contains("(reachable)"), "got: {line}"); + assert!( + node_hits.load(Ordering::SeqCst) >= 1, + "the probe never reached the loopback node directly" + ); +} + +#[test] +fn a_loopback_node_is_never_sent_through_a_live_proxy() { + let (node, node_hits) = serve(|_, _| did_ok()); + let (proxy, proxy_hits) = counting_proxy(format!("127.0.0.1:{node}")); + let r = doctor_with( + Some(&format!("http://127.0.0.1:{node}")), + Some("http://127.0.0.1:1"), + &[("HTTP_PROXY", &format!("http://127.0.0.1:{proxy}"))], + ); + assert!( + r.divergence_line() + .is_some_and(|l| l.contains("(reachable)")), + "got:\n{}", + r.stdout + ); assert_eq!( - node_hits.load(Ordering::SeqCst), + proxy_hits.load(Ordering::SeqCst), 0, - "the probe bypassed the proxy" + "a loopback probe went through the proxy" + ); + assert!(node_hits.load(Ordering::SeqCst) >= 1); +} + +/// The helper refuses a non-loopback `http://` node before sending anything unless +/// `GITLAWB_ALLOW_INSECURE_HTTP` is truthy. Doctor must report that refusal, as a +/// failure because the user set the variable, and must not contact the node. +#[test] +fn a_plaintext_remote_node_is_refused_like_the_helper_and_never_probed() { + let (proxy, proxy_hits) = counting_proxy("node.invalid".to_string()); + let proxy_env = format!("http://127.0.0.1:{proxy}"); + let r = doctor_with( + Some("http://node.invalid:7545"), + Some("http://127.0.0.1:1"), + &[("HTTP_PROXY", &proxy_env)], ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no row:\n{}", r.stdout)); + assert!( + line.trim_start().starts_with('\u{2717}'), + "a refused configured node must fail, got: {line}" + ); + assert!(line.contains("plaintext"), "got: {line}"); + assert!(!line.contains("(reachable)"), "got: {line}"); + assert_eq!( + proxy_hits.load(Ordering::SeqCst), + 0, + "a refused node must not be contacted" + ); +} + +/// Must-not case for the refusal: an explicit opt-in (and only a truthy one) lifts it. +#[test] +fn the_plaintext_refusal_follows_the_helpers_opt_in_parsing() { + let (proxy, _) = serve(|_, _| did_ok()); + let proxy_env = format!("http://127.0.0.1:{proxy}"); + for (val, allowed) in [ + ("1", true), + (" TRUE ", true), + ("0", false), + ("false", false), + ("", false), + ("yes", false), + ] { + let r = doctor_with( + Some("http://node.invalid:7545"), + Some("http://127.0.0.1:1"), + &[ + ("HTTP_PROXY", &proxy_env), + ("GITLAWB_ALLOW_INSECURE_HTTP", val), + ], + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no row for {val:?}:\n{}", r.stdout)); + assert_eq!( + line.contains("(reachable)"), + allowed, + "opt-in {val:?} gave: {line}" + ); + assert_eq!( + line.contains("plaintext"), + !allowed, + "opt-in {val:?}: {line}" + ); + } +} + +/// An unset variable stays advisory even when the default would be refused, which +/// cannot happen today (the default is loopback), so the tier is pinned on the +/// configured case only; a TLS remote must never trip the refusal. +#[test] +fn an_https_remote_node_is_not_refused() { + let r = doctor_with( + Some("https://node.invalid:7545"), + Some("http://127.0.0.1:1"), + &[], + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no row:\n{}", r.stdout)); + assert!(!line.contains("plaintext"), "got: {line}"); +} + +/// The helper parses the node DID before it will build a UCAN invocation, so an +/// empty or malformed `did` is not a usable identity. +#[test] +fn an_empty_or_malformed_did_is_not_a_healthy_transport() { + for body in [ + r#"{"did":""}"#, + r#"{"did":"not-a-did"}"#, + r#"{"did":"did:unknown:abc"}"#, + ] { + let (port, _) = serve(move |_, _| http("200 OK", "", body.as_bytes())); + let r = doctor( + Some(&format!("http://127.0.0.1:{port}")), + "http://127.0.0.1:1", + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no row for {body}:\n{}", r.stdout)); + assert!( + line.contains("not a gitlawb node"), + "{body} must not read as healthy, got: {line}" + ); + } } /// A valid-looking identity at the head of an oversized body is still an