1use std::collections::HashMap;
10use std::fmt;
11
12use base64::Engine as _;
13use serde_json::{Map, Value};
14
15#[derive(Clone, PartialEq, Eq)]
17pub enum AuthCredentials {
18 Basic { username: String, password: String },
20 Bearer { token: String },
22 GitHubToken { token: String },
24 GitLabToken { token: String },
27}
28
29impl fmt::Debug for AuthCredentials {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 match self {
32 Self::Basic { username, .. } => f
33 .debug_struct("Basic")
34 .field("username", username)
35 .field("password", &"<redacted>")
36 .finish(),
37 Self::Bearer { .. } => f
38 .debug_struct("Bearer")
39 .field("token", &"<redacted>")
40 .finish(),
41 Self::GitHubToken { .. } => f
42 .debug_struct("GitHubToken")
43 .field("token", &"<redacted>")
44 .finish(),
45 Self::GitLabToken { .. } => f
46 .debug_struct("GitLabToken")
47 .field("token", &"<redacted>")
48 .finish(),
49 }
50 }
51}
52
53impl AuthCredentials {
54 pub fn basic_from_userinfo(userinfo: &str) -> Self {
58 let (username, password) = userinfo.split_once(':').unwrap_or((userinfo, ""));
59 Self::Basic {
60 username: username.to_owned(),
61 password: password.to_owned(),
62 }
63 }
64
65 pub fn header_name(&self) -> &'static str {
67 match self {
68 Self::Basic { .. } | Self::Bearer { .. } | Self::GitHubToken { .. } => "authorization",
69 Self::GitLabToken { .. } => "private-token",
70 }
71 }
72
73 pub fn header_value(&self) -> String {
75 match self {
76 Self::Basic { username, password } => {
77 let encoded = base64::engine::general_purpose::STANDARD
78 .encode(format!("{username}:{password}"));
79 format!("Basic {encoded}")
80 }
81 Self::Bearer { token } => format!("Bearer {token}"),
82 Self::GitHubToken { token } => format!("token {token}"),
83 Self::GitLabToken { token } => token.clone(),
84 }
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct AuthError(String);
92
93impl fmt::Display for AuthError {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 f.write_str(&self.0)
96 }
97}
98
99impl std::error::Error for AuthError {}
100
101pub fn parse_auth_json(
105 raw: &str,
106 source: &str,
107) -> Result<HashMap<String, AuthCredentials>, AuthError> {
108 let raw = raw.trim();
109 if raw.is_empty() {
110 return Ok(HashMap::new());
111 }
112 let value: Value = serde_json::from_str(raw)
113 .map_err(|e| AuthError(format!("{source} is not valid JSON: {e}")))?;
114 let obj = value
115 .as_object()
116 .ok_or_else(|| AuthError(format!("{source} must be a JSON object")))?;
117 parse_auth_object(obj, source)
118}
119
120pub fn parse_auth_object(
125 obj: &Map<String, Value>,
126 source: &str,
127) -> Result<HashMap<String, AuthCredentials>, AuthError> {
128 let err = |msg: String| AuthError(format!("{source}: {msg}"));
129 let section = |key: &str| {
130 obj.get(key)
131 .and_then(Value::as_object)
132 .into_iter()
133 .flatten()
134 };
135 let string_token = |key: &str, host: &str, val: &Value| {
136 val.as_str()
137 .map(str::to_owned)
138 .ok_or_else(|| err(format!("{key}.{host} must be a string token")))
139 };
140
141 let mut out = HashMap::new();
142 for (host, val) in section("bearer") {
143 let token = string_token("bearer", host, val)?;
144 out.insert(host.clone(), AuthCredentials::Bearer { token });
145 }
146 for (host, val) in section("github-oauth") {
147 let token = string_token("github-oauth", host, val)?;
148 out.insert(host.clone(), AuthCredentials::GitHubToken { token });
149 }
150 for (host, val) in section("gitlab-oauth") {
151 let token = string_token("gitlab-oauth", host, val)?;
152 out.insert(host.clone(), AuthCredentials::Bearer { token });
153 }
154 for (host, val) in section("gitlab-token") {
155 let token = match val {
156 Value::String(s) => s.clone(),
157 Value::Object(o) => o
158 .get("token")
159 .and_then(Value::as_str)
160 .ok_or_else(|| {
161 err(format!(
162 "gitlab-token.{host}.token is missing or not a string"
163 ))
164 })?
165 .to_owned(),
166 _ => {
167 return Err(err(format!(
168 "gitlab-token.{host} must be a string or an object with `token`"
169 )));
170 }
171 };
172 out.insert(host.clone(), AuthCredentials::GitLabToken { token });
173 }
174 for (host, val) in section("http-basic") {
175 let entry = val.as_object().ok_or_else(|| {
176 err(format!(
177 "http-basic.{host} must be an object with `username` and `password`"
178 ))
179 })?;
180 let field = |name: &str| {
181 entry
182 .get(name)
183 .and_then(Value::as_str)
184 .map(str::to_owned)
185 .ok_or_else(|| {
186 err(format!(
187 "http-basic.{host}.{name} is missing or not a string"
188 ))
189 })
190 };
191 out.insert(
192 host.clone(),
193 AuthCredentials::Basic {
194 username: field("username")?,
195 password: field("password")?,
196 },
197 );
198 }
199 Ok(out)
200}
201
202pub fn auth_key(url: &str) -> Option<&str> {
207 let after_scheme = url.split_once("://")?.1;
208 let authority = after_scheme.split(['/', '?', '#']).next()?;
209 let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
210 (!host.is_empty()).then_some(host)
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use serde_json::json;
217
218 fn parse(v: &Value) -> Result<HashMap<String, AuthCredentials>, AuthError> {
219 parse_auth_object(v.as_object().unwrap(), "test")
220 }
221
222 #[test]
223 fn headers_match_composer() {
224 let cases = [
225 (
226 AuthCredentials::Basic {
227 username: "user".into(),
228 password: "pass".into(),
229 },
230 "authorization",
231 "Basic dXNlcjpwYXNz",
232 ),
233 (
234 AuthCredentials::Bearer { token: "t".into() },
235 "authorization",
236 "Bearer t",
237 ),
238 (
239 AuthCredentials::GitHubToken { token: "t".into() },
240 "authorization",
241 "token t",
242 ),
243 (
244 AuthCredentials::GitLabToken { token: "t".into() },
245 "private-token",
246 "t",
247 ),
248 ];
249 for (creds, name, value) in cases {
250 assert_eq!(creds.header_name(), name, "{creds:?}");
251 assert_eq!(creds.header_value(), value, "{creds:?}");
252 }
253 }
254
255 #[test]
256 fn basic_from_userinfo_splits_at_the_first_colon() {
257 assert_eq!(
258 AuthCredentials::basic_from_userinfo("token:a:b"),
259 AuthCredentials::Basic {
260 username: "token".into(),
261 password: "a:b".into()
262 }
263 );
264 assert_eq!(
265 AuthCredentials::basic_from_userinfo("alone"),
266 AuthCredentials::Basic {
267 username: "alone".into(),
268 password: String::new()
269 }
270 );
271 }
272
273 #[test]
274 fn parses_every_kind() {
275 let map = parse(&json!({
276 "http-basic": { "repo.example.com": { "username": "u", "password": "p" } },
277 "bearer": { "api.example.com": "b" },
278 "github-oauth": { "github.com": "g" },
279 "gitlab-oauth": { "gitlab.com": "o" },
280 "gitlab-token": { "gitlab.example.com": "t", "git.example.org": { "token": "t2" } },
281 "preferred-install": "dist"
282 }))
283 .unwrap();
284 assert_eq!(map.len(), 6);
285 assert_eq!(map["repo.example.com"].header_value(), "Basic dTpw");
286 assert_eq!(map["api.example.com"].header_value(), "Bearer b");
287 assert_eq!(map["github.com"].header_value(), "token g");
288 assert_eq!(map["gitlab.com"].header_value(), "Bearer o");
289 assert_eq!(map["gitlab.example.com"].header_name(), "private-token");
290 assert_eq!(map["git.example.org"].header_value(), "t2");
291 }
292
293 #[test]
294 fn errors_name_the_source_and_key_but_not_the_secret() {
295 let e = parse(&json!({"http-basic": {"h": {"username": "u", "password": 5}}})).unwrap_err();
296 assert_eq!(
297 e.to_string(),
298 "test: http-basic.h.password is missing or not a string"
299 );
300 let e = parse(&json!({"bearer": {"h": 1}})).unwrap_err();
301 assert_eq!(e.to_string(), "test: bearer.h must be a string token");
302 assert!(
303 parse_auth_json("[]", "COMPOSER_AUTH")
304 .unwrap_err()
305 .to_string()
306 .contains("COMPOSER_AUTH")
307 );
308 assert!(parse_auth_json(" ", "COMPOSER_AUTH").unwrap().is_empty());
309 }
310
311 #[test]
312 fn debug_redacts_secrets() {
313 let creds = AuthCredentials::Basic {
314 username: "user".into(),
315 password: "s3cret".into(),
316 };
317 let rendered = format!("{creds:?}");
318 assert!(rendered.contains("user"));
319 assert!(!rendered.contains("s3cret"), "{rendered}");
320 }
321
322 #[test]
323 fn auth_key_is_host_and_port() {
324 assert_eq!(
325 auth_key("https://repo.magento.com/archives/x.zip"),
326 Some("repo.magento.com")
327 );
328 assert_eq!(
329 auth_key("http://127.0.0.1:8080/p2/a/b.json"),
330 Some("127.0.0.1:8080")
331 );
332 assert_eq!(
333 auth_key("https://user:pw@host.example/x"),
334 Some("host.example")
335 );
336 assert_eq!(auth_key("https://host.example?x=1"), Some("host.example"));
337 assert_eq!(auth_key("file:///tmp/x.zip"), None);
338 assert_eq!(auth_key("/tmp/x.zip"), None);
339 }
340}