diff --git a/crates/git-remote-gitlawb/src/main.rs b/crates/git-remote-gitlawb/src/main.rs index 599f67c7..a80d060e 100644 --- a/crates/git-remote-gitlawb/src/main.rs +++ b/crates/git-remote-gitlawb/src/main.rs @@ -25,6 +25,8 @@ 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}; fn main() -> Result<()> { @@ -63,9 +65,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(); check_transport_security(&node_base, allow_insecure_http_enabled())?; let repo_base = format!("{}/{}/{}", node_base, short_owner, repo_name); tracing::debug!("repo_base: {repo_base}"); @@ -79,55 +81,10 @@ fn main() -> Result<()> { run_helper(&repo_base, keypair.as_ref()) } -/// 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 +/// 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()) } /// Fixed warning for a `GITLAWB_ALLOW_INSECURE_HTTP` value that is set but not @@ -149,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 @@ -242,7 +198,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, absolute\n\ \x20 (default: ~/.gitlawb/identity.pem). Its parent also\n\ \x20 holds the delegations `gl ucan import` writes.\n\ @@ -2689,9 +2645,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); + } + // ── #369 delete-only push deadlock ─────────────────────────────────────── /// A delete-only receive-pack request ends at the command flush; git then diff --git a/crates/gitlawb-core/src/lib.rs b/crates/gitlawb-core/src/lib.rs index 74f468ce..6712b49d 100644 --- a/crates/gitlawb-core/src/lib.rs +++ b/crates/gitlawb-core/src/lib.rs @@ -17,7 +17,54 @@ 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. +/// +/// `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/gitlawb-core/src/transport_policy.rs b/crates/gitlawb-core/src/transport_policy.rs new file mode 100644 index 00000000..0e7e08b3 --- /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 3406fcb0..5e8f728e 100644 --- a/crates/gl/src/doctor.rs +++ b/crates/gl/src/doctor.rs @@ -13,7 +13,10 @@ use anyhow::Result; use clap::Args; use std::path::PathBuf; -use crate::http::NodeClient; +use gitlawb_core::resolve_transport_node; +use gitlawb_core::transport_policy; + +use crate::http::{sanitize_node_msg, NodeClient}; const PUBLIC_NODE: &str = "https://node.twigpine.com"; const GITHUB_API_BASE: &str = "https://api.github.com"; @@ -183,9 +186,56 @@ pub async fn run(args: DoctorArgs) -> Result<()> { } // ── 3. GITLAWB_NODE env var ─────────────────────────────────────────── - checks.push(gitlawb_node_env_check( - std::env::var("GITLAWB_NODE").ok().as_deref(), - )); + // 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); + + // 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`. + 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!( + "git push/clone will use {} ({}); gl targets {gl_node}", + sanitize_node_msg(&transport_node), + verdict.detail + ); + // The remedy is shell input, so it is built from the canonical value and + // quoted for the shell. The display string above is capped and stripped for + // the terminal, which is a different encoding and must not be reused here. + let fix = format!( + "export GITLAWB_NODE={}", + shell_single_quote(&recovery_target(&args.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)); + } + } // ── 4. Node connectivity ────────────────────────────────────────────── // GITLAWB_NODE="" binds args.node to "" through clap, and check 3 groups @@ -301,7 +351,13 @@ pub async fn run(args: DoctorArgs) -> Result<()> { // ── 7. Version up to date ───────────────────────────────────────────── let current = env!("CARGO_PKG_VERSION"); - checks.push(check_version(current, GITHUB_API_BASE).await); + // Production uses the real endpoint; the override exists so the subprocess tests + // can route the release lookup to a local fixture instead of the public API. + let github_api = std::env::var("GITLAWB_GITHUB_API_URL") + .ok() + .filter(|v| !v.trim().is_empty()) + .unwrap_or_else(|| GITHUB_API_BASE.to_string()); + checks.push(check_version(current, &github_api).await); // ── Render ──────────────────────────────────────────────────────────── for check in &checks { @@ -353,6 +409,122 @@ 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, +} + +/// Cap on the root document the probe reads. A gitlawb node's `/` is a few hundred +/// bytes of identity; anything near this size is not one. +const PROBE_BODY_CAP: usize = 16 * 1024; + +/// Quote `s` as one POSIX shell word. Single quotes are the only construct that +/// needs care inside single quotes: close, emit an escaped quote, reopen. +fn shell_single_quote(s: &str) -> String { + format!("'{}'", s.replace('\'', r"'\''")) +} + +/// The value the remedy tells the user to export, taken from the normalized node +/// (blank means the public node, as for the connectivity probe) and not truncated. +/// A value carrying terminal control characters is not something to hand back for +/// pasting, so the public node stands in for it. +fn recovery_target(node: &str) -> String { + let target = effective_node_url(node).trim(); + if gitlawb_core::sanitize::strip_terminal_controls(target) == target { + target.to_string() + } else { + PUBLIC_NODE.to_string() + } +} + +/// Probe `url` and describe what is actually there. +/// +/// 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 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, + )) + .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())), + } + } + }; + // 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_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_slice::(&body.bytes).unwrap_or_default(); + if info["did"] + .as_str() + .is_some_and(|d| d.parse::().is_ok()) + { + 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())), + }, + } +} + /// Classify the `GITLAWB_NODE` env var for `gl doctor`. Extracted so unit /// tests can pin the Warn tier directly (#357): an unset env is advisory, not /// a failure, because `--node` defaults to `https://node.twigpine.com` and the @@ -393,7 +565,7 @@ fn effective_node_url(node: &str) -> &str { if node.trim().is_empty() { PUBLIC_NODE } else { - node + node.trim() } } @@ -541,7 +713,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 { @@ -564,6 +736,50 @@ fn is_newer(latest: &str, current: &str) -> bool { #[cfg(test)] 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())); + let cases = [ + "plain".to_string(), + "it's".to_string(), + "x'; touch MARK; #'".to_string(), + "has space and $HOME `id` $(id) ;|&".to_string(), + "'".to_string(), + "https://example.com/".to_string() + &"a".repeat(500), + ]; + for value in cases { + let value = value.replace("MARK", marker.to_str().unwrap()); + let script = format!("X={}; printf %s \"$X\"", shell_single_quote(&value)); + let out = std::process::Command::new("sh") + .arg("-c") + .arg(&script) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&out.stdout), + value, + "round trip failed for {value:?}" + ); + assert!(!marker.exists(), "quoting let a command run for {value:?}"); + } + } + + #[test] + fn recovery_target_uses_normalized_state_and_keeps_the_full_value() { + assert_eq!(recovery_target(""), PUBLIC_NODE); + assert_eq!(recovery_target(" "), PUBLIC_NODE); + assert_eq!(recovery_target(" http://h:1 "), "http://h:1"); + // Control characters are rejected, not stripped into a different value. + assert_eq!(recovery_target("http://h:1/\u{1b}[31m"), PUBLIC_NODE); + assert_eq!(recovery_target("http://h:1/\u{202e}"), PUBLIC_NODE); + // Longer than the 200 character display cap, still whole. + let long = format!("http://h:1/{}", "a".repeat(300)); + assert_eq!(recovery_target(&long), long); + } + use super::*; fn fake_home(zshrc: Option<&str>, with_omz_git: bool) -> tempfile::TempDir { diff --git a/crates/gl/src/http.rs b/crates/gl/src/http.rs index 75763a4e..aa7aba42 100644 --- a/crates/gl/src/http.rs +++ b/crates/gl/src/http.rs @@ -54,7 +54,9 @@ const TOTAL_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_sec /// consulting the policy, so on the first redirect `previous.len()` is already 1, and /// `>=` would permit `MAX_REDIRECTS - 1` follows. `Policy::limited(max)` refuses at /// `previous.len() > max`, and matching it is the point of reusing its value. -fn same_origin_redirect(attempt: reqwest::redirect::Attempt<'_>) -> reqwest::redirect::Action { +pub(crate) fn same_origin_redirect( + attempt: reqwest::redirect::Attempt<'_>, +) -> reqwest::redirect::Action { let Some(previous) = attempt.previous().last() else { // No previous URL to compare against. Unreachable through reqwest, which // pushes the redirecting URL before consulting the policy, but the safe diff --git a/crates/gl/tests/doctor_transport_node.rs b/crates/gl/tests/doctor_transport_node.rs new file mode 100644 index 00000000..80045f30 --- /dev/null +++ b/crates/gl/tests/doctor_transport_node.rs @@ -0,0 +1,776 @@ +//! `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; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +const DID_BODY: &str = r#"{"did":"did:key:z6MkTestNode","version":"0.0.0"}"#; + +/// A request-counting HTTP fixture. `handler(hit_index, request_head)` returns the +/// raw bytes to write back. Runs for the life of the test process, one connection +/// at a time, which is all these probes need. +fn serve(handler: impl Fn(usize, &str) -> Vec + Send + 'static) -> (u16, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture"); + let port = listener.local_addr().unwrap().port(); + let hits = Arc::new(AtomicUsize::new(0)); + let seen = hits.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut s) = stream else { continue }; + let mut buf = [0u8; 4096]; + let n = s.read(&mut buf).unwrap_or(0); + let head = String::from_utf8_lossy(&buf[..n]).into_owned(); + let i = seen.fetch_add(1, Ordering::SeqCst); + let _ = s.write_all(&handler(i, &head)); + let _ = s.flush(); + } + }); + (port, hits) +} + +fn http(status: &str, extra: &str, body: &[u8]) -> Vec { + let mut out = format!( + "HTTP/1.1 {status}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .into_bytes(); + out.extend_from_slice(body); + out +} + +fn did_ok() -> Vec { + http( + "200 OK", + "Content-Type: application/json\r\n", + DID_BODY.as_bytes(), + ) +} + +/// 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"; + +struct Run { + stdout: String, +} + +const PROXY_VARS: [&str; 8] = [ + "HTTP_PROXY", + "http_proxy", + "HTTPS_PROXY", + "https_proxy", + "ALL_PROXY", + "all_proxy", + "NO_PROXY", + "no_proxy", +]; + +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 { + doctor_with(env_node, Some(gl_node), &[]) +} + +/// `node_flag: None` runs without `--node`, so clap binds `args.node` from the +/// environment exactly as a user's shell would. +fn doctor_with(env_node: Option<&str>, node_flag: Option<&str>, extra_env: &[(&str, &str)]) -> Run { + // The release lookup goes to a local fixture, so no run reaches api.github.com. + // The hit count is asserted below: if the override stops being honored the + // request escapes, the fixture sees nothing, and every test here fails. + let (release_port, release_hits) = serve(|_, _| http("404 Not Found", "", b"{}")); + let dir = tempfile::tempdir().unwrap(); + let mut cmd = Command::new(env!("CARGO_BIN_EXE_gl")); + cmd.arg("doctor"); + if let Some(n) = node_flag { + cmd.args(["--node", n]); + } + cmd.arg("--dir") + .arg(dir.path().join("gitlawb")) + .env("GITLAWB_ICAPTCHA_URL", "http://127.0.0.1:1") + .env( + "GITLAWB_GITHUB_API_URL", + format!("http://127.0.0.1:{release_port}"), + ); + for v in PROXY_VARS { + cmd.env_remove(v); + } + for (k, v) in extra_env { + cmd.env(k, v); + } + match env_node { + Some(v) => cmd.env("GITLAWB_NODE", v), + None => cmd.env_remove("GITLAWB_NODE"), + }; + 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" || *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" + ); + Run { + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + } +} + +/// 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 + ); +} + +/// `--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. +#[test] +fn a_non_gitlawb_200_is_not_a_healthy_transport() { + 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) { + 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, as it reads once doctor exits non-zero on any Fail-class row: +/// an unset variable must not contribute one. The run still exits 1 here because +/// the empty tempdir has no identity, so assert on the rows, not the exit code. +#[test] +fn an_unset_env_adds_no_failing_row() { + let r = doctor(None, "http://127.0.0.1:1"); + let failing: Vec<&str> = r + .stdout + .lines() + .filter(|l| l.trim_start().starts_with('\u{2717}')) + .collect(); + assert!( + failing.iter().all(|l| !l.contains("GITLAWB_NODE")), + "an unset variable must stay advisory, got failing rows: {failing:?}" + ); + assert!(r.divergence_line().is_some(), "got:\n{}", r.stdout); +} + +/// The suggested fix line printed under "Suggested fixes", or the empty string. +fn fix_line(r: &Run) -> &str { + r.stdout + .lines() + .find(|l| l.trim_start().starts_with("GITLAWB_NODE:")) + .unwrap_or("") +} + +/// A same-origin redirect that re-issues the identical request-target is the one +/// shape the transport follows, so doctor must follow it too and report the node. +#[test] +fn an_identical_target_redirect_is_followed_like_the_transport() { + let (port, _) = serve(|i, _| { + if i < 2 { + http("302 Found", "Location: /\r\n", b"") + } else { + did_ok() + } + }); + 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:\n{}", r.stdout)); + assert!(line.contains("(reachable)"), "got: {line}"); +} + +/// The transport stops at a redirect to another origin, so a node that redirects +/// `/` elsewhere is not a working transport and the other origin is never contacted. +#[test] +fn a_cross_origin_redirect_is_refused_and_never_contacted() { + let (other, other_hits) = serve(|_, _| did_ok()); + let (port, _) = serve(move |_, _| { + http( + "302 Found", + &format!("Location: http://127.0.0.1:{other}/\r\n"), + b"", + ) + }); + 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:\n{}", r.stdout)); + assert!( + line.contains("HTTP 302"), + "a refused redirect surfaces the 3xx, got: {line}" + ); + assert!(!line.contains("(reachable)"), "got: {line}"); + assert_eq!( + other_hits.load(Ordering::SeqCst), + 0, + "the redirect target was contacted" + ); +} + +/// Same origin but a different request-target is also refused by the transport. +#[test] +fn a_request_target_changing_redirect_is_refused() { + let (port, _) = serve(|i, _| { + if i == 0 { + http("302 Found", "Location: /elsewhere\r\n", b"") + } else { + did_ok() + } + }); + 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:\n{}", r.stdout)); + assert!(line.contains("HTTP 302"), "got: {line}"); +} + +/// The helper keeps reqwest's environment proxy discovery, so a node that is only +/// reachable through the configured proxy works for clone/push and must read as +/// reachable here. +#[test] +fn a_node_reachable_only_through_the_configured_proxy_is_reachable() { + 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}")), + ("GITLAWB_ALLOW_INSECURE_HTTP", "1"), + ], + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no row:\n{}", r.stdout)); + assert!(line.contains("(reachable)"), "got: {line}"); + assert!( + proxy_hits.load(Ordering::SeqCst) >= 1, + "the probe bypassed the proxy" + ); +} + +/// 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_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}")), + Some("http://127.0.0.1:1"), + &[("HTTP_PROXY", "http://127.0.0.1:1")], + ); + let line = r + .divergence_line() + .unwrap_or_else(|| panic!("no row:\n{}", r.stdout)); + 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!( + proxy_hits.load(Ordering::SeqCst), + 0, + "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 +/// unbounded read, so it is rejected rather than parsed. +#[test] +fn an_oversized_probe_body_is_rejected_not_parsed() { + let mut body = String::from(r#"{"did":"did:key:z6MkTestNode","pad":""#); + body.push_str(&"A".repeat(2 * 1024 * 1024)); + body.push_str("\"}"); + let (port, _) = serve(move |_, _| { + http( + "200 OK", + "Content-Type: application/json\r\n", + 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:\n{}", r.stdout)); + assert!(line.contains("too large"), "got: {line}"); + assert!(!line.contains("(reachable)"), "got: {line}"); +} + +/// Blank GITLAWB_NODE with no `--node`: clap hands doctor the raw blank value, and +/// the remedy must not reproduce it. It names the public node instead. +#[test] +fn a_blank_env_remedy_does_not_reproduce_the_blank_value() { + for blank in [" ", "\t"] { + let r = doctor_with(Some(blank), None, &[]); + let fix = fix_line(&r); + assert!( + fix.contains("export GITLAWB_NODE='https://node.twigpine.com'"), + "blank {blank:?} must be replaced by a valid target, got: {fix:?}\n{}", + r.stdout + ); + } +} + +/// A node value with an apostrophe must not close the quoting and run what follows. +#[test] +fn an_apostrophe_in_the_node_value_cannot_break_out_of_the_remedy() { + let r = doctor(None, "http://127.0.0.1:1/x'; touch /tmp/pwned; #'"); + let fix = fix_line(&r); + assert!( + fix.contains(r#"'http://127.0.0.1:1/x'\''; touch /tmp/pwned; #'\'''"#), + "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 + ); +} + +/// 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}" + ); +} + +/// 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}" + ); + } +}