Skip to main content

verctl_github/
actions.rs

1use std::time::Duration;
2
3use anyhow::{Context, Result};
4use verctl_core::repo::Repo;
5
6use crate::{block, client, lookup_failed};
7
8/// A workflow run that has not ended.
9#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub struct ActiveRun {
12    /// The run's page on GitHub.
13    pub url: String,
14}
15
16/// The first run of the workflow file `workflow` at commit `sha` that has not
17/// ended, from `GET /repos/{owner}/{repo}/actions/workflows/{workflow}/runs`
18/// with `head_sha` ([list workflow runs]). The first 100 runs of that commit
19/// are read, and the commit is checked again on each, so a server that
20/// ignores the filter finds no run for another commit.
21///
22/// A run has not ended unless its `status` is `completed`, so a status GitHub
23/// adds later, or none at all, counts as running.
24///
25/// # Errors
26///
27/// Returns an error when the GitHub client cannot be built or the request or
28/// its decoding fails, for example when no workflow file has that name. Only
29/// a lookup that GitHub gave no answer to is a
30/// [`verctl_core::lookup::Unavailable`].
31///
32/// [list workflow runs]: https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-workflow
33pub fn active_run(
34    token: &str,
35    repo: &Repo,
36    workflow: &str,
37    sha: &str,
38) -> Result<Option<ActiveRun>> {
39    #[derive(serde::Deserialize)]
40    struct Run {
41        html_url: String,
42        head_sha: String,
43        status: Option<String>,
44    }
45    #[derive(serde::Deserialize)]
46    struct Runs {
47        workflow_runs: Vec<Run>,
48    }
49    block(async {
50        let crab = client(token)?;
51        let runs: Runs = crab
52            .get(
53                format!(
54                    "/repos/{owner}/{name}/actions/workflows/{workflow}/runs?head_sha={sha}&per_page=100",
55                    owner = repo.owner,
56                    name = repo.name
57                ),
58                None::<&()>,
59            )
60            .await
61            .map_err(|error| lookup_failed(error, format!("list the runs of {workflow}")))?;
62        Ok(runs
63            .workflow_runs
64            .into_iter()
65            .find(|run| {
66                run.head_sha.eq_ignore_ascii_case(sha) && run.status.as_deref() != Some("completed")
67            })
68            .map(|run| ActiveRun { url: run.html_url }))
69    })
70}
71
72/// The `type` of each rule that applies to `branch`, from
73/// `GET /repos/{owner}/{repo}/rules/branches/{branch}` ([get rules for a
74/// branch]). The list is empty when no rule applies.
75///
76/// # Errors
77///
78/// Returns an error when the GitHub client cannot be built or the request or
79/// its decoding fails, including the 403 and 404 answers of a token that
80/// cannot read the rules.
81///
82/// [get rules for a branch]: https://docs.github.com/en/rest/repos/rules#get-rules-for-a-branch
83pub fn branch_rule_types(token: &str, repo: &Repo, branch: &str) -> Result<Vec<String>> {
84    #[derive(serde::Deserialize)]
85    struct Rule {
86        #[serde(rename = "type")]
87        rule_name: String,
88    }
89    block(async {
90        let crab = client(token)?;
91        let rules: Vec<Rule> = crab
92            .get(
93                format!(
94                    "/repos/{owner}/{name}/rules/branches/{branch}",
95                    owner = repo.owner,
96                    name = repo.name
97                ),
98                None::<&()>,
99            )
100            .await
101            .with_context(|| format!("read the rules of {branch}"))?;
102        Ok(rules.into_iter().map(|rule| rule.rule_name).collect())
103    })
104}
105
106/// Request a GitHub Actions OIDC JWT from `request_url` for `audience`, using
107/// bearer `request_token`, without exposing the token or URL query string in
108/// any error message.
109///
110/// # Errors
111///
112/// Returns an error when the HTTP client cannot be built, the request fails,
113/// or the JSON body contains no `value` token field.
114pub fn fetch_oidc_token(
115    request_url: &str,
116    request_token: &str,
117    audience: &str,
118    url_env_name: &str,
119    timeout: Duration,
120) -> Result<String> {
121    #[derive(serde::Deserialize)]
122    struct Issued {
123        #[serde(rename = "value")]
124        jwt: String,
125    }
126    block(async {
127        let http = reqwest::Client::builder()
128            .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
129            .timeout(timeout)
130            .build()
131            .context("HTTP client")?;
132        let separator = if request_url.contains('?') { '&' } else { '?' };
133        let response = http
134            .get(format!("{request_url}{separator}audience={audience}"))
135            .bearer_auth(request_token)
136            .send()
137            .await
138            .and_then(reqwest::Response::error_for_status)
139            .map_err(reqwest::Error::without_url)
140            .with_context(|| format!("request the OIDC token from {url_env_name}"))?;
141        let body = response
142            .bytes()
143            .await
144            .map_err(reqwest::Error::without_url)
145            .with_context(|| format!("read the OIDC token from {url_env_name}"))?;
146        let issued: Issued = serde_json::from_slice(&body)
147            .ok()
148            .with_context(|| format!("the answer of {url_env_name} has no OIDC token"))?;
149        Ok(issued.jwt)
150    })
151}