huskarl 0.8.0

A modern OAuth2 client library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Authorizer for `OAuth2` grants.
//!
//! [`HttpAuthorizer`] turns the token machinery (grant, cache, `DPoP`) into
//! request headers: [`get_headers`](HttpAuthorizer::get_headers) builds the
//! authorization headers for a request — exchanging or refreshing tokens as
//! needed — and [`process_response`](HttpAuthorizer::process_response)
//! records what each response reveals.
//!
//! The request loop:
//!
//! 1. Build headers with [`get_headers`](HttpAuthorizer::get_headers) and
//!    send the request with your HTTP client.
//! 2. Pass every response's headers — success or failure — to
//!    [`process_response`](HttpAuthorizer::process_response).
//! 3. On a `401 Unauthorized`, rebuild the headers and re-send **once** if
//!    your API semantics allow: step 2 already recorded any demanded `DPoP`
//!    nonce and dropped a token the server rejected, so the rebuilt headers
//!    carry the fix if there is one. A second `401` is definitive.
//!
//! ```rust
//! # use huskarl::authorizer::{HttpAuthorizer, parse_challenges};
//! # use http::{HeaderMap, Method, StatusCode, Uri};
//! # struct Response { status: StatusCode, headers: HeaderMap }
//! # async fn send(_headers: HeaderMap) -> Response {
//! #     Response { status: StatusCode::OK, headers: HeaderMap::new() }
//! # }
//! # async fn example(authorizer: &HttpAuthorizer) -> Result<(), huskarl::core::Error> {
//! let uri: Uri = "https://api.example.com/v1/widgets".parse().unwrap();
//!
//! let headers = authorizer.get_headers(&Method::GET, &uri).await?;
//! let mut response = send(headers).await;
//! authorizer.process_response(&uri, &response.headers);
//!
//! if response.status == StatusCode::UNAUTHORIZED {
//!     // Optional: the WWW-Authenticate challenges say what the server
//!     // objected to. `insufficient_scope` needs broader authorization —
//!     // re-sending cannot fix it.
//!     let scope_problem = parse_challenges(&response.headers)
//!         .iter()
//!         .any(|challenge| challenge.error() == Some("insufficient_scope"));
//!
//!     if !scope_problem {
//!         let headers = authorizer.get_headers(&Method::GET, &uri).await?;
//!         response = send(headers).await;
//!         authorizer.process_response(&uri, &response.headers);
//!     }
//! }
//! # drop(response);
//! # Ok(())
//! # }
//! ```
//!
//! Whether and when to re-send is the application's decision, not this
//! library's — [`parse_challenges`] exposes the server's stated objection
//! for making it, as above. A `401` is issued before the request is
//! processed, so a single re-send is normally safe even for non-idempotent
//! requests.
//!
//! Step 2's automatic token invalidation works only when the server emits a
//! spec-correct `invalid_token` challenge (RFC 6750 §3.1), and not all do.
//! You know your server better than this library can: when a bare `401`, a
//! JSON error body, or a custom convention tells you the token is bad, call
//! [`invalidate`](HttpAuthorizer::invalidate) yourself before re-sending.
//! Treating any `401` as a stale token is a common policy, at the cost of an
//! occasional unnecessary refresh.

mod challenge;

use std::sync::Arc;

use bon::Builder;
pub use challenge::{Challenge, ChallengePayload, parse_challenges};
use http::{HeaderMap, HeaderName, Method, Uri, header::AUTHORIZATION};

use crate::{
    cache::TokenCache,
    core::{Error, ErrorKind},
    grant::core::TokenResponse,
    token::AccessToken,
};

/// Produces authenticated request headers from a [`TokenCache`].
///
/// Built with [`HttpAuthorizer::builder`]; the only required input is the
/// cache (typically an
/// [`InMemoryTokenCache`](crate::cache::InMemoryTokenCache) wrapping a
/// grant). Carries no type parameters, so it stores directly in application
/// state. See the [module docs](self) for the request loop.
#[derive(Builder)]
pub struct HttpAuthorizer {
    /// The token cache that supplies — and exchanges or refreshes — the
    /// access token.
    #[builder(with = |cache: impl TokenCache + 'static| Arc::new(cache) as Arc<dyn TokenCache>)]
    cache: Arc<dyn TokenCache>,
    /// The header that carries the access token. Defaults to
    /// `Authorization`; override when something else owns that header, e.g.
    /// `X-Forwarded-Authorization` behind a proxy that consumes the real
    /// one.
    #[builder(default = AUTHORIZATION)]
    authorization_header: HeaderName,
}

impl core::fmt::Debug for HttpAuthorizer {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("HttpAuthorizer")
            .field("authorization_header", &self.authorization_header)
            .finish_non_exhaustive()
    }
}

