Skip to main content

eggfetch_core/
auth.rs

1//! Authentication subsystem for eggfetch.
2//!
3//! Provides Basic and Bearer authentication with redacted debug output,
4//! CR/LF injection prevention, and a central apply pipeline.
5//!
6//! Authentication is applied centrally in the client pipeline. Secrets
7//! are never exposed in `Debug`, `Display`, logs, or error messages.
8
9use crate::error::{Error, Result};
10
11/// An authentication scheme applied to outgoing requests.
12///
13/// Authentication is configured at the client level and can be overridden
14/// or disabled per-request. The client applies auth centrally before
15/// sending, after default headers but before the hyper request is built.
16///
17/// # Precedence
18///
19/// 1. Request-level explicit auth (via [`RequestBuilder::auth`])
20/// 2. Request-level auth disabled (via [`RequestBuilder::without_auth`])
21/// 3. Client-level auth (via [`ClientBuilder::auth`])
22/// 4. No auth
23///
24/// [`RequestBuilder::auth`]: crate::request::RequestBuilder::auth
25/// [`RequestBuilder::without_auth`]: crate::request::RequestBuilder::without_auth
26/// [`ClientBuilder::auth`]: crate::client::ClientBuilder::auth
27#[derive(Clone)]
28pub enum AuthScheme {
29    /// HTTP Basic Authentication (`Authorization: Basic <credentials>`).
30    Basic(BasicAuth),
31    /// HTTP Bearer Token Authentication (`Authorization: Bearer <token>`).
32    Bearer(BearerAuth),
33}
34
35impl AuthScheme {
36    /// Create a Basic auth scheme from username and password.
37    ///
38    /// # Errors
39    ///
40    /// Returns [`Error::InvalidAuthHeader`] if the username contains `:`
41    /// or if credentials contain invalid header-value bytes.
42    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Result<Self> {
43        Ok(Self::Basic(BasicAuth::new(username, password)?))
44    }
45
46    /// Create a Bearer auth scheme from a token.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`Error::InvalidAuthHeader`] if the token contains CR/LF
51    /// or invalid header-value bytes.
52    pub fn bearer(token: impl Into<String>) -> Result<Self> {
53        Ok(Self::Bearer(BearerAuth::new(token)?))
54    }
55
56    /// Apply this auth scheme to the request headers.
57    ///
58    /// Sets the `Authorization` header to the appropriate value.
59    /// Returns an error if the header value is invalid.
60    pub(crate) fn apply(&self, headers: &mut crate::headers::Headers) -> Result<()> {
61        match self {
62            Self::Basic(b) => {
63                let value = b.header_value();
64                headers.insert("authorization", &value)?;
65            }
66            Self::Bearer(b) => {
67                let value = b.header_value();
68                headers.insert("authorization", &value)?;
69            }
70        }
71        Ok(())
72    }
73}
74
75impl std::fmt::Debug for AuthScheme {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Self::Basic(b) => f.debug_tuple("Basic").field(b).finish(),
79            Self::Bearer(b) => f.debug_tuple("Bearer").field(b).finish(),
80        }
81    }
82}
83
84/// HTTP Basic Authentication credentials.
85///
86/// Generates `Authorization: Basic base64(username:password)` headers.
87///
88/// # Security
89///
90/// The `Debug` and `Display` implementations redact both username and
91/// password. Credentials are never exposed in error messages or logs.
92///
93/// # Policy
94///
95/// - Usernames containing `:` are rejected (RFC 7617 ambiguity).
96/// - Passwords may be empty.
97/// - Credentials are encoded as UTF-8 bytes.
98/// - CR/LF characters in username or password are rejected.
99#[derive(Clone)]
100pub struct BasicAuth {
101    username: String,
102    password: String,
103}
104
105impl BasicAuth {
106    /// Create new Basic auth credentials.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`Error::InvalidAuthHeader`] if:
111    /// - The username contains `:`
112    /// - The username or password contains CR (`\r`) or LF (`\n`)
113    /// - The credentials produce an invalid header value
114    pub fn new(username: impl Into<String>, password: impl Into<String>) -> Result<Self> {
115        let username = username.into();
116        let password = password.into();
117
118        if username.contains(':') {
119            return Err(Error::InvalidAuthHeader(
120                "basic auth username must not contain ':'".into(),
121            ));
122        }
123
124        validate_auth_bytes(username.as_bytes(), "username")?;
125        validate_auth_bytes(password.as_bytes(), "password")?;
126
127        Ok(Self { username, password })
128    }
129
130    /// Returns the Base64-encoded header value (without the scheme prefix).
131    fn encoded_credentials(&self) -> String {
132        use base64::Engine;
133        let credential = format!("{}:{}", self.username, self.password);
134        base64::engine::general_purpose::STANDARD.encode(credential.as_bytes())
135    }
136
137    /// Returns the full `Authorization` header value.
138    fn header_value(&self) -> String {
139        format!("Basic {}", self.encoded_credentials())
140    }
141
142    /// Returns a reference to the username.
143    #[must_use]
144    pub fn username(&self) -> &str {
145        &self.username
146    }
147}
148
149impl std::fmt::Debug for BasicAuth {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        f.debug_struct("BasicAuth")
152            .field("username", &"<redacted>")
153            .field("password", &"<redacted>")
154            .finish()
155    }
156}
157
158impl std::fmt::Display for BasicAuth {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.write_str("BasicAuth(<redacted>)")
161    }
162}
163
164/// HTTP Bearer Token Authentication credentials.
165///
166/// Generates `Authorization: Bearer <token>` headers.
167///
168/// # Security
169///
170/// The `Debug` and `Display` implementations redact the token.
171/// The raw token is never exposed in error messages or logs.
172///
173/// # Validation
174///
175/// - CR (`\r`) and LF (`\n`) characters are rejected to prevent header injection.
176/// - No token format assumptions beyond header safety.
177#[derive(Clone)]
178pub struct BearerAuth {
179    token: String,
180}
181
182impl BearerAuth {
183    /// Create new Bearer auth credentials.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`Error::InvalidAuthHeader`] if the token contains CR/LF
188    /// or produces an invalid header value.
189    pub fn new(token: impl Into<String>) -> Result<Self> {
190        let token = token.into();
191        validate_auth_bytes(token.as_bytes(), "token")?;
192        let header = format!("Bearer {token}");
193        http::HeaderValue::from_str(&header).map_err(|_| {
194            Error::InvalidAuthHeader(
195                "auth token must contain only characters valid in an HTTP header".into(),
196            )
197        })?;
198        Ok(Self { token })
199    }
200
201    /// Returns the full `Authorization` header value.
202    fn header_value(&self) -> String {
203        format!("Bearer {}", self.token)
204    }
205}
206
207impl std::fmt::Debug for BearerAuth {
208    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209        f.debug_struct("BearerAuth")
210            .field("token", &"<redacted>")
211            .finish()
212    }
213}
214
215impl std::fmt::Display for BearerAuth {
216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217        write!(f, "BearerAuth(<redacted>)")
218    }
219}
220
221/// Validate that auth credential bytes are safe for use in header values.
222///
223/// Rejects CR and LF to prevent header injection.
224fn validate_auth_bytes(bytes: &[u8], field_name: &str) -> Result<()> {
225    if bytes.contains(&b'\r') {
226        return Err(Error::InvalidAuthHeader(format!(
227            "auth {field_name} must not contain CR"
228        )));
229    }
230    if bytes.contains(&b'\n') {
231        return Err(Error::InvalidAuthHeader(format!(
232            "auth {field_name} must not contain LF"
233        )));
234    }
235    Ok(())
236}
237
238/// Determine the effective auth for a request.
239///
240/// Precedence:
241/// 1. Request-level explicit auth
242/// 2. Request-level auth disabled
243/// 3. Client-level auth
244/// 4. No auth
245///
246/// If the request has an explicit `Authorization` header AND auth is
247/// configured, returns `Err` to avoid ambiguity (the user must choose
248/// one or the other).
249pub(crate) fn resolve_request_auth(
250    request_auth: Option<&AuthScheme>,
251    request_auth_disabled: bool,
252    client_auth: Option<&AuthScheme>,
253    request_headers: &crate::headers::Headers,
254) -> Result<Option<AuthScheme>> {
255    // Check for conflicting Authorization header + auth config.
256    if request_headers.contains("authorization") {
257        if request_auth.is_some() || client_auth.is_some() {
258            return Err(Error::ConflictingAuth(
259                "explicit Authorization header conflicts with configured auth; \
260                 use .auth() or remove the header, but not both"
261                    .into(),
262            ));
263        }
264        // User set a raw Authorization header with no auth config — that's fine.
265        return Ok(None);
266    }
267
268    // Request-level explicit auth overrides everything.
269    if let Some(auth) = request_auth {
270        return Ok(Some(auth.clone()));
271    }
272
273    // Request-level auth disabled.
274    if request_auth_disabled {
275        return Ok(None);
276    }
277
278    // Client-level auth.
279    if let Some(auth) = client_auth {
280        return Ok(Some(auth.clone()));
281    } // No auth.
282    Ok(None)
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use base64::Engine;
289
290    // --- BasicAuth tests ---
291
292    #[test]
293    fn basic_auth_header_value() {
294        let auth = BasicAuth::new("user", "pass").unwrap();
295        // user:pass = "dXNlcjpwYXNz" in base64
296        assert_eq!(auth.header_value(), "Basic dXNlcjpwYXNz");
297    }
298
299    #[test]
300    fn basic_auth_empty_password() {
301        let auth = BasicAuth::new("user", "").unwrap();
302        // user: = "dXNlcjo=" in base64
303        assert_eq!(auth.header_value(), "Basic dXNlcjo=");
304    }
305
306    #[test]
307    fn basic_auth_utf8_credentials() {
308        use base64::Engine;
309        let auth = BasicAuth::new("usér", "päss").unwrap();
310        assert!(auth.header_value().starts_with("Basic "));
311        // Verify it can be decoded
312        let header_val = auth.header_value();
313        let encoded = header_val.strip_prefix("Basic ").unwrap();
314        let decoded = base64::engine::general_purpose::STANDARD
315            .decode(encoded)
316            .unwrap();
317        assert_eq!(String::from_utf8(decoded).unwrap(), "usér:päss");
318    }
319
320    #[test]
321    fn basic_auth_rejects_colon_in_username() {
322        let err = BasicAuth::new("user:name", "pass").unwrap_err();
323        assert_eq!(err.kind(), "invalid_auth_header");
324        assert!(!err.to_string().contains("pass"));
325    }
326
327    #[test]
328    fn basic_auth_rejects_cr_in_username() {
329        let err = BasicAuth::new("user\r", "pass").unwrap_err();
330        assert_eq!(err.kind(), "invalid_auth_header");
331    }
332
333    #[test]
334    fn basic_auth_rejects_lf_in_password() {
335        let err = BasicAuth::new("user", "pass\n").unwrap_err();
336        assert_eq!(err.kind(), "invalid_auth_header");
337    }
338
339    #[test]
340    fn basic_auth_redacted_debug() {
341        let auth = BasicAuth::new("user", "secret123").unwrap();
342        let debug = format!("{auth:?}");
343        assert!(!debug.contains("\"user\""));
344        assert!(debug.contains("<redacted>"));
345        assert!(!debug.contains("secret123"));
346    }
347
348    #[test]
349    fn basic_auth_redacted_display() {
350        let auth = BasicAuth::new("user", "secret123").unwrap();
351        let display = format!("{auth}");
352        assert!(!display.contains("user"));
353        assert!(!display.contains("secret123"));
354        assert!(display.contains("<redacted>"));
355    }
356
357    #[test]
358    fn basic_auth_username_accessor() {
359        let auth = BasicAuth::new("admin", "pw").unwrap();
360        assert_eq!(auth.username(), "admin");
361    }
362
363    // --- BearerAuth tests ---
364
365    #[test]
366    fn bearer_auth_header_value() {
367        let auth = BearerAuth::new("my-token").unwrap();
368        assert_eq!(auth.header_value(), "Bearer my-token");
369    }
370
371    #[test]
372    fn bearer_auth_rejects_cr() {
373        let err = BearerAuth::new("tok\r").unwrap_err();
374        assert_eq!(err.kind(), "invalid_auth_header");
375    }
376
377    #[test]
378    fn bearer_auth_rejects_lf() {
379        let err = BearerAuth::new("tok\n").unwrap_err();
380        assert_eq!(err.kind(), "invalid_auth_header");
381    }
382
383    #[test]
384    fn bearer_auth_redacted_debug() {
385        let auth = BearerAuth::new("secret-token").unwrap();
386        let debug = format!("{auth:?}");
387        assert!(debug.contains("<redacted>"));
388        assert!(!debug.contains("secret-token"));
389    }
390
391    #[test]
392    fn bearer_auth_redacted_display() {
393        let auth = BearerAuth::new("secret-token").unwrap();
394        let display = format!("{auth}");
395        assert!(display.contains("<redacted>"));
396        assert!(!display.contains("secret-token"));
397    }
398
399    // --- AuthScheme tests ---
400
401    #[test]
402    fn auth_scheme_debug() {
403        let scheme = AuthScheme::basic("user", "pass").unwrap();
404        let debug = format!("{scheme:?}");
405        assert!(debug.contains("Basic"));
406
407        let scheme = AuthScheme::bearer("token").unwrap();
408        let debug = format!("{scheme:?}");
409        assert!(debug.contains("Bearer"));
410    }
411
412    // --- resolve_request_auth tests ---
413
414    #[test]
415    fn resolve_no_auth() {
416        let headers = crate::headers::Headers::new();
417        let result = resolve_request_auth(None, false, None, &headers).unwrap();
418        assert!(result.is_none());
419    }
420
421    #[test]
422    fn resolve_client_auth() {
423        let headers = crate::headers::Headers::new();
424        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
425        let result = resolve_request_auth(None, false, client_auth.as_ref(), &headers).unwrap();
426        assert!(result.is_some());
427    }
428
429    #[test]
430    fn resolve_request_auth_overrides_client() {
431        let headers = crate::headers::Headers::new();
432        let request_auth = Some(AuthScheme::bearer("req-tok").unwrap());
433        let client_auth = Some(AuthScheme::bearer("client-tok").unwrap());
434        let result =
435            resolve_request_auth(request_auth.as_ref(), false, client_auth.as_ref(), &headers)
436                .unwrap();
437        let auth = result.unwrap();
438        match auth {
439            AuthScheme::Bearer(b) => {
440                assert_eq!(b.header_value(), "Bearer req-tok");
441            }
442            AuthScheme::Basic(_) => panic!("expected Bearer"),
443        }
444    }
445
446    #[test]
447    fn resolve_auth_disabled() {
448        let headers = crate::headers::Headers::new();
449        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
450        let result = resolve_request_auth(None, true, client_auth.as_ref(), &headers).unwrap();
451        assert!(result.is_none());
452    }
453
454    #[test]
455    fn resolve_explicit_header_conflicts_with_auth() {
456        let mut headers = crate::headers::Headers::new();
457        headers.insert("authorization", "Bearer manual").unwrap();
458        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
459        let err = resolve_request_auth(None, false, client_auth.as_ref(), &headers).unwrap_err();
460        assert_eq!(err.kind(), "conflicting_auth");
461    }
462
463    #[test]
464    fn resolve_explicit_header_no_auth_config() {
465        let mut headers = crate::headers::Headers::new();
466        headers.insert("authorization", "Bearer manual").unwrap();
467        let result = resolve_request_auth(None, false, None, &headers).unwrap();
468        assert!(result.is_none());
469    }
470
471    #[test]
472    fn resolve_request_auth_disabled_overrides_client() {
473        let headers = crate::headers::Headers::new();
474        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
475        let result = resolve_request_auth(None, true, client_auth.as_ref(), &headers).unwrap();
476        assert!(result.is_none());
477    }
478
479    // --- Edge-case tests (Track C) ---
480
481    #[test]
482    fn resolve_no_auth_is_same_as_absent() {
483        let headers = crate::headers::Headers::new();
484        // None (not set) vs None (explicitly no auth) — same result
485        let r1 = resolve_request_auth(None, false, None, &headers).unwrap();
486        let r2 = resolve_request_auth(None, false, None, &headers).unwrap();
487        assert_eq!(r1.is_none(), r2.is_none());
488    }
489
490    #[test]
491    fn auth_scheme_debug_does_not_leak_basic_password() {
492        let scheme = AuthScheme::basic("admin", "hunter2").unwrap();
493        let debug = format!("{scheme:?}");
494        assert!(!debug.contains("admin"));
495        assert!(!debug.contains("hunter2"));
496        assert!(debug.contains("<redacted>"));
497    }
498
499    #[test]
500    fn auth_scheme_debug_does_not_leak_bearer_token() {
501        let scheme = AuthScheme::bearer("secret-value").unwrap();
502        let debug = format!("{scheme:?}");
503        assert!(!debug.contains("secret-value"));
504        assert!(debug.contains("<redacted>"));
505    }
506
507    #[test]
508    fn basic_auth_empty_username_and_password() {
509        let auth = BasicAuth::new("", "").unwrap();
510        // "" ":" "" → base64(":")
511        let expected = base64::engine::general_purpose::STANDARD.encode(b":");
512        assert_eq!(auth.header_value(), format!("Basic {expected}"));
513    }
514
515    #[test]
516    fn bearer_auth_empty_token() {
517        let auth = BearerAuth::new("").unwrap();
518        assert_eq!(auth.header_value(), "Bearer ");
519    }
520
521    #[test]
522    fn basic_auth_colon_in_password_is_allowed() {
523        let auth = BasicAuth::new("user", "p:a:s:s").unwrap();
524        let expected = base64::engine::general_purpose::STANDARD.encode(b"user:p:a:s:s");
525        assert_eq!(auth.header_value(), format!("Basic {expected}"));
526    }
527
528    #[test]
529    fn bearer_auth_with_spaces_in_token() {
530        let auth = BearerAuth::new("token with spaces").unwrap();
531        assert_eq!(auth.header_value(), "Bearer token with spaces");
532    }
533
534    #[test]
535    fn bearer_auth_with_unicode_token() {
536        let auth = BearerAuth::new("tökën-üñîçödé").unwrap();
537        assert!(auth.header_value().starts_with("Bearer "));
538        assert!(auth.header_value().contains("tökën-üñîçödé"));
539    }
540
541    #[test]
542    fn basic_auth_header_format() {
543        let auth = BasicAuth::new("user", "pass").unwrap();
544        let val = auth.header_value();
545        assert!(val.starts_with("Basic "), "must start with 'Basic '");
546        // The rest must be valid base64
547        let encoded = val.strip_prefix("Basic ").unwrap();
548        let decoded = base64::engine::general_purpose::STANDARD
549            .decode(encoded)
550            .unwrap();
551        assert_eq!(String::from_utf8(decoded).unwrap(), "user:pass");
552    }
553
554    #[test]
555    fn bearer_auth_header_format() {
556        let auth = BearerAuth::new("my-token-123").unwrap();
557        let val = auth.header_value();
558        assert_eq!(val, "Bearer my-token-123");
559    }
560
561    #[test]
562    fn double_resolution_is_idempotent() {
563        let headers = crate::headers::Headers::new();
564        let client_auth = Some(AuthScheme::bearer("client-tok").unwrap());
565        let request_auth = Some(AuthScheme::bearer("req-tok").unwrap());
566
567        // First resolution: request auth overrides client
568        let first =
569            resolve_request_auth(request_auth.as_ref(), false, client_auth.as_ref(), &headers)
570                .unwrap();
571        assert!(first.is_some());
572
573        // Second resolution: result + no auth → result passes through
574        let second = resolve_request_auth(first.as_ref(), false, None, &headers).unwrap();
575        match second.unwrap() {
576            AuthScheme::Bearer(b) => assert_eq!(b.header_value(), "Bearer req-tok"),
577            AuthScheme::Basic(_) => panic!("expected Bearer"),
578        }
579    }
580
581    #[test]
582    fn request_builder_without_auth_sets_disabled_and_clears_auth() {
583        let client = crate::client::Client::builder().build();
584        let req = client
585            .request(http::Method::GET, "http://example.com")
586            .unwrap()
587            .auth(AuthScheme::bearer("tok").unwrap())
588            .without_auth()
589            .build()
590            .unwrap();
591
592        assert!(req.is_auth_disabled());
593        assert!(req.auth().is_none());
594    }
595
596    #[test]
597    fn request_builder_auth_clears_disabled() {
598        let client = crate::client::Client::builder().build();
599        let req = client
600            .request(http::Method::GET, "http://example.com")
601            .unwrap()
602            .without_auth()
603            .auth(AuthScheme::bearer("tok").unwrap())
604            .build()
605            .unwrap();
606
607        assert!(!req.is_auth_disabled());
608        assert!(req.auth().is_some());
609    }
610
611    #[test]
612    fn basic_auth_display_shows_username_not_password() {
613        let auth = BasicAuth::new("admin", "s3cret").unwrap();
614        let display = format!("{auth}");
615        assert!(!display.contains("admin"));
616        assert!(!display.contains("s3cret"));
617        assert!(display.contains("<redacted>"));
618    }
619
620    #[test]
621    fn bearer_auth_display_redacts_token() {
622        let auth = BearerAuth::new("my-secret-token").unwrap();
623        let display = format!("{auth}");
624        assert!(!display.contains("my-secret-token"));
625        assert!(display.contains("<redacted>"));
626    }
627
628    #[test]
629    fn resolve_request_overrides_client_different_types() {
630        let headers = crate::headers::Headers::new();
631        let client_auth = Some(AuthScheme::basic("c", "cp").unwrap());
632        let request_auth = Some(AuthScheme::bearer("req-tok").unwrap());
633        let result =
634            resolve_request_auth(request_auth.as_ref(), false, client_auth.as_ref(), &headers)
635                .unwrap();
636        match result.unwrap() {
637            AuthScheme::Bearer(b) => assert_eq!(b.header_value(), "Bearer req-tok"),
638            AuthScheme::Basic(_) => panic!("expected Bearer"),
639        }
640    }
641}