diff --git a/README.md b/README.md index 99af838..a0ed338 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. -Repository commands use the checkout’s `origin` by default. Use `--remote NAME` to select another remote or `--repo URL` to supply a clone URL. The CLI sends the host and full project path to Proofline, including subgroup names. The CLI recognizes gitlab.com and otherwise looks for a GitHub repository on the exact remote host, including GitHub Enterprise Server. Use `--source-provider gitlab` for private GitLab hosts or `--source-provider git` for other Git servers. Hooks can read the same choice from `PROOFLINE_SOURCE_PROVIDER`. A connected private Git repository can use `proofline review --source-provider git --range BASE..HEAD` to request a review of two pushed commits. +Repository commands use the checkout’s `origin` by default. Use `--remote NAME` to select another remote or `--repo URL` to supply a clone URL. The CLI sends the host and full project path to Proofline, including subgroup names. When Proofline finds no repository on an SSH or scp-style remote's host, the CLI looks again on the host `ssh -G` reports, so a `Host` alias in the SSH configuration, written in the remote or produced by `url..insteadOf`, finds the repository it stands for; `ssh.github.com`, GitHub's SSH over port 443, counts as github.com. When Proofline still finds no repository, the message names the project and each host the CLI looked up. The CLI recognizes gitlab.com and otherwise looks for a GitHub repository on the exact remote host, including GitHub Enterprise Server. Use `--source-provider gitlab` for private GitLab hosts or `--source-provider git` for other Git servers. Hooks can read the same choice from `PROOFLINE_SOURCE_PROVIDER`. A connected private Git repository can use `proofline review --source-provider git --range BASE..HEAD` to request a review of two pushed commits. `proofline review --range BASE..HEAD --fail-on serious` exits 3 when a complete review has an unresolved finding at or above the threshold. PR reviews use the server’s effective open-item counts; other reviews count unresolved findings, including those a partial code assessment recorded. Incomplete and unavailable results retain their nonzero exits. `--fail-on` cannot be combined with `--no-wait`. diff --git a/src/git.rs b/src/git.rs index c88f567..bb577af 100644 --- a/src/git.rs +++ b/src/git.rs @@ -559,6 +559,79 @@ pub(crate) async fn remote_repository(remote: &str) -> Result Option { + let url = url::Url::parse(&format!("ssh://{host}/")).ok()?; + let Some(url::Host::Domain(name)) = url.host() else { + return None; + }; + // A host that starts with `-` would be read as an option, as Git refuses. + if name.starts_with('-') { + return None; + } + let mut command = Command::new("ssh"); + command.arg("-G"); + if let Some(port) = url.port() { + command.arg("-p").arg(port.to_string()); + } + command + .arg("--") + .arg(name) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true); + let output = tokio::time::timeout(SSH_CONFIG_TIMEOUT, command.output()) + .await + .ok()? + .ok()?; + if !output.status.success() { + return None; + } + ssh_destination(name, &String::from_utf8_lossy(&output.stdout)) +} + +/// The `hostname` and `port` in `ssh -G` output, as `parse` writes a host, +/// when they name a different host than `name`. GitHub's SSH over port 443 +/// (`ssh.github.com`) is github.com. +fn ssh_destination(name: &str, config: &str) -> Option { + let value = |key: &str| { + config + .lines() + .find_map(|line| line.strip_prefix(key)?.strip_prefix(' ')) + }; + let hostname = value("hostname")?; + if hostname.is_empty() + || hostname.starts_with('-') + || hostname.contains(|character: char| { + character.is_whitespace() + || character.is_control() + || matches!(character, '/' | '\\' | '?' | '#' | '@') + }) + { + return None; + } + let mut hostname = url::Url::parse(&format!("ssh://{hostname}/")) + .ok()? + .host_str()? + .to_ascii_lowercase(); + let mut port = value("port").and_then(|port| port.parse::().ok()); + if hostname == "ssh.github.com" { + hostname = "github.com".to_owned(); + port = None; + } + if hostname.eq_ignore_ascii_case(name) { + return None; + } + Some(match port { + Some(22) | None => hostname, + Some(port) => format!("{hostname}:{port}"), + }) +} + /// The checkout's `HEAD` commit. pub async fn head() -> Result { let sha = git(&["rev-parse", "--verify", "HEAD^{commit}"]).await?; @@ -578,10 +651,13 @@ pub fn commit_sha(raw: &str) -> Result { /// Coordinates from a clone URL. Only the server can establish whether this /// host and project belong to the selected organization. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct RemoteRepository { pub(crate) host: String, pub(crate) full_name: String, + /// Reached over SSH (an `ssh://` or scp-style URL), where `host` may be an + /// alias in the SSH config. + pub(crate) ssh: bool, } impl RemoteRepository { @@ -624,6 +700,7 @@ impl RemoteRepository { Some(Self { host, full_name: full_name.to_owned(), + ssh: scheme == "ssh", }) } } @@ -653,7 +730,8 @@ mod tests { RemoteRepository::parse("git@gitlab.com:Group/Team/web.git"), Some(RemoteRepository { host: "gitlab.com".to_owned(), - full_name: "Group/Team/web".to_owned() + full_name: "Group/Team/web".to_owned(), + ssh: true, }) ); assert_eq!( @@ -662,11 +740,68 @@ mod tests { .host, "git.example:8443" ); + assert!( + !RemoteRepository::parse("https://github.com/acme/web") + .unwrap() + .ssh + ); + assert!( + RemoteRepository::parse("ssh://git@github.com/acme/web") + .unwrap() + .ssh + ); assert!(RemoteRepository::parse("https://gitlab.com/group/../web.git").is_none()); assert_eq!(full_name("https://github.com/"), None); assert_eq!(full_name("/srv/repo"), None); } + #[test] + fn an_ssh_alias_reads_as_the_host_ssh_connects_to() { + let config = + |hostname: &str, port: &str| format!("user git\nhostname {hostname}\nport {port}\n"); + assert_eq!( + ssh_destination("github-work", &config("github.com", "22")).as_deref(), + Some("github.com") + ); + assert_eq!( + ssh_destination("ghe-work", &config("GHE.example.com", "2222")).as_deref(), + Some("ghe.example.com:2222") + ); + // GitHub's SSH over port 443 reaches github.com, so it is github.com. + assert_eq!( + ssh_destination("github-work", &config("ssh.github.com", "443")).as_deref(), + Some("github.com") + ); + assert_eq!( + ssh_destination("github.com", &config("ssh.github.com", "443")), + None + ); + // A host that is no alias keeps its lookup, whatever port SSH uses. + assert_eq!( + ssh_destination("github.com", &config("github.com", "2222")), + None + ); + assert_eq!( + ssh_destination("GitHub.com", &config("github.com", "22")), + None + ); + // Output that names no usable host leaves the remote's host. + for output in [ + "user git\nport 22\n".to_owned(), + config("", "22"), + config("-oProxyCommand=x", "22"), + config("a b", "22"), + config("evil.example/acme", "22"), + ] { + assert_eq!(ssh_destination("github-work", &output), None, "{output:?}"); + } + } + + #[tokio::test] + async fn ssh_is_never_asked_about_a_host_that_reads_as_an_option() { + assert_eq!(ssh_host("-oProxyCommand=touch").await, None); + } + #[test] fn only_full_commit_shas_are_accepted() { let sha = "A".repeat(40); diff --git a/src/lib.rs b/src/lib.rs index c181cff..54a2b1c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -340,7 +340,17 @@ impl SourceProvider { enum RepositorySelector { Name(String), - Remote(SourceProvider, git::RemoteRepository), + /// A remote, with the provider `--source-provider` named, if any. + Remote(Option, git::RemoteRepository), +} + +/// The provider named, else GitLab on gitlab.com and GitHub on other hosts. +fn provider_for(named: Option, host: &str) -> SourceProvider { + match (named, host) { + (Some(provider), _) => provider, + (None, "gitlab.com") => SourceProvider::Gitlab, + (None, _) => SourceProvider::Github, + } } #[derive(Debug, Args)] @@ -1001,12 +1011,7 @@ async fn repository_selector(args: &RepositoryArgs) -> anyhow::Result git::remote_repository(&args.remote).await?, }; - let provider = match (args.source_provider, remote.host.as_str()) { - (Some(provider), _) => provider, - (None, "gitlab.com") => SourceProvider::Gitlab, - (None, _) => SourceProvider::Github, - }; - Ok(RepositorySelector::Remote(provider, remote)) + Ok(RepositorySelector::Remote(args.source_provider, remote)) } /// The one candidate whose name is `name`, ignoring case, with the name as @@ -1041,15 +1046,67 @@ async fn connected_repository(api: &Api, args: &RepositoryArgs) -> anyhow::Resul resolve_repository(api, args, RepositoryRead::Connected).await } +/// Looks up the repository a remote names on its own host. Git reaches an +/// SSH host through SSH, which may resolve it as an alias, so a host the +/// console doesn't know is tried again as SSH resolves it; a 404 names both. +async fn source( + api: &Api, + provider: Option, + remote: &git::RemoteRepository, + read: RepositoryRead, +) -> anyhow::Result<(String, Uuid)> { + let missing = |error: ApiError, hosts: String| { + let not_found = error.status() == Some(404); + let error = anyhow::Error::new(error); + if not_found { + error.context(format!("looked up {} on host {hosts}", remote.full_name)) + } else { + error + } + }; + let error = match api + .resolve_source(provider_for(provider, &remote.host).as_str(), remote, read) + .await + { + Err(error) if error.status() == Some(404) => error, + result => return Ok(result?), + }; + let ssh_host = if remote.ssh { + git::ssh_host(&remote.host).await + } else { + None + }; + let Some(ssh_host) = ssh_host else { + return Err(missing(error, remote.host.clone())); + }; + let resolved = git::RemoteRepository { + host: ssh_host, + ..remote.clone() + }; + api.resolve_source( + provider_for(provider, &resolved.host).as_str(), + &resolved, + read, + ) + .await + .map_err(|error| { + missing( + error, + format!( + "{} and on host {}, its SSH host", + remote.host, resolved.host + ), + ) + }) +} + async fn resolve_repository( api: &Api, args: &RepositoryArgs, read: RepositoryRead, ) -> anyhow::Result<(String, Uuid)> { match repository_selector(args).await? { - RepositorySelector::Remote(provider, remote) => { - Ok(api.resolve_source(provider.as_str(), &remote, read).await?) - } + RepositorySelector::Remote(provider, remote) => source(api, provider, &remote, read).await, RepositorySelector::Name(name) => match read { RepositoryRead::Connected => connected(api, name, api.repository_names().await?), RepositoryRead::Scan => connected(api, name, api.scan_repository_names().await?), @@ -1107,8 +1164,7 @@ async fn pull_request_runs( ) -> anyhow::Result { let (full_name, repository_id) = match repository_selector(args).await? { RepositorySelector::Remote(provider, remote) => { - api.resolve_source(provider.as_str(), &remote, RepositoryRead::History) - .await? + source(api, provider, &remote, RepositoryRead::History).await? } RepositorySelector::Name(name) => { let (raw, filters) = api.pull_request_reviews(route_name(&name), number).await?; diff --git a/tests/hooks.rs b/tests/hooks.rs index ca3f94a..8198315 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -93,10 +93,20 @@ async fn serve_reads( .route( &format!("/api/v1/organizations/{ORG}/review-repository-source"), get(|Query(query): Query>| async move { - assert_eq!(query["host"], "github.com"); assert_eq!(query["provider"], "github"); assert_eq!(query["full_name"], "acme/web"); - Json(json!({ "repository_id": REPOSITORY })) + // Only github.com holds acme/web, as on the real console. + if query["host"] == "github.com" { + ( + axum::http::StatusCode::OK, + Json(json!({ "repository_id": REPOSITORY })), + ) + } else { + ( + axum::http::StatusCode::NOT_FOUND, + Json(json!({ "detail": "repository not found" })), + ) + } }), ) .route( @@ -919,3 +929,239 @@ async fn the_pre_commit_framework_preserves_selection_policy_and_existing_config assert_eq!(blocked.status.code(), Some(1), "{blocked:?}"); assert!(String::from_utf8_lossy(&blocked.stdout).contains("a finding at or above SERIOUS")); } + +/// `PATH` with a stand-in for `ssh -G` first, and the file it logs each host +/// to. `github-work` is an alias for github.com, `github-443` for GitHub's SSH +/// over port 443, github.com itself uses that port, and other hosts stand +/// for themselves; `gitlab-work` is an alias for gitlab.com. +#[cfg(unix)] +async fn ssh_alias_path(checkout: &Checkout) -> (std::ffi::OsString, PathBuf) { + use std::os::unix::fs::PermissionsExt as _; + let bin = checkout.temporary.path().join("ssh-bin"); + tokio::fs::create_dir_all(&bin).await.unwrap(); + let ssh = bin.join("ssh"); + tokio::fs::write( + &ssh, + "#!/bin/sh\n[ \"$1\" = -G ] || exit 1\nfor host; do :; done\n\ + echo \"$host\" >> \"$(dirname \"$0\")/calls\"\nname=$host port=22\n\ + case $host in\n\ + github-work) name=github.com ;;\n\ + github-443 | github.com) name=ssh.github.com port=443 ;;\n\ + gitlab-work) name=gitlab.com ;;\n\ + esac\n\ + printf 'user git\\nhostname %s\\nport %s\\n' \"$name\" \"$port\"\n", + ) + .await + .unwrap(); + tokio::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)) + .await + .unwrap(); + let path = std::env::join_paths(std::iter::once(bin.clone()).chain(std::env::split_paths( + &std::env::var_os("PATH").unwrap_or_default(), + ))) + .unwrap(); + (path, bin.join("calls")) +} + +/// The CLI with `path` as its `PATH`. +#[cfg(unix)] +async fn proofline_on( + checkout: &Checkout, + path: &std::ffi::OsStr, + origin: &str, + args: &[&str], +) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .env("PROOFLINE_TOKEN", TOKEN) + .env("PATH", path) + .args(["--base-url", origin, "--org", ORG]) + .args(args) + .stdin(std::process::Stdio::null()); + checkout.environment(&mut command); + command.output().await.unwrap() +} + +/// A console that finds no repository on any host, and each lookup it was +/// asked for, in order, as ` `. +async fn serve_missing() -> (String, Arc>>) { + let hosts = Arc::new(Mutex::new(Vec::new())); + let asked = hosts.clone(); + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/review-repository-source"), + get(move |Query(query): Query>| { + asked + .lock() + .unwrap() + .push(format!("{} {}", query["host"], query["provider"])); + async { + ( + axum::http::StatusCode::NOT_FOUND, + Json(json!({ "detail": "repository not found" })), + ) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (origin, hosts) +} + +async fn stage_a_change(checkout: &Checkout) { + tokio::fs::write(checkout.root().join("orders.rs"), "fn main() { retry() }\n") + .await + .unwrap(); + checkout.git(&["add", "orders.rs"]).await; +} + +// GitHub's SSH over port 443 (`Host github.com`, `HostName ssh.github.com`) +// keeps a github.com remote's lookup: the remote's own host comes first, and +// SSH is not asked about a host the console knows. +#[cfg(unix)] +#[tokio::test] +async fn ssh_over_port_443_keeps_the_github_com_lookup() { + let checkout = Checkout::new().await; + let uploads = Uploads::default(); + let origin = serve(uploads.clone(), "WARNING", true).await; + let (path, calls) = ssh_alias_path(&checkout).await; + stage_a_change(&checkout).await; + checkout + .git(&["remote", "set-url", "origin", "git@github.com:acme/web.git"]) + .await; + let output = proofline_on(&checkout, &path, &origin, &["hook", "run", "pre-commit"]).await; + let text = stderr(&output); + assert!(!text.contains("could not review"), "{text}"); + assert_eq!(uploads.lock().unwrap().len(), 1); + assert_eq!( + read(&calls), + None, + "ssh was asked about a host the console knows" + ); +} + +// Git connects through SSH, which resolves an alias in the SSH config, so a +// remote the console doesn't know is looked up again on the host the alias +// stands for: whether the remote names the alias, the alias stands for +// GitHub's SSH over port 443, Git rewrites a github.com remote to it, or +// --repo names it. +#[cfg(unix)] +#[tokio::test] +async fn an_ssh_host_alias_is_looked_up_on_the_host_it_stands_for() { + let checkout = Checkout::new().await; + let uploads = Uploads::default(); + let origin = serve(uploads.clone(), "WARNING", true).await; + let (path, _) = ssh_alias_path(&checkout).await; + stage_a_change(&checkout).await; + let hook = + async || proofline_on(&checkout, &path, &origin, &["hook", "run", "pre-commit"]).await; + let mut outputs = Vec::new(); + for remote in [ + "git@github-work:acme/web.git", + "git@github-443:acme/web.git", + ] { + checkout.git(&["remote", "set-url", "origin", remote]).await; + outputs.push(hook().await); + } + checkout + .git(&["remote", "set-url", "origin", "git@github.com:acme/web.git"]) + .await; + checkout + .git(&[ + "config", + "url.git@github-work:.insteadOf", + "git@github.com:", + ]) + .await; + outputs.push(hook().await); + outputs.push( + proofline_on( + &checkout, + &path, + &origin, + &[ + "review", + "--staged", + "--no-wait", + "--repo", + "git@github-work:acme/web.git", + ], + ) + .await, + ); + for output in &outputs { + let text = stderr(output); + assert!(!text.contains("404"), "{text}"); + assert!(!text.contains("could not review"), "{text}"); + } + assert_eq!(uploads.lock().unwrap().len(), 4); +} + +// When neither the alias nor the host SSH resolves it to holds the +// repository, the message names both, for commands and hooks alike. The +// second lookup guesses the provider from the resolved host, so an alias +// for gitlab.com is looked up as GitLab there. +#[cfg(unix)] +#[tokio::test] +async fn a_repository_missing_on_both_hosts_names_both() { + let checkout = Checkout::new().await; + let (origin, hosts) = serve_missing().await; + let (path, _) = ssh_alias_path(&checkout).await; + stage_a_change(&checkout).await; + for (alias, resolved, provider) in [ + ("github-work", "github.com", "github"), + ("gitlab-work", "gitlab.com", "gitlab"), + ] { + let remote = format!("git@{alias}:acme/web.git"); + checkout + .git(&["remote", "set-url", "origin", &remote]) + .await; + for args in [ + &["hook", "run", "pre-commit"][..], + &["findings", "--pr", "1"], + ] { + hosts.lock().unwrap().clear(); + let text = stderr(&proofline_on(&checkout, &path, &origin, args).await); + let named = format!( + "looked up acme/web on host {alias} and on host {resolved}, its SSH host: " + ); + assert!(text.contains(&named), "{text}"); + assert!(text.contains("HTTP 404: repository not found"), "{text}"); + assert_eq!( + *hosts.lock().unwrap(), + [format!("{alias} github"), format!("{resolved} {provider}")] + ); + } + } +} + +// A host no SSH config resolves is looked up once, as written; when the +// console finds no repository there, the message names the repository and +// host, for commands and hooks alike. +#[tokio::test] +async fn a_repository_the_console_cannot_find_is_named_with_its_host() { + let checkout = Checkout::new().await; + let (origin, hosts) = serve_missing().await; + stage_a_change(&checkout).await; + checkout + .git(&[ + "remote", + "set-url", + "origin", + "git@unknown-alias.invalid:acme/web.git", + ]) + .await; + for args in [ + &["hook", "run", "pre-commit"][..], + &["findings", "--pr", "1"], + ] { + hosts.lock().unwrap().clear(); + let text = stderr(&checkout.proofline(&origin, args, "").await); + assert!( + text.contains("looked up acme/web on host unknown-alias.invalid: "), + "{text}" + ); + assert!(text.contains("HTTP 404: repository not found"), "{text}"); + assert_eq!(*hosts.lock().unwrap(), ["unknown-alias.invalid github"]); + } +}