gitpoulpi_hosting/
integration.rs1pub use gitpoulpi_config::{Integration, IntegrationKind};
7
8use crate::{Error, Result};
9
10pub trait TokenSource: Send + Sync {
14 fn token(&self, integration: &Integration) -> Result<String>;
15}
16
17pub 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
27pub 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
46pub struct DefaultTokenSource {
59 store: Box<dyn TokenStore + Send + Sync>,
60 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 pub fn for_integrations(integrations: &[Integration]) -> Self {
74 Self::new(Box::new(CredentialHelperTokens::new()), integrations)
75 }
76}
77
78fn helper_fallback_allowed(integration: &Integration) -> bool {
80 matches!(
81 integration.kind.family(),
82 gitpoulpi_config::ApiFamily::Github | gitpoulpi_config::ApiFamily::Gitlab
83 )
84}
85
86fn 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 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 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
161pub 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 #[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 #[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 #[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}