1use crate::integration::{Integration, IntegrationKind};
24
25pub fn auth_headers(integration: &Integration, token: &str) -> Vec<(String, String)> {
27 let authorization = |value: String| ("Authorization".to_string(), value);
28 match integration.kind {
29 IntegrationKind::Github | IntegrationKind::GithubEnterprise => {
30 vec![authorization(format!("Bearer {token}"))]
31 }
32 IntegrationKind::Gitlab | IntegrationKind::GitlabSelfManaged => vec![
33 ("PRIVATE-TOKEN".to_string(), token.to_string()),
34 authorization(format!("Bearer {token}")),
35 ],
36 IntegrationKind::AzureDevops | IntegrationKind::AzureDevopsServer => {
37 vec![authorization(basic("", token))]
38 }
39 IntegrationKind::Bitbucket => {
40 let account = integration.account.trim();
41 if account.is_empty() {
42 vec![authorization(format!("Bearer {token}"))]
43 } else {
44 vec![authorization(basic(account, token))]
45 }
46 }
47 IntegrationKind::Gitea | IntegrationKind::Forgejo => {
49 vec![authorization(format!("token {token}"))]
50 }
51 IntegrationKind::Linear => vec![authorization(token.to_string())],
53 IntegrationKind::BitbucketDataCenter
54 | IntegrationKind::JiraDataCenter
55 | IntegrationKind::Youtrack => {
56 vec![authorization(format!("Bearer {token}"))]
57 }
58 IntegrationKind::JiraCloud => {
59 vec![authorization(basic(integration.account.trim(), token))]
60 }
61 IntegrationKind::Redmine => vec![("X-Redmine-API-Key".to_string(), token.to_string())],
63 IntegrationKind::Gerrit => vec![authorization(basic(integration.account.trim(), token))],
65 IntegrationKind::LocalMarkdown => Vec::new(),
66 IntegrationKind::Trello => vec![authorization(format!(
67 "OAuth oauth_consumer_key=\"{}\", oauth_token=\"{token}\"",
68 integration.account.trim()
69 ))],
70 }
71}
72
73fn basic(user: &str, token: &str) -> String {
74 format!("Basic {}", base64(format!("{user}:{token}").as_bytes()))
75}
76
77pub fn git_username(kind: IntegrationKind, account: &str, login: &str) -> Option<String> {
94 let (account, login) = (account.trim(), login.trim());
95 let first = |names: &[&str], fallback: &str| {
96 names
97 .iter()
98 .find(|n| !n.is_empty())
99 .copied()
100 .unwrap_or(fallback)
101 .to_string()
102 };
103 Some(match kind {
104 IntegrationKind::Github | IntegrationKind::GithubEnterprise => "x-access-token".into(),
105 IntegrationKind::Gitlab | IntegrationKind::GitlabSelfManaged => "oauth2".into(),
106 IntegrationKind::Bitbucket => first(&[account], "x-token-auth"),
107 IntegrationKind::BitbucketDataCenter => first(&[account, login], "x-token-auth"),
108 IntegrationKind::AzureDevops | IntegrationKind::AzureDevopsServer => {
109 first(&[account, login], "gitpoulpi")
110 }
111 IntegrationKind::Gitea | IntegrationKind::Forgejo => first(&[login, account], "git"),
112 IntegrationKind::Gerrit => first(&[account, login], "git"),
113 IntegrationKind::JiraCloud
114 | IntegrationKind::JiraDataCenter
115 | IntegrationKind::Trello
116 | IntegrationKind::Linear
117 | IntegrationKind::Youtrack
118 | IntegrationKind::Redmine
119 | IntegrationKind::LocalMarkdown => return None,
120 })
121}
122
123pub fn base64(input: &[u8]) -> String {
125 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
126 let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
127 for chunk in input.chunks(3) {
128 let n = (u32::from(chunk[0]) << 16)
129 | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
130 | u32::from(*chunk.get(2).unwrap_or(&0));
131 out.push(ALPHABET[(n >> 18) as usize & 63] as char);
132 out.push(ALPHABET[(n >> 12) as usize & 63] as char);
133 out.push(if chunk.len() > 1 {
134 ALPHABET[(n >> 6) as usize & 63] as char
135 } else {
136 '='
137 });
138 out.push(if chunk.len() > 2 {
139 ALPHABET[n as usize & 63] as char
140 } else {
141 '='
142 });
143 }
144 out
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn base64_matches_the_rfc_4648_vectors() {
153 for (input, want) in [
154 ("", ""),
155 ("f", "Zg=="),
156 ("fo", "Zm8="),
157 ("foo", "Zm9v"),
158 ("foob", "Zm9vYg=="),
159 ("fooba", "Zm9vYmE="),
160 ("foobar", "Zm9vYmFy"),
161 ] {
162 assert_eq!(base64(input.as_bytes()), want, "{input:?}");
163 }
164 }
165
166 #[test]
167 fn git_usernames_per_host() {
168 use IntegrationKind as K;
169 let name = git_username;
170 assert_eq!(
171 name(K::Github, "me", "me").as_deref(),
172 Some("x-access-token")
173 );
174 assert_eq!(
175 name(K::GithubEnterprise, "", "").as_deref(),
176 Some("x-access-token")
177 );
178 assert_eq!(name(K::Gitlab, "me", "").as_deref(), Some("oauth2"));
179 assert_eq!(
180 name(K::GitlabSelfManaged, "", "").as_deref(),
181 Some("oauth2")
182 );
183 assert_eq!(name(K::Bitbucket, "ada", "").as_deref(), Some("ada"));
184 assert_eq!(
185 name(K::Bitbucket, " ", "ada").as_deref(),
186 Some("x-token-auth")
187 );
188 assert_eq!(
189 name(K::BitbucketDataCenter, "", "ada").as_deref(),
190 Some("ada")
191 );
192 assert_eq!(name(K::AzureDevops, "", "").as_deref(), Some("gitpoulpi"));
193 assert_eq!(name(K::AzureDevops, "", "ada").as_deref(), Some("ada"));
194 assert_eq!(name(K::Gitea, "acct", "ada").as_deref(), Some("ada"));
195 assert_eq!(name(K::Forgejo, "acct", "").as_deref(), Some("acct"));
196 assert_eq!(name(K::Gerrit, "ada", "other").as_deref(), Some("ada"));
197 for k in [
198 K::JiraCloud,
199 K::JiraDataCenter,
200 K::Trello,
201 K::Linear,
202 K::Youtrack,
203 K::Redmine,
204 K::LocalMarkdown,
205 ] {
206 assert_eq!(name(k, "a", "b"), None, "{k:?}");
207 }
208 }
209
210 fn profile(kind: IntegrationKind, account: &str) -> Integration {
211 let mut i = Integration::new("x", kind, "https://h.example");
212 i.account = account.into();
213 i
214 }
215
216 fn headers(kind: IntegrationKind, account: &str) -> Vec<(String, String)> {
217 auth_headers(&profile(kind, account), "tok")
218 }
219
220 #[test]
221 fn every_kind_has_its_scheme() {
222 let bearer = vec![("Authorization".to_string(), "Bearer tok".to_string())];
223 let basic = |v: &str| vec![("Authorization".to_string(), format!("Basic {v}"))];
224 assert_eq!(base64(b":tok"), "OnRvaw==");
226 assert_eq!(base64(b"me@x:tok"), "bWVAeDp0b2s=");
227
228 assert_eq!(headers(IntegrationKind::Github, ""), bearer);
229 assert_eq!(headers(IntegrationKind::GithubEnterprise, ""), bearer);
230 for kind in [IntegrationKind::Gitlab, IntegrationKind::GitlabSelfManaged] {
231 assert_eq!(
232 headers(kind, ""),
233 vec![
234 ("PRIVATE-TOKEN".to_string(), "tok".to_string()),
235 ("Authorization".to_string(), "Bearer tok".to_string()),
236 ]
237 );
238 }
239 for kind in [
240 IntegrationKind::AzureDevops,
241 IntegrationKind::AzureDevopsServer,
242 ] {
243 assert_eq!(headers(kind, ""), basic("OnRvaw=="));
244 }
245 assert_eq!(
246 headers(IntegrationKind::Bitbucket, "me@x"),
247 basic("bWVAeDp0b2s=")
248 );
249 assert_eq!(
250 headers(IntegrationKind::Bitbucket, ""),
251 bearer,
252 "empty account"
253 );
254 assert_eq!(headers(IntegrationKind::Bitbucket, " "), bearer);
255 assert_eq!(headers(IntegrationKind::BitbucketDataCenter, ""), bearer);
256 assert_eq!(headers(IntegrationKind::JiraDataCenter, ""), bearer);
257 assert_eq!(
258 headers(IntegrationKind::JiraCloud, "me@x"),
259 basic("bWVAeDp0b2s=")
260 );
261 assert_eq!(
262 headers(IntegrationKind::Redmine, ""),
263 vec![("X-Redmine-API-Key".to_string(), "tok".to_string())]
264 );
265 assert_eq!(
267 headers(IntegrationKind::Gerrit, "me@x"),
268 basic("bWVAeDp0b2s=")
269 );
270 assert_eq!(
271 headers(IntegrationKind::Trello, "KEY"),
272 vec![(
273 "Authorization".to_string(),
274 "OAuth oauth_consumer_key=\"KEY\", oauth_token=\"tok\"".to_string()
275 )]
276 );
277 }
278
279 #[test]
280 fn a_token_never_lands_in_a_url_scheme() {
281 let h = headers(IntegrationKind::Trello, "KEY");
283 assert!(h.iter().all(|(k, _)| k == "Authorization"));
284 }
285}