Skip to main content

gitpoulpi_hosting/
scope.rs

1//! Per-repository decisions the hosting clients honour without every caller
2//! passing a repository: which token a repository's host calls use (a token
3//! command, for a GitHub App bot) and whether assignment is blocked.
4//!
5//! The hosting crate cannot read the repository's stored settings (those live
6//! in crates that depend on it), so a higher crate installs one
7//! [`RepoScopes`] for the process. A client then asks it, per call, by the
8//! `(integration id, project)` pair every call already carries: no call site
9//! needs a repository handed to it, and a surface that forgets to register a
10//! repository simply gets the plain behaviour (personal token, assignment
11//! allowed) rather than a failure.
12
13use std::sync::{Arc, OnceLock};
14
15use crate::{Error, Result};
16
17/// The reason shown wherever an assignment is refused or an assignee field is
18/// hidden. Also the marker a CLI answer is recognised by (exit code 2).
19pub const ASSIGNMENT_BLOCKED: &str = "assignment is blocked for this repository";
20
21/// What a repository's stored settings say about its host calls.
22#[async_trait::async_trait]
23pub trait RepoScopes: Send + Sync {
24    /// Whether nothing may be assigned in `project` of `integration_id`.
25    fn assignment_blocked(&self, integration_id: &str, project: &str) -> bool;
26
27    /// The token the repository's token command gives for its host calls,
28    /// `None` when the repository does not use one (the personal token
29    /// applies). `refresh`: the host refused the previous one, so ask the
30    /// command again. An `Err` refuses the call: it never falls back to the
31    /// personal token.
32    async fn token(
33        &self,
34        integration_id: &str,
35        project: &str,
36        refresh: bool,
37    ) -> Option<Result<String>>;
38
39    /// Whether the repository's host calls are made by an App bot.
40    fn acts_as_bot(&self, integration_id: &str, project: &str) -> bool;
41
42    /// The "Post as" name the user configured for `project`: the
43    /// repository's own, else the global `general.hosting_post_as`.
44    fn post_as(&self, _integration_id: &str, _project: &str) -> Option<String> {
45        None
46    }
47
48    /// The login learned from the author of our first post, kept in the
49    /// repository's state.
50    fn learned_login(&self, _integration_id: &str, _project: &str) -> Option<String> {
51        None
52    }
53
54    /// Remembers `login` as who the repository's token posts as.
55    fn learn_login(&self, _integration_id: &str, _project: &str, _login: &str) {}
56}
57
58static SCOPES: OnceLock<Arc<dyn RepoScopes>> = OnceLock::new();
59
60/// Installs the process's scopes (the first call wins).
61pub fn install(scopes: Arc<dyn RepoScopes>) {
62    let _ = SCOPES.set(scopes);
63}
64
65pub(crate) fn installed() -> Option<&'static Arc<dyn RepoScopes>> {
66    SCOPES.get()
67}
68
69/// Whether assignment is blocked for `project` of `integration_id`.
70pub fn assignment_blocked(integration_id: &str, project: &str) -> bool {
71    installed().is_some_and(|s| s.assignment_blocked(integration_id, project))
72}
73
74/// Whether the repository's host calls are made by an App bot.
75pub fn acts_as_bot(integration_id: &str, project: &str) -> bool {
76    installed().is_some_and(|s| s.acts_as_bot(integration_id, project))
77}
78
79/// The configured "Post as" name of `project`, if any.
80pub fn post_as(integration_id: &str, project: &str) -> Option<String> {
81    installed()
82        .and_then(|s| s.post_as(integration_id, project))
83        .map(|n| n.trim().to_string())
84        .filter(|n| !n.is_empty())
85}
86
87/// The login learned from our first post in `project`, if any.
88pub fn learned_login(integration_id: &str, project: &str) -> Option<String> {
89    installed().and_then(|s| s.learned_login(integration_id, project))
90}
91
92/// Persists `login` as who the token posts as in `project`.
93pub fn learn_login(integration_id: &str, project: &str, login: &str) {
94    if let Some(s) = installed() {
95        s.learn_login(integration_id, project, login);
96    }
97}
98
99/// The refusal of an assignment into a blocked repository.
100#[cfg_attr(not(feature = "hosting"), allow(dead_code))]
101pub(crate) fn refuse() -> Error {
102    Error::AssignmentBlocked
103}
104
105/// Whether `token` is a GitHub App installation token (`ghs_`): it has no
106/// "me" and cannot call `GET /user`.
107pub fn is_app_installation_token(token: &str) -> bool {
108    token.trim().starts_with("ghs_")
109}
110
111/// `owner/repo` of an API URL of the form `<api>/repos/<owner>/<repo>/...`.
112#[cfg_attr(not(feature = "github"), allow(dead_code))]
113pub(crate) fn github_project_of(url: &str) -> Option<String> {
114    let path = url.split(['?', '#']).next()?;
115    let (_, rest) = path.split_once("/repos/")?;
116    let mut parts = rest.split('/');
117    let owner = parts.next().filter(|p| !p.is_empty())?;
118    let repo = parts.next().filter(|p| !p.is_empty())?;
119    Some(format!("{owner}/{repo}"))
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn the_project_of_an_api_url_is_owner_and_repo() {
128        assert_eq!(
129            github_project_of("https://api.example.com/repos/acme/app/issues/3/comments?x=1"),
130            Some("acme/app".to_string())
131        );
132        assert_eq!(github_project_of("https://api.example.com/user"), None);
133        assert_eq!(
134            github_project_of("https://api.example.com/repos/acme"),
135            None
136        );
137    }
138
139    #[test]
140    fn an_installation_token_is_recognised_by_its_prefix() {
141        assert!(is_app_installation_token("ghs_abc"));
142        assert!(!is_app_installation_token("ghp_abc"));
143        assert!(!is_app_installation_token("github_pat_abc"));
144    }
145}