Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 24 additions & 56 deletions crates/git-remote-gitlawb/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<()> {
Expand Down Expand Up @@ -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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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}");
Expand All @@ -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::<std::net::IpAddr>() {
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
Expand All @@ -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
Expand Down Expand Up @@ -242,7 +198,7 @@ fn help_text() -> String {
\x20 git clone gitlawb://did:key:z6Mk.../<repo>\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\
Expand Down Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions crates/gitlawb-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> = std::result::Result<T, Error>;

#[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"
);
}
}
102 changes: 102 additions & 0 deletions crates/gitlawb-core/src/transport_policy.rs
Original file line number Diff line number Diff line change
@@ -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::<std::net::IpAddr>() {
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"));
}
}
Loading
Loading