Skip to main content

gitpoulpi_hosting/
protection.rs

1//! What a host protects (S23 of the history rewrite): the branches a rewrite
2//! must not force-push unless the user lifts the protection first.
3//!
4//! Two pieces, both client side (hosting stays out of the daemon):
5//!
6//! - [`locate`]: which host and project a repository is on and whether the
7//!   user *linked* it. Only a linked repository is ever queried (hosting is
8//!   opt-in per repository); an unlinked one still gets the how-to links,
9//!   built from its remote's URL, because a link is a string, not a request.
10//! - [`lookup`]: what the host's API says is protected, through the
11//!   provider's [`HostingClient::protected_branches`]. Whatever the token
12//!   cannot read comes back as "unknown" with the reason; it is never an
13//!   error that stops a rewrite.
14//!
15//! What each provider exposes, and with which token (the clients' own docs):
16//! GitHub the protected flag of the branches plus the active branch rulesets
17//! (a classic token with `repo`, a fine-grained one with Metadata read);
18//! GitLab `protected_branches` (`read_api`); Azure DevOps the blocking branch
19//! policies (Code read); Bitbucket Cloud the branch restrictions
20//! (`repository:admin`), Data Center the branch permissions (repository
21//! admin).
22
23use gitpoulpi_config::{ApiFamily, Integration, IntegrationCategory};
24use gitpoulpi_core::domain::rewrite::{HostKind, HostProtection};
25
26use crate::client::HostingClient;
27use crate::resolve::{resolve_for_repo, ResolveRemote};
28use crate::spec::{spec_for, web_base};
29use crate::Error;
30
31/// The protected branch names and `*` patterns of one project (short names),
32/// and what could not be read of them.
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct ProtectedBranches {
35    pub patterns: Vec<String>,
36    /// Part of the answer is missing (rulesets the token cannot read, a
37    /// restriction that names a branching model): English, shown beside the
38    /// list.
39    pub note: Option<String>,
40}
41
42impl ProtectedBranches {
43    /// Adds a branch name or pattern (a full `refs/heads/` name is
44    /// shortened); empty and repeated ones are dropped.
45    pub fn add(&mut self, name: &str) {
46        let name = name.trim();
47        let short = name.strip_prefix("refs/heads/").unwrap_or(name);
48        if !short.is_empty() && !self.patterns.iter().any(|p| p == short) {
49            self.patterns.push(short.to_string());
50        }
51    }
52
53    /// Records one more thing that could not be read.
54    pub fn note(&mut self, text: &str) {
55        match &mut self.note {
56            Some(existing) => {
57                existing.push_str("; ");
58                existing.push_str(text);
59            }
60            None => self.note = Some(text.to_string()),
61        }
62    }
63}
64
65/// The answer of [`lookup`].
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum ProtectionLookup {
68    Known(ProtectedBranches),
69    /// The host could not say; the reason is English.
70    Unknown(String),
71}
72
73/// Why a failed read is "unknown" rather than a failure.
74pub fn unknown_reason(error: &Error) -> String {
75    match error {
76        Error::Unauthorized { .. } => {
77            "the host rejected the token, so its branch protection could not be read".to_string()
78        }
79        Error::Forbidden { .. } => {
80            "the token lacks the scope to read the host's branch protection".to_string()
81        }
82        Error::Api { status: 404, .. } => "the token cannot see this repository's branch protection (it needs admin or maintainer access)"
83            .to_string(),
84        Error::Unsupported(_) | Error::NotImplemented(_) => {
85            "this host's client cannot read branch protection".to_string()
86        }
87        other => format!("the host's branch protection could not be read ({other})"),
88    }
89}
90
91/// Asks the host which branches of `project` are protected.
92pub async fn lookup(client: &dyn HostingClient, project: &str) -> ProtectionLookup {
93    match client.protected_branches(project).await {
94        Ok(found) => ProtectionLookup::Known(found),
95        Err(error) => ProtectionLookup::Unknown(unknown_reason(&error)),
96    }
97}
98
99/// The repository's host, as far as it is known without a request.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Located {
102    pub kind: HostKind,
103    /// The profile that answers for it, when one is configured.
104    pub integration: Option<Integration>,
105    pub web_base: String,
106    pub project: String,
107    pub remote: String,
108    /// The user linked the repository (a pulls/issues source or a pinned
109    /// profile): the only case where the host may be asked.
110    pub linked: bool,
111}
112
113impl Located {
114    /// The how-to's data with the answer of a lookup folded in (`None`: not
115    /// asked).
116    pub fn protection(&self, lookup: Option<ProtectionLookup>) -> HostProtection {
117        let mut out = HostProtection::new(self.kind, self.project.clone(), self.web_base.clone());
118        match lookup {
119            None => {}
120            Some(ProtectionLookup::Known(found)) => {
121                out.asked = true;
122                out.patterns = found.patterns;
123                out.unknown = found.note;
124            }
125            Some(ProtectionLookup::Unknown(why)) => {
126                out.asked = true;
127                out.unknown = Some(why);
128            }
129        }
130        out
131    }
132}
133
134fn host_kind(family: ApiFamily) -> HostKind {
135    match family {
136        ApiFamily::Github => HostKind::GitHub,
137        ApiFamily::Gitlab => HostKind::GitLab,
138        ApiFamily::AzureDevops => HostKind::AzureDevOps,
139        ApiFamily::Bitbucket => HostKind::Bitbucket,
140        _ => HostKind::Other,
141    }
142}
143
144fn family_of(kind: HostKind) -> Option<ApiFamily> {
145    match kind {
146        HostKind::GitHub => Some(ApiFamily::Github),
147        HostKind::GitLab => Some(ApiFamily::Gitlab),
148        HostKind::AzureDevOps => Some(ApiFamily::AzureDevops),
149        HostKind::Bitbucket => Some(ApiFamily::Bitbucket),
150        HostKind::Other => None,
151    }
152}
153
154fn is_hosting(integration: &Integration) -> bool {
155    integration.enabled && integration.kind.category() == IntegrationCategory::Hosting
156}
157
158/// The host of a repository.
159///
160/// `link` is the saved pulls or issues source (profile id and project),
161/// `pinned` the repository's pinned profile; either makes the repository
162/// linked. Without one the profile that owns a remote answers (not linked),
163/// and without a profile the remote's own URL names the host by its name
164/// (`github`, `gitlab`, `dev.azure.com`, `bitbucket`). `remote_hint` is the
165/// remote a push went to, tried first.
166pub fn locate(
167    remotes: &[ResolveRemote],
168    integrations: &[Integration],
169    link: Option<(&str, &str)>,
170    pinned: Option<&str>,
171    remote_hint: Option<&str>,
172) -> Option<Located> {
173    if let Some((id, project)) = link {
174        if let Some(integration) = integrations.iter().find(|i| i.id == id && is_hosting(i)) {
175            let project = if project.is_empty() {
176                resolve_for_repo(remotes, std::slice::from_ref(integration), Some(id))
177                    .map(|r| r.project_path)
178                    .unwrap_or_default()
179            } else {
180                project.to_string()
181            };
182            if let (Some(base), false) = (web_base(integration), project.is_empty()) {
183                return Some(Located {
184                    kind: host_kind(integration.kind.family()),
185                    integration: Some(integration.clone()),
186                    web_base: base,
187                    project,
188                    remote: remote_hint.unwrap_or_default().to_string(),
189                    linked: true,
190                });
191            }
192        }
193    }
194    let ordered: Vec<ResolveRemote> = match remote_hint {
195        Some(hint) => remotes
196            .iter()
197            .filter(|r| r.name == hint)
198            .chain(remotes.iter().filter(|r| r.name != hint))
199            .cloned()
200            .collect(),
201        None => remotes.to_vec(),
202    };
203    if let Some(found) = resolve_for_repo(&ordered, integrations, pinned) {
204        if let Some(base) = web_base(found.integration) {
205            return Some(Located {
206                kind: host_kind(found.integration.kind.family()),
207                integration: Some(found.integration.clone()),
208                web_base: base,
209                project: found.project_path,
210                remote: found.remote,
211                linked: pinned.is_some_and(|p| p == found.integration.id),
212            });
213        }
214    }
215    // No profile: the remote's URL says which host it is.
216    for remote in &ordered {
217        let kind = HostKind::of_url(&remote.url);
218        let Some(family) = family_of(kind) else {
219            continue;
220        };
221        if let Some(parsed) = (spec_for(family).parse_remote)(&remote.url) {
222            return Some(Located {
223                kind,
224                integration: None,
225                web_base: parsed.web_base,
226                project: parsed.project,
227                remote: remote.name.clone(),
228                linked: false,
229            });
230        }
231    }
232    None
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use gitpoulpi_config::IntegrationKind;
239
240    fn remote(name: &str, url: &str) -> ResolveRemote {
241        ResolveRemote::new(name, url)
242    }
243
244    #[test]
245    fn an_unlinked_repository_is_located_from_its_remote_url_and_never_asked() {
246        let found = locate(
247            &[remote("origin", "git@github.com:octo/thing.git")],
248            &[],
249            None,
250            None,
251            None,
252        )
253        .unwrap();
254        assert_eq!(found.kind, HostKind::GitHub);
255        assert_eq!(found.web_base, "https://github.com");
256        assert_eq!(found.project, "octo/thing");
257        assert!(!found.linked, "no link: the host is not to be queried");
258        let how = found.protection(None).howto(&[]);
259        assert!(how.ways[0].links[0].starts_with("https://github.com/octo/thing/settings"));
260    }
261
262    #[test]
263    fn a_saved_link_decides_the_project_and_makes_the_repository_linked() {
264        let gitlab = Integration::new(
265            "corp",
266            IntegrationKind::GitlabSelfManaged,
267            "https://git.corp.example",
268        );
269        let found = locate(
270            &[remote("origin", "https://elsewhere.example/x/y.git")],
271            &[gitlab],
272            Some(("corp", "team/sub/proj")),
273            None,
274            None,
275        )
276        .unwrap();
277        assert!(found.linked);
278        assert_eq!(found.kind, HostKind::GitLab);
279        assert_eq!(found.project, "team/sub/proj");
280        assert_eq!(found.web_base, "https://git.corp.example");
281    }
282
283    #[test]
284    fn a_failed_read_is_unknown_with_the_reason_never_an_error() {
285        let forbidden = Error::Forbidden {
286            what: "x".into(),
287            detail: "no".into(),
288        };
289        assert!(unknown_reason(&forbidden).contains("lacks the scope"));
290        let missing = Error::Api {
291            what: "x".into(),
292            status: 404,
293            detail: "Not Found".into(),
294        };
295        assert!(unknown_reason(&missing).contains("admin or maintainer"));
296        let located = locate(
297            &[remote("origin", "https://github.com/o/r")],
298            &[],
299            None,
300            None,
301            None,
302        )
303        .unwrap();
304        let protection = located.protection(Some(ProtectionLookup::Unknown("because".into())));
305        assert!(protection.asked && protection.patterns.is_empty());
306        assert_eq!(protection.unknown.as_deref(), Some("because"));
307    }
308
309    #[test]
310    fn names_are_shortened_and_deduplicated() {
311        let mut list = ProtectedBranches::default();
312        list.add("refs/heads/main");
313        list.add("main");
314        list.add(" ");
315        list.add("release/*");
316        assert_eq!(list.patterns, ["main", "release/*"]);
317    }
318}