impl HttpAuthorizer {
    /// Builds the authorization headers for a request: the access token in
    /// the configured header, plus a `DPoP` proof bound to `method` and
    /// `uri` when the token is `DPoP`-bound.
    ///
    /// Acquires or refreshes the token as needed, using the HTTP client held
    /// by the underlying grant.
    ///
    /// # Errors
    ///
    /// Errors follow the crate's three-signal contract — see
    /// [Handling errors](crate::core::error#handling-errors). In particular,
    /// [`ReauthRequired`](crate::core::ErrorKind::ReauthRequired) means the
    /// interactive flow must run again, while retryable transport failures
    /// keep their own classification.
    pub async fn get_headers(&self, method: &Method, uri: &Uri) -> Result<HeaderMap, Error> {
        let token = self.cache.get_token_response().await?;

        let mut headers = HeaderMap::new();

        match token.access_token() {
            AccessToken::Dpop(dpop_access_token) => {
                let Some(proof) = self
                    .cache
                    .resource_server_dpop()
                    .proof(
                        method,
                        uri,
                        dpop_access_token.token(),
                        dpop_access_token.jkt(),
                    )
                    .await?
                else {
                    // A DPoP-bound token paired with a proof implementation
                    // that produces no proof indicates a logic bug in the
                    // cache configuration.
                    return Err(Error::from(ErrorKind::Dpop)
                        .with_context("received DPoP token but no DPoP configuration present"));
                };

                headers.insert(
                    "DPoP",
                    proof.expose_secret().parse().map_err(|source| {
                        Error::new(ErrorKind::Dpop, source)
                            .with_context("DPoP proof is not a valid header value")
                    })?,
                );
                headers.insert(
                    &self.authorization_header,
                    dpop_access_token.expose_header_value().map_err(|source| {
                        Error::new(ErrorKind::Protocol, source)
                            .with_context("access token is not a valid header value")
                    })?,
                );
            }
            AccessToken::Bearer(bearer_access_token) => {
                headers.insert(
                    &self.authorization_header,
                    bearer_access_token
                        .expose_header_value()
                        .map_err(|source| {
                            Error::new(ErrorKind::Protocol, source)
                                .with_context("access token is not a valid header value")
                        })?,
                );
            }
        }

        Ok(headers)
    }

    /// Returns a reference to the underlying token cache.
    pub fn cache(&self) -> &dyn TokenCache {
        self.cache.as_ref()
    }

    /// Primes the cache with an existing token response — the handoff from
    /// the login path, e.g. after an initial authorization code exchange.
    ///
    /// # Errors
    ///
    /// Returns an error if the cache fails to persist the response's refresh token.
    pub async fn prime(&self, response: Arc<TokenResponse>) -> Result<(), Error> {
        self.cache.prime(response).await
    }

    /// Invalidates the cached token, forcing a refresh on the next call to
    /// [`Self::get_headers`].
    ///
    /// This is the integration point for staleness signals only the
    /// application can see — a server that reports a bad token without a
    /// spec-correct challenge (see the [module docs](self)).
    pub fn invalidate(&self) {
        self.cache.invalidate();
    }

    /// Records a `DPoP` nonce for the given URI's server.
    ///
    /// Nonces are tracked per server origin, so a nonce recorded for one
    /// path applies to every request to that server. This is the manual
    /// escape hatch (paired with [`extract_dpop_nonce`]);
    /// [`Self::process_response`] does both steps in one call.
    pub fn set_nonce(&self, uri: &Uri, nonce: String) {
        self.cache.resource_server_dpop().update_nonce(uri, nonce);
    }

    /// Records what a resource server response teaches about authorization
    /// state. Call this with **every** response, success or failure.
    ///
    /// - Any `DPoP-Nonce` header is recorded for the URI's origin (RFC 9449
    ///   §8.1 — servers may rotate the nonce on any response, and the next
    ///   proof must carry the latest value).
    /// - An `invalid_token` challenge (RFC 6750 §3.1) invalidates the cached
    ///   token, so the next [`Self::get_headers`] acquires a fresh one. This
    ///   is opportunistic — a server that signals token failure any other
    ///   way needs [`Self::invalidate`] called from your own context (see
    ///   the [module docs](self)).
    ///
    /// This is bookkeeping only; whether to re-send is yours to decide — the
    /// [module docs](self) show the loop, and [`parse_challenges`] exposes
    /// what the server objected to.
    pub fn process_response(&self, uri: &Uri, headers: &HeaderMap) {
        if let Some(nonce) = extract_dpop_nonce(headers) {
            self.set_nonce(uri, nonce);
        }

        if challenge::challenge_has_error(headers, "invalid_token") {
            self.invalidate();
        }
    }
}

