Skip to main content

vgi_cli/
forgejo.rs

1//! Forgejo (and Gitea), with the person's own token.
2//!
3//! The plan, the merge-settings body and the branch-protection body — and
4//! the tests for "already done" — are the Forgejo adapter's own; this module
5//! only carries them over HTTP as the repository's admin instead of the
6//! community's bot.
7
8use std::time::Duration;
9
10use anyhow::{Context, Result, anyhow, bail};
11use base64::Engine;
12use base64::engine::general_purpose::STANDARD;
13use reqwest::{Method, StatusCode, redirect};
14use serde_json::{Value, json};
15use url::Url;
16use vgi_forge::{
17    BootstrapStep, MergeMethod, ProtectionSpec, RepoSettings, RepoSpec, StepAction, VgiConfig,
18};
19use vgi_forge_forgejo::plan::{MergePlan, PlanOptions, default_status_context, forgejo_plan};
20use vgi_forge_forgejo::{
21    DEFAULT_ACTIONS_BASE, DEFAULT_CHECKOUT_ACTION, InstanceInfo, managed_protection_rule,
22    protection_body, protection_satisfies, settings_body, settings_satisfied,
23};
24
25use crate::report::{Change, Report};
26
27/// The environment variable holding the person's token.
28pub const TOKEN_ENV: &str = "FORGEJO_TOKEN";
29
30/// A Forgejo API client acting as the token's owner.
31pub struct Client {
32    http: reqwest::Client,
33    api: Url,
34    token: String,
35}
36
37impl std::fmt::Debug for Client {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.debug_struct("Client")
40            .field("api", &self.api.as_str())
41            .field("token", &"<redacted>")
42            .finish()
43    }
44}
45
46/// `https://<host>/`, or `base` checked the way the adapter checks its
47/// instance URL: `https`, or `http` only on loopback (the token travels on
48/// every request). `base` must be on `host`, the repository's own host (any
49/// port), so the token never goes to a server the resource does not name.
50pub fn base_url(host: &str, base: Option<&Url>) -> Result<Url> {
51    let mut url = match base {
52        Some(u) => u.clone(),
53        None => Url::parse(&format!("https://{host}/")).context("instance URL")?,
54    };
55    let h = url.host_str().unwrap_or("").to_ascii_lowercase();
56    if !h.eq_ignore_ascii_case(host) {
57        bail!(
58            "--forgejo-url `{url}` is on `{h}`, but the repository is on `{host}`. {TOKEN_ENV} \
59             is sent to --forgejo-url, so it must be the repository's own host; give --resource \
60             as <instance-host>/<owner>/<repo>"
61        );
62    }
63    let loopback = matches!(h.as_str(), "localhost" | "127.0.0.1" | "[::1]");
64    match url.scheme() {
65        "https" => {}
66        "http" if loopback => {}
67        s => bail!("instance URL `{url}`: `{s}` is not allowed (https, or http on loopback)"),
68    }
69    if !url.path().ends_with('/') {
70        let p = format!("{}/", url.path());
71        url.set_path(&p);
72    }
73    url.set_query(None);
74    url.set_fragment(None);
75    Ok(url)
76}
77
78impl Client {
79    /// Connect to the instance at `base` (see [`base_url`]): ask it for
80    /// `GET /api/v1/version` *without* the token, and hand back a client
81    /// carrying the token only if the answer is Forgejo's or Gitea's (JSON
82    /// with a `version` string). `auto`: the forge was guessed from the
83    /// host (`--forge auto`), so a failure suggests `--forge`.
84    pub async fn connect(base: &Url, token: String, auto: bool) -> Result<(Self, InstanceInfo)> {
85        let c = Client::new(base, token)?;
86        match c.version().await {
87            Ok(info) => Ok((c, info)),
88            Err(why) if auto => bail!(
89                "{base} did not answer GET /api/v1/version as Forgejo or Gitea ({why:#}), so \
90                 {TOKEN_ENV} was not sent to it. `--forge auto` takes any host other than \
91                 github.com for Forgejo: pass --forge github for GitHub Enterprise Server, or \
92                 --forge forgejo with --forgejo-url if the instance lives under a sub-path"
93            ),
94            Err(why) => bail!(
95                "{base} did not answer GET /api/v1/version as Forgejo or Gitea ({why:#}), so \
96                 {TOKEN_ENV} was not sent to it; check --forgejo-url"
97            ),
98        }
99    }
100
101    /// `GET /api/v1/version`, unauthenticated.
102    async fn version(&self) -> Result<InstanceInfo> {
103        let url = self.url(&["version"]);
104        let resp = self
105            .http
106            .get(url)
107            .header("Accept", "application/json")
108            .send()
109            .await
110            .map_err(|e| anyhow!("{}", e.without_url()))?;
111        let status = resp.status();
112        if !status.is_success() {
113            bail!("HTTP {status}");
114        }
115        let bytes = resp.bytes().await.context("reading the reply")?;
116        let v: Value = serde_json::from_slice(&bytes).map_err(|_| anyhow!("not JSON"))?;
117        let version = v
118            .get("version")
119            .and_then(Value::as_str)
120            .filter(|s| !s.trim().is_empty())
121            .ok_or_else(|| anyhow!("no `version` string"))?;
122        Ok(InstanceInfo::from_version(version))
123    }
124
125    fn new(base: &Url, token: String) -> Result<Self> {
126        if token.trim().is_empty() {
127            bail!("{TOKEN_ENV} is empty");
128        }
129        let http = reqwest::Client::builder()
130            .user_agent(concat!("vgi/", env!("CARGO_PKG_VERSION")))
131            .redirect(redirect::Policy::none())
132            .timeout(Duration::from_secs(30))
133            .build()
134            .context("HTTP client")?;
135        Ok(Client {
136            http,
137            api: base.join("api/v1/").context("API URL")?,
138            token,
139        })
140    }
141
142    fn url(&self, segments: &[&str]) -> Url {
143        let mut u = self.api.clone();
144        u.path_segments_mut()
145            .expect("an http(s) URL has path segments")
146            .pop_if_empty()
147            .extend(segments);
148        u
149    }
150
151    async fn call(
152        &self,
153        method: Method,
154        url: Url,
155        body: Option<&Value>,
156    ) -> Result<(StatusCode, Value)> {
157        let mut req = self
158            .http
159            .request(method.clone(), url.clone())
160            .header("Authorization", format!("token {}", self.token))
161            .header("Accept", "application/json");
162        if let Some(b) = body {
163            req = req.json(b);
164        }
165        let what = format!("{method} {}", url.path());
166        let resp = req
167            .send()
168            .await
169            .map_err(|e| anyhow!("{what}: {}", e.without_url()))?;
170        let status = resp.status();
171        let bytes = resp.bytes().await.with_context(|| what.clone())?;
172        let value = if bytes.iter().all(u8::is_ascii_whitespace) {
173            Value::Null
174        } else {
175            serde_json::from_slice(&bytes)
176                .unwrap_or_else(|_| json!(String::from_utf8_lossy(&bytes)))
177        };
178        Ok((status, value))
179    }
180
181    async fn get(&self, segments: &[&str]) -> Result<Option<Value>> {
182        let url = self.url(segments);
183        let (status, v) = self.call(Method::GET, url.clone(), None).await?;
184        match status.as_u16() {
185            200..=299 => Ok(Some(v)),
186            404 => Ok(None),
187            _ => bail!("GET {}: HTTP {status}: {}", url.path(), message(&v)),
188        }
189    }
190
191    async fn send(&self, method: Method, segments: &[&str], body: &Value) -> Result<Value> {
192        let url = self.url(segments);
193        let (status, v) = self.call(method.clone(), url.clone(), Some(body)).await?;
194        if !status.is_success() {
195            bail!("{method} {}: HTTP {status}: {}", url.path(), message(&v));
196        }
197        Ok(v)
198    }
199}
200
201fn message(v: &Value) -> String {
202    v.get("message")
203        .and_then(Value::as_str)
204        .map(str::to_string)
205        .unwrap_or_else(|| v.to_string())
206}
207
208/// The token owner's login.
209pub async fn whoami(c: &Client) -> Result<String> {
210    let me = c
211        .get(&["user"])
212        .await?
213        .ok_or_else(|| anyhow!("{TOKEN_ENV} is not accepted (GET /user)"))?;
214    let login = me
215        .get("login")
216        .and_then(Value::as_str)
217        .ok_or_else(|| anyhow!("GET /user: no login"))?
218        .to_string();
219    Ok(login)
220}
221
222/// The adapter's plan, with the adapter's defaults: fast-forward-only
223/// merges, DIDs written into the workflow.
224pub fn plan(spec: &RepoSpec, cfg: &VgiConfig, runs_on: &str) -> Result<Vec<BootstrapStep>> {
225    let actions_base = Url::parse(DEFAULT_ACTIONS_BASE).expect("static URL");
226    let opts = PlanOptions {
227        checkout_action: DEFAULT_CHECKOUT_ACTION,
228        actions_base: &actions_base,
229        runs_on,
230        status_context: default_status_context(&cfg.required_check),
231        inline_variables: true,
232        merges: MergePlan::FastForwardOnly,
233    };
234    Ok(forgejo_plan(spec, cfg, &opts)?)
235}
236
237/// Run `steps` in order, check-then-apply, stopping at the first failure.
238pub async fn apply(
239    c: &Client,
240    owner: &str,
241    name: &str,
242    me: &str,
243    info: &InstanceInfo,
244    steps: &[BootstrapStep],
245    report: &mut Report<'_>,
246) -> Result<()> {
247    let repo = c.get(&["repos", owner, name]).await?.ok_or_else(|| {
248        anyhow!("{owner}/{name} does not exist, or {TOKEN_ENV} cannot see it; create it first")
249    })?;
250    if repo.pointer("/permissions/admin").and_then(Value::as_bool) != Some(true) {
251        bail!(
252            "{TOKEN_ENV} does not show admin on {owner}/{name}; branch protection needs admin \
253             (the account holder, or an organisation owner, runs this)"
254        );
255    }
256    for step in steps {
257        let id = step.id.as_str();
258        match &step.action {
259            StepAction::ConfigureRepo(s) => {
260                let (change, body) = configure(c, owner, name, info, s, report.dry_run()).await?;
261                report.step(
262                    id,
263                    "merge settings",
264                    change,
265                    Some(&serde_json::to_string_pretty(&body)?),
266                );
267            }
268            StepAction::WriteFile {
269                path,
270                contents,
271                message,
272            } => {
273                let change =
274                    write_file(c, owner, name, path, contents, message, report.dry_run()).await?;
275                report.step(id, path, change, Some(&String::from_utf8_lossy(contents)));
276            }
277            StepAction::ProtectDefaultBranch(spec) => {
278                let (change, body) = protect(c, owner, name, me, spec, report.dry_run()).await?;
279                report.step(
280                    id,
281                    "default branch protection",
282                    change,
283                    Some(&serde_json::to_string_pretty(&body)?),
284                );
285            }
286            other => bail!("step `{id}` ({other:?}) is not one `vgi repo init` runs on Forgejo"),
287        }
288    }
289    Ok(())
290}
291
292async fn configure(
293    c: &Client,
294    owner: &str,
295    name: &str,
296    info: &InstanceInfo,
297    s: &RepoSettings,
298    dry_run: bool,
299) -> Result<(Change, Value)> {
300    let repo = c
301        .get(&["repos", owner, name])
302        .await?
303        .ok_or_else(|| anyhow!("{owner}/{name} vanished"))?;
304    let ff_wanted = s.merge_methods.contains(&MergeMethod::FastForward);
305    let ff_available =
306        info.features.fast_forward_only && repo.get("allow_fast_forward_only_merge").is_some();
307    if ff_wanted && !ff_available {
308        bail!(
309            "this instance ({}) cannot restrict merges to fast-forward only, and every web merge \
310             would land a commit the check never saw. Upgrade to Forgejo 7 or Gitea 1.22",
311            info.version
312        );
313    }
314    let body = settings_body(&repo, s)?;
315    if settings_satisfied(&repo, s)? {
316        return Ok((Change::Unchanged, body));
317    }
318    if !dry_run {
319        let after = c
320            .send(Method::PATCH, &["repos", owner, name], &body)
321            .await?;
322        if !settings_satisfied(&after, s)? {
323            bail!(
324                "{owner}/{name}: the instance accepted the settings but did not apply them all \
325                 (are Actions or pull requests disabled instance-wide?)"
326            );
327        }
328    }
329    Ok((Change::Update, body))
330}
331
332async fn write_file(
333    c: &Client,
334    owner: &str,
335    name: &str,
336    file: &str,
337    contents: &[u8],
338    message: &str,
339    dry_run: bool,
340) -> Result<Change> {
341    vgi_forge::validate_repo_path(file)?;
342    let mut segs = vec!["repos", owner, name, "contents"];
343    segs.extend(file.split('/'));
344    let existing = match c.get(&segs).await? {
345        None => None,
346        Some(v) => {
347            if v.is_array() || v.get("type").and_then(Value::as_str) != Some("file") {
348                bail!("`{file}` exists in {owner}/{name} and is not a file");
349            }
350            let Some(b64) = v.get("content").and_then(Value::as_str) else {
351                bail!(
352                    "`{file}` in {owner}/{name} is too large for the instance to return inline; \
353                     it was not written by the bootstrap — remove or rename it"
354                );
355            };
356            let compact: String = b64.chars().filter(|c| !c.is_whitespace()).collect();
357            let bytes = STANDARD
358                .decode(compact)
359                .with_context(|| format!("`{file}`: content is not base64"))?;
360            let sha = v
361                .get("sha")
362                .and_then(Value::as_str)
363                .unwrap_or("")
364                .to_string();
365            Some((sha, bytes))
366        }
367    };
368    let (change, method) = match &existing {
369        Some((_, current)) if current == contents => return Ok(Change::Unchanged),
370        Some(_) => (Change::Update, Method::PUT),
371        None => (Change::Create, Method::POST),
372    };
373    if dry_run {
374        return Ok(change);
375    }
376    let mut body = json!({ "message": message, "content": STANDARD.encode(contents) });
377    if let Some((sha, _)) = &existing {
378        body["sha"] = json!(sha);
379    }
380    c.send(method, &segs, &body).await.map_err(|e| {
381        e.context(format!(
382            "writing `{file}` — once the default branch is protected, no one can push to it and \
383             the workflow directories are protected file patterns. To change the workflow (a new \
384             --verify-trust-version, say), an admin temporarily lifts that protection (deletes \
385             the default branch's protection rule, or allows pushes and clears its protected \
386             file patterns) and re-runs `vgi repo init`, which writes the workflow and puts the \
387             protection back; where a community bridge manages the repository, it makes the \
388             change instead"
389        ))
390    })?;
391    Ok(change)
392}
393
394/// Admin collaborators, plus the person running this: the rule applies to
395/// admins, and its merge allow-list is who may merge at all, so the account
396/// holder (never a collaborator of their own repository) must be on it or
397/// they lock themselves out. The bridge seeds only collaborators, because
398/// there a namespace's owner is not the one running the plan.
399async fn admins(c: &Client, owner: &str, name: &str, me: &str) -> Result<Vec<String>> {
400    let mut out = vec![me.to_string()];
401    let mut page = 1u32;
402    loop {
403        let mut url = c.url(&["repos", owner, name, "collaborators"]);
404        url.query_pairs_mut()
405            .append_pair("page", &page.to_string())
406            .append_pair("limit", "50");
407        let (status, v) = c.call(Method::GET, url, None).await?;
408        if !status.is_success() {
409            bail!("listing collaborators: HTTP {status}: {}", message(&v));
410        }
411        let users = v.as_array().cloned().unwrap_or_default();
412        if users.is_empty() {
413            break;
414        }
415        for u in &users {
416            let Some(login) = u.get("login").and_then(Value::as_str) else {
417                continue;
418            };
419            let perm = c
420                .get(&["repos", owner, name, "collaborators", login, "permission"])
421                .await?;
422            let is_admin = perm
423                .as_ref()
424                .and_then(|p| p.get("permission"))
425                .and_then(Value::as_str)
426                == Some("admin");
427            if is_admin && !out.iter().any(|l| l.eq_ignore_ascii_case(login)) {
428                out.push(login.to_string());
429            }
430        }
431        if users.len() < 50 {
432            break;
433        }
434        page += 1;
435    }
436    Ok(out)
437}
438
439async fn protect(
440    c: &Client,
441    owner: &str,
442    name: &str,
443    me: &str,
444    spec: &ProtectionSpec,
445    dry_run: bool,
446) -> Result<(Change, Value)> {
447    let repo = c
448        .get(&["repos", owner, name])
449        .await?
450        .ok_or_else(|| anyhow!("{owner}/{name} vanished"))?;
451    let empty = repo.get("empty").and_then(Value::as_bool) == Some(true);
452    let branch = repo
453        .get("default_branch")
454        .and_then(Value::as_str)
455        .filter(|b| !b.is_empty() && !empty)
456        .map(str::to_string);
457    let Some(branch) = branch else {
458        if dry_run {
459            // The workflow step would have made the first commit.
460            let mut body = protection_body(None, &[me.to_string()], spec)?;
461            body["rule_name"] = json!("<default branch>");
462            return Ok((Change::Create, body));
463        }
464        bail!("{owner}/{name} is empty: there is no default branch to protect yet");
465    };
466    if branch.contains(['*', '?', '[', ']', '{', '}', '\\']) {
467        bail!(
468            "the default branch `{branch}` contains glob characters, so Forgejo would read a rule \
469             for it as a pattern; rename the branch"
470        );
471    }
472    let rules = c
473        .get(&["repos", owner, name, "branch_protections"])
474        .await?
475        .unwrap_or(Value::Array(Vec::new()));
476    let (existing, shadowing) = managed_protection_rule(&rules, &branch)?;
477    if !shadowing.is_empty() {
478        bail!(
479            "{owner}/{name}: branch protection rule(s) {} also match `{branch}` (Forgejo compares \
480             rule names case-insensitively and applies the oldest), so the managed rule may \
481             never apply; remove them and re-run",
482            shadowing.join(", ")
483        );
484    }
485    if let Some(rule) = &existing
486        && protection_satisfies(rule, spec)?
487    {
488        return Ok((Change::Unchanged, rule.clone()));
489    }
490    let admins = admins(c, owner, name, me).await?;
491    let mut body = protection_body(existing.as_ref(), &admins, spec)?;
492    let (change, method, segs): (Change, Method, Vec<String>) = match &existing {
493        Some(rule) => {
494            let rule_name = rule
495                .get("rule_name")
496                .and_then(Value::as_str)
497                .filter(|n| !n.is_empty())
498                .or_else(|| rule.get("branch_name").and_then(Value::as_str))
499                .unwrap_or(&branch)
500                .to_string();
501            (
502                Change::Update,
503                Method::PATCH,
504                vec![
505                    "repos".into(),
506                    owner.into(),
507                    name.into(),
508                    "branch_protections".into(),
509                    rule_name,
510                ],
511            )
512        }
513        None => {
514            body["rule_name"] = json!(branch);
515            // Pre-1.22 instances know only `branch_name`.
516            body["branch_name"] = json!(branch);
517            (
518                Change::Create,
519                Method::POST,
520                vec![
521                    "repos".into(),
522                    owner.into(),
523                    name.into(),
524                    "branch_protections".into(),
525                ],
526            )
527        }
528    };
529    if !dry_run {
530        let segs: Vec<&str> = segs.iter().map(String::as_str).collect();
531        let after = c.send(method, &segs, &body).await?;
532        if !protection_satisfies(&after, spec)? {
533            bail!(
534                "{owner}/{name}: the instance accepted the branch protection but it does not read \
535                 back as requested"
536            );
537        }
538    }
539    Ok((change, body))
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    #[test]
547    fn instance_urls_are_checked() {
548        assert_eq!(
549            base_url("codeberg.org", None).unwrap().as_str(),
550            "https://codeberg.org/"
551        );
552        let sub = Url::parse("https://example.org/git").unwrap();
553        assert_eq!(
554            base_url("example.org", Some(&sub)).unwrap().as_str(),
555            "https://example.org/git/"
556        );
557        let lo = Url::parse("http://127.0.0.1:3000").unwrap();
558        assert!(base_url("127.0.0.1", Some(&lo)).is_ok());
559        let plain = Url::parse("http://git.example.org/").unwrap();
560        assert!(base_url("git.example.org", Some(&plain)).is_err());
561    }
562
563    #[test]
564    fn the_instance_url_must_be_on_the_repositorys_host() {
565        let sub = Url::parse("https://Example.org:8443/git").unwrap();
566        assert_eq!(
567            base_url("example.org", Some(&sub)).unwrap().as_str(),
568            "https://example.org:8443/git/"
569        );
570        let err = base_url("codeberg.org", Some(&sub))
571            .unwrap_err()
572            .to_string();
573        assert!(
574            err.contains("codeberg.org") && err.contains(TOKEN_ENV),
575            "{err}"
576        );
577        let lo = Url::parse("http://127.0.0.1:3000").unwrap();
578        assert!(base_url("codeberg.org", Some(&lo)).is_err());
579    }
580
581    #[test]
582    fn path_segments_are_encoded() {
583        let c = Client::new(&Url::parse("https://h.example/sub/").unwrap(), "t".into()).unwrap();
584        assert_eq!(
585            c.url(&["repos", "a", "b", "contents", ".forgejo", "x y?"])
586                .as_str(),
587            "https://h.example/sub/api/v1/repos/a/b/contents/.forgejo/x%20y%3F"
588        );
589    }
590}