Skip to content

Commit 950dea9

Browse files
agorischekCopilot
andauthored
CLI: a workflow GitHub can't read is an error, not an ineligible workflow (#91)
--ci's default policy accepts a run when its workflow file on the default branch uses the Projections Action. The lookup treated every gh failure (authentication, rate limits, transport) as 'doesn't use the Action', cached it, and reported no CI output. Now only GitHub's 404 (the file is absent there) means ineligible; any other failure is reported, through accepted() to download() and attested(), and isn't cached. Code review, finding 3. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent c9204c7 commit 950dea9

2 files changed

Lines changed: 84 additions & 22 deletions

File tree

‎packages/cli/src/ci_artifacts/github.rs‎

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@
1010
//! whose file on the default branch uses `githubnext/projections`.
1111
1212
use super::Origin;
13-
use crate::{artifact, runtime::Runner};
13+
use crate::{
14+
artifact,
15+
runtime::{ProcessFailure, Runner},
16+
};
1417
use anyhow::{Context, Result};
1518
use serde_json::{Value, json};
1619
use std::{
@@ -89,37 +92,45 @@ impl<'a> GitHub<'a> {
8992

9093
/// The workflow file of `run` (an Actions run from GitHub's API) when its
9194
/// artifact is this repository's own CI output, with the basis it was
92-
/// accepted on ([`Basis`]), else `None`.
93-
pub fn accepted(&self, run: &Value) -> Option<(String, Basis)> {
94-
let workflow = candidate(run, &self.repository)?;
95+
/// accepted on ([`Basis`]), else `None`. It fails when GitHub can't say
96+
/// whether the workflow uses the Action, rather than calling it ineligible.
97+
pub fn accepted(&self, run: &Value) -> Result<Option<(String, Basis)>> {
98+
let Some(workflow) = candidate(run, &self.repository) else {
99+
return Ok(None);
100+
};
95101
let basis = if self.workflows.is_empty() {
96-
self.runs_action(&workflow).then_some(Basis::UsesAction)
102+
self.runs_action(&workflow)?.then_some(Basis::UsesAction)
97103
} else {
98104
names(self.workflows, &workflow).then_some(Basis::Configured)
99105
};
100-
basis.map(|basis| (workflow, basis))
106+
Ok(basis.map(|basis| (workflow, basis)))
101107
}
102108

103109
/// Whether the workflow file at `path` on the default branch uses the
104-
/// Projections Action.
105-
fn runs_action(&self, path: &str) -> bool {
110+
/// Projections Action: not when it's absent there (GitHub's 404), and an
111+
/// error when it can't be read (authentication, rate limits, transport).
112+
fn runs_action(&self, path: &str) -> Result<bool> {
106113
if let Some(known) = self.uses_action.borrow().get(path) {
107-
return *known;
114+
return Ok(*known);
108115
}
109116
let action = regex::Regex::new(r#"(?m)^\s*(?:-\s+)?uses:\s*["']?githubnext/projections@"#).expect("pattern");
110117
// Without a ref, the contents API reads the default branch.
111-
let uses = self
112-
.gh(&[
113-
"api",
114-
"--hostname",
115-
&self.host,
116-
"-H",
117-
"Accept: application/vnd.github.raw+json",
118-
&format!("repos/{}/contents/{path}", self.repository),
119-
])
120-
.is_ok_and(|text| action.is_match(&text));
118+
let uses = match self.gh(&[
119+
"api",
120+
"--hostname",
121+
&self.host,
122+
"-H",
123+
"Accept: application/vnd.github.raw+json",
124+
&format!("repos/{}/contents/{path}", self.repository),
125+
]) {
126+
Ok(text) => action.is_match(&text),
127+
Err(error) if not_found(&error) => false,
128+
Err(error) => {
129+
return Err(error.context(format!("couldn't read {path} on the default branch of {}", self.repository)));
130+
}
131+
};
121132
self.uses_action.borrow_mut().insert(path.to_owned(), uses);
122-
uses
133+
Ok(uses)
123134
}
124135

125136
/// Downloads into `base/<run>` the `name` artifact of the newest
@@ -134,7 +145,7 @@ impl<'a> GitHub<'a> {
134145
let Some(id) = run["id"].as_u64().filter(|id| *id > 0) else {
135146
continue;
136147
};
137-
let Some((workflow, basis)) = self.accepted(run) else {
148+
let Some((workflow, basis)) = self.accepted(run)? else {
138149
continue;
139150
};
140151
let artifacts = self.api(&format!("repos/{}/actions/runs/{id}/artifacts?name=projections", self.repository))?;
@@ -223,7 +234,7 @@ impl<'a> GitHub<'a> {
223234
let run = self.api(&format!("repos/{}/actions/runs/{id}", self.repository))?;
224235
anyhow::ensure!(run["conclusion"] == "success", "run {id} didn't succeed");
225236
let (workflow, _) = self
226-
.accepted(&run)
237+
.accepted(&run)?
227238
.with_context(|| format!("run {id} isn't this repository's own Projections workflow"))?;
228239
anyhow::ensure!(signed.contains(&workflow), "run {id}'s attestation names another workflow");
229240
Ok(Origin {
@@ -261,6 +272,15 @@ impl Basis {
261272
}
262273
}
263274

275+
/// Whether a failed `gh api` call was GitHub's 404: what it answers for a file
276+
/// absent on the branch it reads.
277+
fn not_found(error: &anyhow::Error) -> bool {
278+
error
279+
.chain()
280+
.find_map(|cause| cause.downcast_ref::<ProcessFailure>())
281+
.is_some_and(|failure| !failure.timed_out() && failure.stderr().contains("(HTTP 404)"))
282+
}
283+
264284
/// Whether `workflows` (paths or file names) names the workflow file `workflow`.
265285
pub fn names(workflows: &[String], workflow: &str) -> bool {
266286
workflows

‎packages/cli/tests/execution.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,48 @@ fn a_fork_pull_request_run_is_never_the_repository_ci() {
607607
assert!(!log.exists());
608608
}
609609

610+
#[test]
611+
fn a_workflow_github_cannot_read_is_an_error_not_an_ineligible_workflow() {
612+
let (repository, first, _, _published) = published();
613+
let runs = format!("{{\"workflow_runs\":[{}]}}", workflow_run(4242, "push", "acme/demo"));
614+
let lookup = |workflow: &str| {
615+
let bin = tempfile::tempdir().unwrap();
616+
let gh = fake_gh(
617+
bin.path(),
618+
&[
619+
(&format!("*\"actions/runs?head_sha={first}\"*"), &format!("printf '%s' '{runs}'")),
620+
("*\"contents/.github/workflows/ci.yml\"*", workflow),
621+
],
622+
);
623+
let shown = with_gh(&repository, &gh)
624+
.with_cache_base(tempfile::tempdir().unwrap().path())
625+
.with_artifacts(Vec::new(), true)
626+
.show("probe", &first, None);
627+
let calls = fs::read_to_string(bin.path().join("calls.log")).unwrap();
628+
assert!(!calls.contains("artifacts"), "{calls}");
629+
shown
630+
};
631+
// Absent on the default branch, or not running the Action: not CI's
632+
// output, so the commit is extracted.
633+
for ineligible in ["echo 'gh: Not Found (HTTP 404)' >&2; exit 1", "printf 'jobs: {}\\n'"] {
634+
let document = lookup(ineligible).unwrap();
635+
assert!(repository.probe_ran(), "{ineligible}");
636+
assert_ne!(document["provenance"]["execution"]["source"], "ci");
637+
}
638+
// A rate limit or failed authentication says nothing about the workflow.
639+
for unreadable in [
640+
"echo 'gh: API rate limit exceeded for user ID 1. (HTTP 403)' >&2; exit 1",
641+
"echo 'gh: Bad credentials (HTTP 401)' >&2; exit 1",
642+
] {
643+
let error = format!("{:#}", lookup(unreadable).unwrap_err());
644+
assert!(
645+
error.contains("couldn't read .github/workflows/ci.yml on the default branch of acme/demo"),
646+
"{error}"
647+
);
648+
assert!(!repository.probe_ran(), "{unreadable}");
649+
}
650+
}
651+
610652
#[test]
611653
fn an_imported_artifact_is_official_only_when_its_attestation_verifies() {
612654
let (repository, first, _, published) = published();

0 commit comments

Comments
 (0)