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 the password.
91/// The raw password is 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", &self.username)
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        write!(f, "BasicAuth(username={})", self.username)
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    }
355
356    #[test]
357    fn basic_auth_username_accessor() {
358        let auth = BasicAuth::new("admin", "pw").unwrap();
359        assert_eq!(auth.username(), "admin");
360    }
361
362    // --- BearerAuth tests ---
363
364    #[test]
365    fn bearer_auth_header_value() {
366        let auth = BearerAuth::new("my-token").unwrap();
367        assert_eq!(auth.header_value(), "Bearer my-token");
368    }
369
370    #[test]
371    fn bearer_auth_rejects_cr() {
372        let err = BearerAuth::new("tok\r").unwrap_err();
373        assert_eq!(err.kind(), "invalid_auth_header");
374    }
375
376    #[test]
377    fn bearer_auth_rejects_lf() {
378        let err = BearerAuth::new("tok\n").unwrap_err();
379        assert_eq!(err.kind(), "invalid_auth_header");
380    }
381
382    #[test]
383    fn bearer_auth_redacted_debug() {
384        let auth = BearerAuth::new("secret-token").unwrap();
385        let debug = format!("{auth:?}");
386        assert!(debug.contains("<redacted>"));
387        assert!(!debug.contains("secret-token"));
388    }
389
390    #[test]
391    fn bearer_auth_redacted_display() {
392        let auth = BearerAuth::new("secret-token").unwrap();
393        let display = format!("{auth}");
394        assert!(display.contains("<redacted>"));
395        assert!(!display.contains("secret-token"));
396    }
397
398    // --- AuthScheme tests ---
399
400    #[test]
401    fn auth_scheme_debug() {
402        let scheme = AuthScheme::basic("user", "pass").unwrap();
403        let debug = format!("{scheme:?}");
404        assert!(debug.contains("Basic"));
405
406        let scheme = AuthScheme::bearer("token").unwrap();
407        let debug = format!("{scheme:?}");
408        assert!(debug.contains("Bearer"));
409    }
410
411    // --- resolve_request_auth tests ---
412
413    #[test]
414    fn resolve_no_auth() {
415        let headers = crate::headers::Headers::new();
416        let result = resolve_request_auth(None, false, None, &headers).unwrap();
417        assert!(result.is_none());
418    }
419
420    #[test]
421    fn resolve_client_auth() {
422        let headers = crate::headers::Headers::new();
423        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
424        let result = resolve_request_auth(None, false, client_auth.as_ref(), &headers).unwrap();
425        assert!(result.is_some());
426    }
427
428    #[test]
429    fn resolve_request_auth_overrides_client() {
430        let headers = crate::headers::Headers::new();
431        let request_auth = Some(AuthScheme::bearer("req-tok").unwrap());
432        let client_auth = Some(AuthScheme::bearer("client-tok").unwrap());
433        let result =
434            resolve_request_auth(request_auth.as_ref(), false, client_auth.as_ref(), &headers)
435                .unwrap();
436        let auth = result.unwrap();
437        match auth {
438            AuthScheme::Bearer(b) => {
439                assert_eq!(b.header_value(), "Bearer req-tok");
440            }
441            AuthScheme::Basic(_) => panic!("expected Bearer"),
442        }
443    }
444
445    #[test]
446    fn resolve_auth_disabled() {
447        let headers = crate::headers::Headers::new();
448        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
449        let result = resolve_request_auth(None, true, client_auth.as_ref(), &headers).unwrap();
450        assert!(result.is_none());
451    }
452
453    #[test]
454    fn resolve_explicit_header_conflicts_with_auth() {
455        let mut headers = crate::headers::Headers::new();
456        headers.insert("authorization", "Bearer manual").unwrap();
457        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
458        let err = resolve_request_auth(None, false, client_auth.as_ref(), &headers).unwrap_err();
459        assert_eq!(err.kind(), "conflicting_auth");
460    }
461
462    #[test]
463    fn resolve_explicit_header_no_auth_config() {
464        let mut headers = crate::headers::Headers::new();
465        headers.insert("authorization", "Bearer manual").unwrap();
466        let result = resolve_request_auth(None, false, None, &headers).unwrap();
467        assert!(result.is_none());
468    }
469
470    #[test]
471    fn resolve_request_auth_disabled_overrides_client() {
472        let headers = crate::headers::Headers::new();
473        let client_auth = Some(AuthScheme::bearer("tok").unwrap());
474        let result = resolve_request_auth(None, true, client_auth.as_ref(), &headers).unwrap();
475        assert!(result.is_none());
476    }
477
478    // --- Edge-case tests (Track C) ---
479
480    #[test]
481    fn resolve_no_auth_is_same_as_absent() {
482        let headers = crate::headers::Headers::new();
483        // None (not set) vs None (explicitly no auth) — same result
484        let r1 = resolve_request_auth(None, false, None, &headers).unwrap();
485        let r2 = resolve_request_auth(None, false, None, &headers).unwrap();
486        assert_eq!(r1.is_none(), r2.is_none());
487    }
488
489    #[test]
490    fn auth_scheme_debug_does_not_leak_basic_password() {
491        let scheme = AuthScheme::basic("admin", "hunter2").unwrap();
492        let debug = format!("{scheme:?}");
493        assert!(debug.contains("admin"));
494        assert!(!debug.contains("hunter2"));
495        assert!(debug.contains("<redacted>"));
496    }
497
498    #[test]
499    fn auth_scheme_debug_does_not_leak_bearer_token() {
500        let scheme = AuthScheme::bearer("secret-value").unwrap();
501        let debug = format!("{scheme:?}");
502        assert!(!debug.contains("secret-value"));
503        assert!(debug.contains("<redacted>"));
504    }
505
506    #[test]
507    fn basic_auth_empty_username_and_password() {
508        let auth = BasicAuth::new("", "").unwrap();
509        // "" ":" "" → base64(":")
510        let expected = base64::engine::general_purpose::STANDARD.encode(b":");
511        assert_eq!(auth.header_value(), format!("Basic {expected}"));
512    }
513
514    #[test]
515    fn bearer_auth_empty_token() {
516        let auth = BearerAuth::new("").unwrap();
517        assert_eq!(auth.header_value(), "Bearer ");
518    }
519
520    #[test]
521    fn basic_auth_colon_in_password_is_allowed() {
522        let auth = BasicAuth::new("user", "p:a:s:s").unwrap();
523        let expected = base64::engine::general_purpose::STANDARD.encode(b"user:p:a:s:s");
524        assert_eq!(auth.header_value(), format!("Basic {expected}"));
525    }
526
527    #[test]
528    fn bearer_auth_with_spaces_in_token() {
529        let auth = BearerAuth::new("token with spaces").unwrap();
530        assert_eq!(auth.header_value(), "Bearer token with spaces");
531    }
532
533    #[test]
534    fn bearer_auth_with_unicode_token() {
535        let auth = BearerAuth::new("tökën-üñîçödé").unwrap();
536        assert!(auth.header_value().starts_with("Bearer "));
537        assert!(auth.header_value().contains("tökën-üñîçödé"));
538    }
539
540    #[test]
541    fn basic_auth_header_format() {
542        let auth = BasicAuth::new("user", "pass").unwrap();
543        let val = auth.header_value();
544        assert!(val.starts_with("Basic "), "must start with 'Basic '");
545        // The rest must be valid base64
546        let encoded = val.strip_prefix("Basic ").unwrap();
547        let decoded = base64::engine::general_purpose::STANDARD
548            .decode(encoded)
549            .unwrap();
550        assert_eq!(String::from_utf8(decoded).unwrap(), "user:pass");
551    }
552
553    #[test]
554    fn bearer_auth_header_format() {
555        let auth = BearerAuth::new("my-token-123").unwrap();
556        let val = auth.header_value();
557        assert_eq!(val, "Bearer my-token-123");
558    }
559
560    #[test]
561    fn double_resolution_is_idempotent() {
562        let headers = crate::headers::Headers::new();
563        let client_auth = Some(AuthScheme::bearer("client-tok").unwrap());
564        let request_auth = Some(AuthScheme::bearer("req-tok").unwrap());
565
566        // First resolution: request auth overrides client
567        let first =
568            resolve_request_auth(request_auth.as_ref(), false, client_auth.as_ref(), &headers)
569                .unwrap();
570        assert!(first.is_some());
571
572        // Second resolution: result + no auth → result passes through
573        let second = resolve_request_auth(first.as_ref(), false, None, &headers).unwrap();
574        match second.unwrap() {
575            AuthScheme::Bearer(b) => assert_eq!(b.header_value(), "Bearer req-tok"),
576            AuthScheme::Basic(_) => panic!("expected Bearer"),
577        }
578    }
579
580    #[test]
581    fn request_builder_without_auth_sets_disabled_and_clears_auth() {
582        let client = crate::client::Client::builder().build();
583        let req = client
584            .request(http::Method::GET, "http://example.com")
585            .unwrap()
586            .auth(AuthScheme::bearer("tok").unwrap())
587            .without_auth()
588            .build()
589            .unwrap();
590
591        assert!(req.is_auth_disabled());
592        assert!(req.auth().is_none());
593    }
594
595    #[test]
596    fn request_builder_auth_clears_disabled() {
597        let client = crate::client::Client::builder().build();
598        let req = client
599            .request(http::Method::GET, "http://example.com")
600            .unwrap()
601            .without_auth()
602            .auth(AuthScheme::bearer("tok").unwrap())
603            .build()
604            .unwrap();
605
606        assert!(!req.is_auth_disabled());
607        assert!(req.auth().is_some());
608    }
609
610    #[test]
611    fn basic_auth_display_shows_username_not_password() {
612        let auth = BasicAuth::new("admin", "s3cret").unwrap();
613        let display = format!("{auth}");
614        assert!(display.contains("admin"));
615        assert!(!display.contains("s3cret"));
616        assert!(display.starts_with("BasicAuth(username="));
617    }
618
619    #[test]
620    fn bearer_auth_display_redacts_token() {
621        let auth = BearerAuth::new("my-secret-token").unwrap();
622        let display = format!("{auth}");
623        assert!(!display.contains("my-secret-token"));
624        assert!(display.contains("<redacted>"));
625    }
626
627    #[test]
628    fn resolve_request_overrides_client_different_types() {
629        let headers = crate::headers::Headers::new();
630        let client_auth = Some(AuthScheme::basic("c", "cp").unwrap());
631        let request_auth = Some(AuthScheme::bearer("req-tok").unwrap());
632        let result =
633            resolve_request_auth(request_auth.as_ref(), false, client_auth.as_ref(), &headers)
634                .unwrap();
635        match result.unwrap() {
636            AuthScheme::Bearer(b) => assert_eq!(b.header_value(), "Bearer req-tok"),
637            AuthScheme::Basic(_) => panic!("expected Bearer"),
638        }
639    }
640}