Skip to main content

gitpoulpi_hosting/
integration.rs

1//! Which host to talk to, and how to get the token for it.
2//!
3//! [`Integration`] and [`IntegrationKind`] are owned by `gitpoulpi-config`
4//! and re-exported here; this module only adds token resolution.
5
6pub use gitpoulpi_config::{Integration, IntegrationKind};
7
8use crate::{Error, Result};
9
10/// Where a token comes from. A trait so the clients can be tested with a
11/// canned token and the resolution order can change without touching a
12/// client.
13pub trait TokenSource: Send + Sync {
14    fn token(&self, integration: &Integration) -> Result<String>;
15}
16
17/// A token held in memory. For tests, and for a CLI invocation that was
18/// handed one on the command line.
19pub struct StaticToken(pub String);
20
21impl TokenSource for StaticToken {
22    fn token(&self, _integration: &Integration) -> Result<String> {
23        Ok(self.0.clone())
24    }
25}
26
27/// The environment variable an integration's token can be supplied in
28/// (CI, a one-off shell), without writing it to disk.
29///
30/// `my-gitlab` becomes `GITPOULPI_TOKEN_MY_GITLAB`: uppercased, with every
31/// non-alphanumeric turned into `_`.
32pub fn token_env_var(id: &str) -> String {
33    let sanitized: String = id
34        .chars()
35        .map(|c| {
36            if c.is_ascii_alphanumeric() {
37                c.to_ascii_uppercase()
38            } else {
39                '_'
40            }
41        })
42        .collect();
43    format!("GITPOULPI_TOKEN_{sanitized}")
44}
45
46/// The default resolution order, per profile:
47///
48/// 1. the `GITPOULPI_TOKEN_<ID>` environment variable (one-off override,
49///    CI);
50/// 2. the token stored under the profile's own `token_ref`;
51/// 3. the system credential helper for the profile's host - **only** when
52///    exactly one enabled profile has that host. With two profiles on one
53///    host (two GitHub users, say) the helper's single per-host credential
54///    would silently authenticate one as the other.
55///
56/// SSH is deliberately absent: per ADR-0004 this crate never sees a
57/// private key; token auth is for the *API*.
58pub struct DefaultTokenSource {
59    store: Box<dyn TokenStore + Send + Sync>,
60    /// Lowercased hosts that exactly one enabled profile uses.
61    unique_hosts: std::collections::HashSet<String>,
62}
63
64impl DefaultTokenSource {
65    pub fn new(store: Box<dyn TokenStore + Send + Sync>, integrations: &[Integration]) -> Self {
66        Self {
67            store,
68            unique_hosts: unique_hosts(integrations),
69        }
70    }
71
72    /// The production wiring: the git credential helper as the store.
73    pub fn for_integrations(integrations: &[Integration]) -> Self {
74        Self::new(Box::new(CredentialHelperTokens::new()), integrations)
75    }
76}
77
78/// Whether the git credential helper may stand in for a stored token.
79fn helper_fallback_allowed(integration: &Integration) -> bool {
80    matches!(
81        integration.kind.family(),
82        gitpoulpi_config::ApiFamily::Github | gitpoulpi_config::ApiFamily::Gitlab
83    )
84}
85
86/// What to ask the credential helper for: the host, spelled `http://host`
87/// when the profile is a plain-http server (the helper keys entries by
88/// protocol), else the bare host.
89fn helper_target(integration: &Integration, host: &str) -> String {
90    let plain_http = integration
91        .url
92        .trim()
93        .get(..7)
94        .is_some_and(|s| s.eq_ignore_ascii_case("http://"));
95    if plain_http {
96        format!("http://{host}")
97    } else {
98        host.to_string()
99    }
100}
101
102fn unique_hosts(integrations: &[Integration]) -> std::collections::HashSet<String> {
103    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
104    for host in integrations
105        .iter()
106        .filter(|i| i.enabled)
107        .filter_map(|i| i.host())
108    {
109        *counts.entry(host.to_ascii_lowercase()).or_default() += 1;
110    }
111    counts
112        .into_iter()
113        .filter(|(_, n)| *n == 1)
114        .map(|(h, _)| h)
115        .collect()
116}
117
118impl TokenSource for DefaultTokenSource {
119    fn token(&self, integration: &Integration) -> Result<String> {
120        // A folder of notes has no token to find.
121        if integration.kind.capabilities().local_folder {
122            return Ok(String::new());
123        }
124        if let Some(from_env) = std::env::var(token_env_var(&integration.id))
125            .ok()
126            .filter(|t| !t.trim().is_empty())
127        {
128            return Ok(from_env);
129        }
130
131        if let Ok(Some(stored)) = self.store.load(&integration.token_ref) {
132            if !stored.trim().is_empty() {
133                return Ok(stored);
134            }
135        }
136
137        let host = integration
138            .host()
139            .ok_or_else(|| Error::BadUrl(integration.url.clone()))?;
140        // Only GitHub and GitLab: Azure's helper (Git Credential Manager)
141        // holds an Entra OAuth token, not a PAT, and the Atlassian helpers
142        // hold a git password, not an API token.
143        if helper_fallback_allowed(integration)
144            && self.unique_hosts.contains(&host.to_ascii_lowercase())
145        {
146            if let Ok(credential) = CredentialHelper.resolve(&helper_target(integration, &host)) {
147                if !credential.password.trim().is_empty() {
148                    return Ok(credential.password);
149                }
150            }
151        }
152        Err(Error::NoToken {
153            id: integration.id.clone(),
154            token_ref: integration.token_ref.clone(),
155            env_var: token_env_var(&integration.id),
156            host,
157        })
158    }
159}
160
161/// A repository-relative folder made absolute; an absolute one is kept and
162/// `~/` is expanded. How a local Markdown issue source's folder is read.
163pub fn resolve_local_folder(repo_root: &std::path::Path, folder: &str) -> std::path::PathBuf {
164    let folder = folder.trim();
165    if let Some(rest) = folder.strip_prefix("~/") {
166        if let Some(home) = gitpoulpi_config::home_dir() {
167            return home.join(rest);
168        }
169    }
170    let path = std::path::Path::new(folder);
171    if path.is_absolute() {
172        path.to_path_buf()
173    } else {
174        repo_root.join(path)
175    }
176}
177
178use gitpoulpi_secrets::{CredentialHelper, CredentialHelperTokens, CredentialSource, TokenStore};
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use gitpoulpi_secrets::InMemoryTokens;
184
185    fn gl(id: &str, url: &str) -> Integration {
186        Integration::new(id, IntegrationKind::GitlabSelfManaged, url)
187    }
188
189    #[test]
190    fn the_credential_helper_is_asked_over_http_for_a_plain_http_profile() {
191        assert_eq!(
192            helper_target(&gl("a", "http://nas:8080"), "nas:8080"),
193            "http://nas:8080"
194        );
195        assert_eq!(helper_target(&gl("a", "HTTP://nas"), "nas"), "http://nas");
196        assert_eq!(
197            helper_target(&gl("a", "https://gl.example.com"), "gl.example.com"),
198            "gl.example.com"
199        );
200    }
201
202    #[test]
203    fn an_integration_id_becomes_a_legal_environment_variable_name() {
204        assert_eq!(token_env_var("my-gitlab"), "GITPOULPI_TOKEN_MY_GITLAB");
205        assert_eq!(token_env_var("acme.corp/2"), "GITPOULPI_TOKEN_ACME_CORP_2");
206    }
207
208    #[test]
209    fn the_mandated_toml_shape_parses() {
210        #[derive(serde::Deserialize)]
211        struct Wrapper {
212            integrations: Vec<Integration>,
213        }
214        let parsed: Wrapper = toml::from_str(
215            r#"
216            [[integrations]]
217            id = "my-gitlab"
218            kind = "gitlab"
219            url = "https://gitlab.example.com"
220            token_ref = "integration:my-gitlab"
221            "#,
222        )
223        .unwrap();
224        assert_eq!(parsed.integrations[0].kind, IntegrationKind::Gitlab);
225        assert_eq!(parsed.integrations[0].token_ref, "integration:my-gitlab");
226    }
227
228    /// The stored per-profile token is found by `token_ref`, and two
229    /// profiles on one host each get their own - no leak between them.
230    #[test]
231    fn each_profile_resolves_its_own_stored_token() {
232        let a = gl("tok-a", "https://gitlab.example.com");
233        let b = gl("tok-b", "https://gitlab.example.com");
234        let store = InMemoryTokens::default();
235        store.store(&a.token_ref, "token-a").unwrap();
236        store.store(&b.token_ref, "token-b").unwrap();
237        let source = DefaultTokenSource::new(Box::new(store), &[a.clone(), b.clone()]);
238        assert_eq!(source.token(&a).unwrap(), "token-a");
239        assert_eq!(source.token(&b).unwrap(), "token-b");
240    }
241
242    /// A shared host has no unambiguous helper credential, so a profile
243    /// with no stored token errors instead of borrowing the helper's.
244    #[test]
245    fn same_host_profiles_never_fall_back_to_the_credential_helper() {
246        let a = gl("nofallback-a", "https://gitlab.invalid.example");
247        let b = gl("nofallback-b", "https://gitlab.invalid.example");
248        let source =
249            DefaultTokenSource::new(Box::new(InMemoryTokens::default()), &[a.clone(), b.clone()]);
250        assert!(matches!(source.token(&a), Err(Error::NoToken { .. })));
251        assert!(source.unique_hosts.is_empty());
252
253        let mut disabled = b.clone();
254        disabled.enabled = false;
255        let source = DefaultTokenSource::new(Box::new(InMemoryTokens::default()), &[a, disabled]);
256        assert!(source.unique_hosts.contains("gitlab.invalid.example"));
257    }
258
259    /// A helper credential for the host exists, yet a non-GitHub/GitLab
260    /// profile must not borrow it.
261    #[test]
262    fn the_credential_helper_fallback_is_refused_for_other_families() {
263        for kind in [
264            IntegrationKind::AzureDevops,
265            IntegrationKind::AzureDevopsServer,
266            IntegrationKind::Bitbucket,
267            IntegrationKind::BitbucketDataCenter,
268            IntegrationKind::JiraCloud,
269            IntegrationKind::JiraDataCenter,
270            IntegrationKind::Trello,
271        ] {
272            let i = Integration::new("nohelper-zz", kind, "https://h.invalid.example");
273            assert!(!helper_fallback_allowed(&i), "{kind:?}");
274            let source = DefaultTokenSource::new(
275                Box::new(InMemoryTokens::default()),
276                std::slice::from_ref(&i),
277            );
278            assert!(source.unique_hosts.contains("h.invalid.example"));
279            assert!(matches!(source.token(&i), Err(Error::NoToken { .. })));
280        }
281        for kind in [IntegrationKind::Github, IntegrationKind::GitlabSelfManaged] {
282            let i = Integration::new("x", kind, "https://h.invalid.example");
283            assert!(helper_fallback_allowed(&i), "{kind:?}");
284        }
285    }
286
287    #[test]
288    fn the_environment_wins_over_the_store() {
289        let i = gl("envwins-zz", "https://gitlab.example.com");
290        let store = InMemoryTokens::default();
291        store.store(&i.token_ref, "stored").unwrap();
292        let var = token_env_var(&i.id);
293        std::env::set_var(&var, "from-env");
294        let source = DefaultTokenSource::new(Box::new(store), std::slice::from_ref(&i));
295        let got = source.token(&i);
296        std::env::remove_var(&var);
297        assert_eq!(got.unwrap(), "from-env");
298    }
299}