Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<base>.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`.

Expand Down
139 changes: 137 additions & 2 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,79 @@ pub(crate) async fn remote_repository(remote: &str) -> Result<RemoteRepository,
RemoteRepository::parse(&url).ok_or(GitError::UnknownRemote)
}

/// The most `ssh -G` may take; it reads configuration and does not connect.
const SSH_CONFIG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// The host SSH connects to for `host`, from `ssh -G`, when it differs: an
/// alias's host. `None` when `host` is no alias or SSH cannot say.
pub(crate) async fn ssh_host(host: &str) -> Option<String> {
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<String> {
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::<u16>().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<String, GitError> {
let sha = git(&["rev-parse", "--verify", "HEAD^{commit}"]).await?;
Expand All @@ -578,10 +651,13 @@ pub fn commit_sha(raw: &str) -> Result<String, GitError> {

/// 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 {
Expand Down Expand Up @@ -624,6 +700,7 @@ impl RemoteRepository {
Some(Self {
host,
full_name: full_name.to_owned(),
ssh: scheme == "ssh",
})
}
}
Expand Down Expand Up @@ -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!(
Expand All @@ -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);
Expand Down
80 changes: 68 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SourceProvider>, git::RemoteRepository),
}

/// The provider named, else GitLab on gitlab.com and GitHub on other hosts.
fn provider_for(named: Option<SourceProvider>, host: &str) -> SourceProvider {
match (named, host) {
(Some(provider), _) => provider,
(None, "gitlab.com") => SourceProvider::Gitlab,
(None, _) => SourceProvider::Github,
}
}

#[derive(Debug, Args)]
Expand Down Expand Up @@ -1001,12 +1011,7 @@ async fn repository_selector(args: &RepositoryArgs) -> anyhow::Result<Repository
}
None => 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
Expand Down Expand Up @@ -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<SourceProvider>,
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?),
Expand Down Expand Up @@ -1107,8 +1164,7 @@ async fn pull_request_runs(
) -> anyhow::Result<PullRequestRuns> {
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?;
Expand Down
Loading