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