/// Extracts the `DPoP-Nonce` header value from a response's headers.
///
/// The manual escape hatch, paired with [`HttpAuthorizer::set_nonce`];
/// [`HttpAuthorizer::process_response`] does both steps in one call.
#[must_use]
pub fn extract_dpop_nonce(headers: &HeaderMap) -> Option<String> {
    headers
        .get("DPoP-Nonce")
        .and_then(|v| v.to_str().ok())
        .map(std::borrow::ToOwned::to_owned)
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicBool, Ordering};

    use super::*;
    use crate::{
        core::{dpop::NoDPoP, platform::MaybeSendBoxFuture},
        grant::core::TokenResponse,
    };

    /// A cache stub that records [`TokenCache::invalidate`] calls; the token
    /// acquisition methods are never exercised by these tests.
    #[derive(Clone, Default)]
    struct FakeCache {
        invalidated: Arc<AtomicBool>,
    }

    impl TokenCache for FakeCache {
        fn get_token_response(&self) -> MaybeSendBoxFuture<'_, Result<Arc<TokenResponse>, Error>> {
            Box::pin(async { Err(Error::from(ErrorKind::Config)) })
        }

        fn resource_server_dpop(&self) -> &dyn crate::core::dpop::ResourceServerDPoP {
            &NoDPoP
        }

        fn prime(
            &self,
            _response: Arc<TokenResponse>,
        ) -> MaybeSendBoxFuture<'_, Result<(), Error>> {
            Box::pin(async { Ok(()) })
        }

        fn invalidate(&self) {
            self.invalidated.store(true, Ordering::Relaxed);
        }
    }

    fn authorizer() -> (HttpAuthorizer, Arc<AtomicBool>) {
        let cache = FakeCache::default();
        let invalidated = cache.invalidated.clone();
        (HttpAuthorizer::builder().cache(cache).build(), invalidated)
    }

    fn uri() -> Uri {
        "https://api.example.com/resource".parse().unwrap()
    }

    fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for (name, value) in pairs {
            headers.append(
                http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
                value.parse().unwrap(),
            );
        }
        headers
    }

    #[test]
    fn invalid_token_challenge_invalidates() {
        let (authorizer, invalidated) = authorizer();
        let headers = headers(&[(
            "www-authenticate",
            r#"Bearer error="invalid_token", error_description="The access token expired""#,
        )]);

        authorizer.process_response(&uri(), &headers);
        assert!(invalidated.load(Ordering::Relaxed));
    }

    #[test]
    fn unquoted_error_param_is_recognized() {
        let (authorizer, invalidated) = authorizer();
        // RFC 7235 auth-params may use the plain token form.
        let headers = headers(&[("www-authenticate", "Bearer error=invalid_token")]);

        authorizer.process_response(&uri(), &headers);
        assert!(invalidated.load(Ordering::Relaxed));
    }

    #[test]
    fn dpop_nonce_challenge_does_not_invalidate() {
        let (authorizer, invalidated) = authorizer();
        // A nonce demand does not mean the token is bad.
        let headers = headers(&[
            (
                "www-authenticate",
                r#"DPoP error="use_dpop_nonce", error_description="Resource server requires nonce in DPoP proof""#,
            ),
            ("dpop-nonce", "eyJ7S_zG.eyJH0-Z.HX4w-7v"),
        ]);

        authorizer.process_response(&uri(), &headers);
        assert!(!invalidated.load(Ordering::Relaxed));
    }

    #[test]
    fn other_challenges_do_not_invalidate() {
        let (authorizer, invalidated) = authorizer();
        let headers = headers(&[(
            "www-authenticate",
            r#"Bearer error="insufficient_scope", scope="read write""#,
        )]);

        authorizer.process_response(&uri(), &headers);
        assert!(!invalidated.load(Ordering::Relaxed));
    }

    #[test]
    fn challenge_free_response_does_not_invalidate() {
        let (authorizer, invalidated) = authorizer();

        // E.g. a success response rotating the nonce: bookkeeping only.
        authorizer.process_response(&uri(), &headers(&[("dpop-nonce", "rotated")]));
        // And a response with no relevant headers at all.
        authorizer.process_response(&uri(), &headers(&[]));
        assert!(!invalidated.load(Ordering::Relaxed));
    }

    #[test]
    fn error_code_must_match_exactly() {
        // Prefix of a longer code, and an embedded `error=` inside another
        // parameter, must not count.
        for value in [
            r#"Bearer error="invalid_token_format""#,
            r#"Bearer error="invalid_request", error_uri="https://as.example.com/doc?error=invalid_token""#,
        ] {
            let (authorizer, invalidated) = authorizer();
            authorizer.process_response(&uri(), &headers(&[("www-authenticate", value)]));
            assert!(
                !invalidated.load(Ordering::Relaxed),
                "must not invalidate for: {value}"
            );
        }
    }

    #[test]
    fn error_inside_quoted_description_does_not_invalidate() {
        let (authorizer, invalidated) = authorizer();
        // `error=` inside a quoted value must not be read as a challenge
        // error code (commas and spaces are legal inside quoted-strings).
        let headers = headers(&[(
            "www-authenticate",
            r#"Bearer error="invalid_request", error_description="try again, error=invalid_token happens sometimes""#,
        )]);

        authorizer.process_response(&uri(), &headers);
        assert!(!invalidated.load(Ordering::Relaxed));
    }
}