use super::env::BatchSsh;
use super::{CliError, Contact, Direction};
#[derive(Clone, Debug)]
pub(super) struct Reach {
pub(super) ssh: bool,
pub(super) helper: bool,
pub(super) unread: Option<CliError>,
}
type RemoteUrlList = Vec<((String, Direction), String)>;
pub(super) fn parse_remote_urls(listing: &str, names: &[&str]) -> Result<RemoteUrlList, CliError> {
let mut folded: RemoteUrlList = Vec::new();
for line in listing.lines() {
let name = names
.iter()
.filter(|name| {
line.strip_prefix(**name)
.is_some_and(|rest| rest.starts_with('\t'))
})
.max_by_key(|name| name.len());
let Some(&name) = name else {
return Err(CliError::new(format!(
"unparseable `git remote -v` line {line:?}"
)));
};
let rest = &line[name.len() + 1..];
if rest.trim().is_empty() {
continue;
}
let rest = rest
.strip_suffix(']')
.and_then(|head| head.rsplit_once(" ["))
.map(|(head, _)| head)
.filter(|head| head.ends_with(" (fetch)"))
.unwrap_or(rest);
let parsed = if let Some(url) = rest.strip_suffix(" (fetch)") {
Some((url, Direction::Fetch))
} else {
rest.strip_suffix(" (push)")
.map(|url| (url, Direction::Push))
};
let Some((url, direction)) = parsed else {
return Err(CliError::new(format!(
"unparseable `git remote -v` line {line:?}"
)));
};
let key = (name.to_owned(), direction);
match folded.iter_mut().find(|(entry, _)| *entry == key) {
Some((_, urls)) => {
urls.push('\n');
urls.push_str(url);
}
None => folded.push((key, url.to_owned())),
}
}
Ok(folded)
}
pub(super) fn classify(urls: Result<&str, &CliError>) -> Reach {
match urls {
Ok(urls) => Reach {
ssh: urls.lines().any(reaches_over_ssh),
helper: urls.lines().any(runs_a_helper),
unread: None,
},
Err(err) => {
let detail = err.detail();
Reach {
ssh: false,
helper: false,
unread: Some(CliError::new(format!(
"oakum could not read that remote's URL ({detail})"
))),
}
}
}
}
pub(super) fn notes_for(contact: Contact<'_>, reach: &Reach, batch: &BatchSsh) -> Vec<String> {
let remote = contact.remote;
let reason = batch.unprotected_reason();
let mut notes = Vec::new();
if reach.helper {
let mut note = format!(
"the remote {remote:?} runs a helper command oakum cannot inspect; \
its ssh `BatchMode` does not reach whatever that helper runs, so \
a prompt can still block."
);
if let Some(reason) = reason {
use std::fmt::Write;
let _ = write!(
note,
" The ssh transport could not be protected either: {reason}."
);
}
notes.push(note);
}
if let Some(why) = &reach.unread {
let mut note = format!(
"oakum could not establish what transport {remote:?} uses ({why}); \
if the remote runs a helper, a prompt may still block."
);
if let Some(reason) = reason {
use std::fmt::Write;
let _ = write!(
note,
" The ssh transport could not be protected either: {reason}."
);
}
notes.push(note);
}
if let Some(reason) = reason {
if reach.ssh {
notes.push(format!(
"oakum cannot refuse ssh prompts for the transport {remote:?} \
uses: {reason}. A prompt can still block."
));
}
}
notes
}
fn reaches_over_ssh(url: &str) -> bool {
if let Some((scheme, _)) = url.split_once("://") {
return matches!(scheme, "ssh" | "git+ssh" | "ssh+git");
}
let Some(at) = scp_separator(url) else {
return false;
};
if url[at..].starts_with("::") {
return false;
}
!dos_drive(&url[..at])
}
fn runs_a_helper(url: &str) -> bool {
if names_a_helper(url) {
return true;
}
match url.split_once("://") {
Some((scheme, _)) => !matches!(
scheme,
"ssh" | "git+ssh" | "ssh+git" | "http" | "https" | "git" | "file" | "ftp" | "ftps"
),
None => false,
}
}
fn names_a_helper(url: &str) -> bool {
scp_separator(url).is_some_and(|at| url[at..].starts_with("::"))
}
fn scp_separator(url: &str) -> Option<usize> {
let mut bracketed = false;
for (at, character) in url.char_indices() {
match character {
'[' if url[at..].contains(']') => bracketed = true,
']' => bracketed = false,
':' if !bracketed => return Some(at),
'/' => return None,
_ => {}
}
}
None
}
fn dos_drive(host: &str) -> bool {
cfg!(windows) && host.len() == 1 && host.starts_with(|first: char| first.is_ascii_alphabetic())
}
#[cfg(test)]
mod tests {
use super::super::Direction;
use super::*;
#[test]
fn only_an_ssh_remote_can_stop_at_an_ssh_prompt() {
for url in [
"ssh://git@github.com/oakoss/oakum.git",
"git+ssh://git@github.com/oakoss/oakum.git",
"ssh+git://git@github.com/oakoss/oakum.git",
"git@github.com:oakoss/oakum.git",
"github.com:oakoss/oakum.git",
] {
assert!(reaches_over_ssh(url), "{url} reaches git over ssh");
}
#[cfg(not(windows))]
assert!(
reaches_over_ssh("x:oakum.git"),
"a single-letter host is a host off Windows"
);
#[cfg(windows)]
assert!(
!reaches_over_ssh("x:oakum.git"),
"a single-letter prefix is a drive on Windows"
);
for url in [
"SSH://git@github.com/oakoss/oakum.git",
"https://github.com/oakoss/oakum.git",
"http://github.com/oakoss/oakum.git",
"git://github.com/oakoss/oakum.git",
"file:///srv/mirrors/oakum.git",
"/srv/mirrors/oakum.git",
"../sibling.git",
"./odd:name.git",
] {
assert!(!reaches_over_ssh(url), "{url} does not use ssh");
}
}
#[test]
fn helper_syntax_is_not_ssh_but_an_empty_host_is() {
for url in [
":oakum.git",
"[::1]:demo.git",
"foo[bar:baz",
"a[b:c",
"user@[::1]:repo.git",
"git@[2001:db8::1]:oakum.git",
] {
assert!(reaches_over_ssh(url), "{url} reaches git over ssh");
}
for url in ["a::b", "::a"] {
assert!(!reaches_over_ssh(url), "{url} names a remote helper");
}
}
#[test]
fn a_helper_remote_is_unestablished_rather_than_not_ssh() {
for url in ["a::b", "::a", "ext::ssh -p 22 git@h git-upload-pack r.git"] {
assert!(names_a_helper(url), "{url} names a helper");
assert!(!reaches_over_ssh(url), "{url} is not itself an ssh URL");
}
for url in [
"git@github.com:oakoss/oakum.git",
"https://github.com/oakoss/oakum.git",
"ssh://git@github.com/oakoss/oakum.git",
"/srv/mirrors/oakum.git",
] {
assert!(!names_a_helper(url), "{url} names no helper");
}
}
#[cfg(not(windows))]
#[test]
fn a_drive_letter_is_a_hostname_off_windows() {
assert!(reaches_over_ssh(r"C:\repos\oakum"));
assert!(reaches_over_ssh("C:/repos/oakum"));
}
#[cfg(windows)]
#[test]
fn a_drive_letter_is_a_path_on_windows() {
assert!(!reaches_over_ssh(r"C:\repos\oakum"));
assert!(!reaches_over_ssh("C:/repos/oakum"));
assert!(!reaches_over_ssh("x:oakum.git"));
}
#[test]
fn the_listing_keeps_fetch_and_push_urls_apart() {
let names = ["origin", "s", "pushonly"];
let listing = "origin\thttps://host/r.git (fetch)\n\
origin\tgit@host:r.git (push)\n\
origin\thelper::two (push)";
let parsed = parse_remote_urls(listing, &names).expect("parses");
let urls = |direction: Direction| {
parsed
.iter()
.find(|((name, at), _)| name == "origin" && *at == direction)
.map(|(_, urls)| urls.as_str())
.expect("listed")
};
assert!(!classify(Ok(urls(Direction::Fetch))).ssh);
assert!(classify(Ok(urls(Direction::Push))).ssh);
let err = parse_remote_urls("origin\thttps://host/r.git (fetched)", &names)
.expect_err("an unknown marker fails the parse");
assert!(err.to_string().contains("unparseable"), "{err}");
let err = parse_remote_urls("stranger\thttps://host/r.git (fetch)", &names)
.expect_err("a name outside the configured set fails the parse");
assert!(err.to_string().contains("unparseable"), "{err}");
let spaced = parse_remote_urls("s\text::sh -c \"echo hi\" (fetch)", &names)
.expect("whitespace in a URL survives");
assert_eq!(spaced[0].1, "ext::sh -c \"echo hi\"");
let partial = parse_remote_urls(
"pushonly\t\npushonly\tgit@host:r.git (push)\norigin\thttps://host/r.git (fetch)",
&names,
)
.expect("a bare direction line is absence, not failure");
assert_eq!(partial.len(), 2, "{partial:?}");
let filtered = parse_remote_urls(
"origin\tfile:///srv/r.git (fetch) [blob:none]\norigin\tfile:///srv/r.git (push)",
&names,
)
.expect("a partial clone's filter rides its fetch line");
assert_eq!(filtered[0].1, "file:///srv/r.git", "{filtered:?}");
}
#[test]
fn an_unread_url_is_never_classed_as_safe() {
let failed = CliError::new("git exited 128");
let unread = classify(Err(&failed));
assert!(unread.unread.is_some() && !unread.ssh && !unread.helper);
let helper = classify(Ok("ext::my-helper"));
assert!(helper.helper && !helper.ssh);
assert!(classify(Ok("marker://addr")).helper);
assert!(classify(Ok("SSH://host/r.git")).helper);
let ssh = classify(Ok("git@host:r.git"));
assert!(ssh.ssh && !ssh.helper);
let plain = classify(Ok("https://host/r.git"));
assert!(!plain.ssh && !plain.helper && plain.unread.is_none());
assert!(!classify(Ok("ftps://host/r.git")).helper);
let mixed = classify(Ok("ssh://host/a.git\nmarker://b"));
assert!(mixed.ssh && mixed.helper);
}
#[test]
fn the_note_table_covers_every_reach_and_both_transport_columns() {
let origin = Contact {
remote: "origin",
direction: Direction::Fetch,
};
let composed = BatchSsh::Composed(String::from("ssh -o BatchMode=yes"));
let unprotected = BatchSsh::Unprotected(String::from("ssh.variant is opaque"));
let plain = Reach {
ssh: false,
helper: false,
unread: None,
};
let ssh_only = Reach {
ssh: true,
..plain.clone()
};
let helper_only = Reach {
helper: true,
..plain.clone()
};
let unread = Reach {
unread: Some(CliError::new("could not read that remote's URL")),
..plain.clone()
};
let notes = notes_for(origin, &plain, &composed);
assert!(notes.is_empty(), "{notes:?}");
let notes = notes_for(origin, &plain, &unprotected);
assert!(notes.is_empty(), "{notes:?}");
let notes = notes_for(origin, &ssh_only, &composed);
assert!(notes.is_empty(), "{notes:?}");
let unread_composed = notes_for(origin, &unread, &composed);
assert_eq!(unread_composed.len(), 1, "{unread_composed:?}");
assert!(
unread_composed[0].contains("could not establish what transport"),
"{unread_composed:?}"
);
assert!(
unread_composed[0].contains("may still block"),
"{unread_composed:?}"
);
assert!(
!unread_composed[0].contains("could not be protected"),
"a composed transport owes no transport rider: {unread_composed:?}"
);
let helper_composed = notes_for(origin, &helper_only, &composed);
assert_eq!(helper_composed.len(), 1, "{helper_composed:?}");
assert!(
helper_composed[0].contains("\"origin\""),
"{helper_composed:?}"
);
assert!(helper_composed[0].contains("helper"), "{helper_composed:?}");
assert!(
helper_composed[0].contains("can still block"),
"{helper_composed:?}"
);
let helper_unprotected = notes_for(origin, &helper_only, &unprotected);
assert_eq!(helper_unprotected.len(), 1, "{helper_unprotected:?}");
assert!(
helper_unprotected[0].contains("ssh.variant is opaque"),
"the transport reason must not be dropped: {helper_unprotected:?}"
);
let ssh = notes_for(origin, &ssh_only, &unprotected);
assert_eq!(ssh.len(), 1, "{ssh:?}");
assert!(ssh[0].contains("\"origin\""), "{}", ssh[0]);
assert!(ssh[0].contains("ssh.variant is opaque"), "{}", ssh[0]);
assert!(ssh[0].contains("cannot refuse ssh prompts"), "{}", ssh[0]);
assert!(ssh[0].contains("can still block"), "{}", ssh[0]);
let hedged = notes_for(origin, &unread, &unprotected);
assert_eq!(hedged.len(), 1, "{hedged:?}");
assert!(hedged[0].contains("may still block"), "{}", hedged[0]);
assert!(
hedged[0].contains("could not read that remote's URL"),
"the note must say why it could not tell: {}",
hedged[0]
);
assert!(
hedged[0].contains("could not be protected either"),
"an unprotected transport adds its reason: {}",
hedged[0]
);
assert_ne!(ssh[0], hedged[0], "a guess must not read as a finding");
let both = Reach {
ssh: true,
helper: true,
unread: None,
};
let notes = notes_for(origin, &both, &unprotected);
assert_eq!(notes.len(), 2, "{notes:?}");
let notes = notes_for(origin, &both, &composed);
assert_eq!(notes.len(), 1, "{notes:?}");
assert!(notes[0].contains("helper"), "{notes:?}");
}
}