Skip to main content

beyondigital_auth_sdk/
dpop.rs

1//! DPoP (RFC 9449): sender-constraining access and refresh tokens with a key the client holds.
2//!
3//! A proof is a short JWT signed with that key and naming the request it is for (`htm`, `htu`, a fresh `jti`, `iat`,
4//! and `ath` when an access token goes with it). The service (`services/dpop.rs`) accepts ES256, PS256 and RS256, so
5//! those are the only algorithms here, and it binds the issued tokens to the key's RFC 7638 thumbprint (`cnf.jkt`): a
6//! bound token is useless without a proof from the same key.
7//!
8//! What this module never does: put the private key in anything it returns (a [`DpopKey`] prints the algorithm and the
9//! thumbprint only), reuse a `jti`, or retry more than once. The proof goes in the `DPoP` header, never in a URL or a
10//! body. The `htu` is computed with the same `url` crate function the service uses, so the two agree on every path.
11//!
12//! Nonces (RFC 9449 section 8). The service does not hand out nonces yet; when it does (or any other server does),
13//! [`DpopSession`] handles it: a `use_dpop_nonce` challenge with a `DPoP-Nonce` header is retried once with a new proof
14//! carrying the nonce, and the latest nonce is remembered per origin. Nothing is retried for any other error, for a nonce
15//! that is not a valid nonce, or a second time.
16use std::collections::HashMap;
17use std::fmt;
18use std::sync::{Arc, Mutex};
19
20use serde_json::{Map, Value};
21use sha2::{Digest, Sha256};
22
23use crate::client_assertion::unix_now;
24use crate::error::AuthError;
25use crate::keys::{thumbprint_of, PrivateKeyInput, SigningAlgorithm, SigningKey};
26use crate::wire::{b64url, normalise_htu, origin_of};
27
28/// A DPoP key pair. The private half is held out of reach: it signs proofs and cannot be read back.
29#[derive(Clone)]
30pub struct DpopKey {
31    alg: SigningAlgorithm,
32    public_jwk: Map<String, Value>,
33    thumbprint: String,
34    key: Arc<SigningKey>,
35}
36
37impl fmt::Debug for DpopKey {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.debug_struct("DpopKey")
40            .field("alg", &self.alg)
41            .field("thumbprint", &self.thumbprint)
42            .finish()
43    }
44}
45
46impl DpopKey {
47    pub fn algorithm(&self) -> SigningAlgorithm {
48        self.alg
49    }
50    /// The public key as a JWK: the members RFC 7638 uses, and no private member.
51    pub fn public_jwk(&self) -> &Map<String, Value> {
52        &self.public_jwk
53    }
54    /// RFC 7638 SHA-256 thumbprint of the public key: the `jkt` the service binds tokens to.
55    pub fn thumbprint(&self) -> &str {
56        &self.thumbprint
57    }
58}
59
60fn new_key(key: SigningKey) -> Result<DpopKey, AuthError> {
61    let thumbprint = thumbprint_of(key.public_jwk())?;
62    let public_jwk = key
63        .public_jwk()
64        .iter()
65        .map(|(name, value)| (name.clone(), Value::String(value.clone())))
66        .collect();
67    Ok(DpopKey {
68        alg: key.algorithm(),
69        public_jwk,
70        thumbprint,
71        key: Arc::new(key),
72    })
73}
74
75/// A new key pair: ES256 (P-256), or PS256 / RS256 (RSA 2048; slow to generate, so prefer ES256).
76pub fn generate_dpop_key(alg: SigningAlgorithm) -> Result<DpopKey, AuthError> {
77    new_key(SigningKey::generate(alg)?)
78}
79
80/// Use a key you already hold: a private JWK or a PKCS#8 PEM.
81pub fn import_dpop_key(alg: SigningAlgorithm, key: PrivateKeyInput) -> Result<DpopKey, AuthError> {
82    new_key(SigningKey::from_input(alg, &key)?)
83}
84
85/// RFC 7638 thumbprint (base64url SHA-256) of a public JWK given as JSON (EC P-256 or RSA).
86pub fn dpop_thumbprint(jwk: &Value) -> Result<String, AuthError> {
87    let members = jwk
88        .as_object()
89        .ok_or_else(|| AuthError::Config("A JWK object is required".into()))?
90        .iter()
91        .filter_map(|(name, value)| Some((name.clone(), value.as_str()?.to_string())))
92        .collect();
93    thumbprint_of(&members)
94}
95
96/// `ath`: base64url SHA-256 of an access token (RFC 9449 section 4.2).
97pub fn dpop_access_token_hash(access_token: &str) -> String {
98    b64url(&Sha256::digest(access_token.as_bytes()))
99}
100
101/// `htu`: the request URL without query or fragment, scheme and host lower-cased, default port dropped. Computed with
102/// the service's own normalisation.
103pub fn dpop_htu(url: &str) -> Result<String, AuthError> {
104    normalise_htu(url)
105        .ok_or_else(|| AuthError::Config("The DPoP proof needs an absolute http(s) URL".into()))
106}
107
108/// A nonce is `1*NQCHAR` (RFC 9449 section 8.1) and short; anything else is ignored.
109fn valid_nonce(value: &str) -> bool {
110    !value.is_empty()
111        && value.len() <= 256
112        && value
113            .bytes()
114            .all(|b| b == 0x21 || (0x23..=0x5B).contains(&b) || (0x5D..=0x7E).contains(&b))
115}
116
117/// What goes into one proof.
118#[derive(Debug, Clone)]
119pub struct DpopProofParams<'a> {
120    /// The HTTP method; upper-cased in the proof.
121    pub method: &'a str,
122    /// The request URL; its query and fragment are not part of the proof.
123    pub url: &'a str,
124    /// Adds `ath`: the request is made with this access token.
125    pub access_token: Option<&'a str>,
126    /// A nonce the server gave.
127    pub nonce: Option<&'a str>,
128    /// Issued-at, unix seconds. For tests.
129    pub now: Option<i64>,
130    /// For tests: a real call leaves it out so every proof has its own `jti`.
131    pub jti: Option<&'a str>,
132}
133
134impl<'a> DpopProofParams<'a> {
135    pub fn new(method: &'a str, url: &'a str) -> Self {
136        Self {
137            method,
138            url,
139            access_token: None,
140            nonce: None,
141            now: None,
142            jti: None,
143        }
144    }
145    pub fn with_access_token(mut self, access_token: &'a str) -> Self {
146        self.access_token = Some(access_token);
147        self
148    }
149    pub fn with_nonce(mut self, nonce: &'a str) -> Self {
150        self.nonce = Some(nonce);
151        self
152    }
153}
154
155/// A DPoP proof JWT for one request.
156pub fn create_dpop_proof(key: &DpopKey, params: &DpopProofParams<'_>) -> Result<String, AuthError> {
157    let verb = params.method.trim();
158    if verb.is_empty() || !verb.bytes().all(|b| b.is_ascii_alphabetic()) {
159        return Err(AuthError::Config(
160            "The DPoP proof needs an HTTP method".into(),
161        ));
162    }
163    let htu = dpop_htu(params.url)?;
164    let jti = params
165        .jti
166        .map(str::to_string)
167        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
168    if jti.is_empty() || jti.chars().count() > 256 {
169        return Err(AuthError::Config(
170            "The DPoP proof needs a non-empty jti".into(),
171        ));
172    }
173    if let Some(nonce) = params.nonce {
174        if !valid_nonce(nonce) {
175            return Err(AuthError::Config(
176                "The DPoP nonce is not a valid nonce".into(),
177            ));
178        }
179    }
180    let mut claims = Map::new();
181    claims.insert("htm".into(), Value::String(verb.to_ascii_uppercase()));
182    claims.insert("htu".into(), Value::String(htu));
183    claims.insert(
184        "iat".into(),
185        Value::from(params.now.unwrap_or_else(unix_now)),
186    );
187    claims.insert("jti".into(), Value::String(jti));
188    if let Some(token) = params.access_token {
189        claims.insert("ath".into(), Value::String(dpop_access_token_hash(token)));
190    }
191    if let Some(nonce) = params.nonce {
192        claims.insert("nonce".into(), Value::String(nonce.to_string()));
193    }
194    let mut header = Map::new();
195    header.insert("typ".into(), Value::String("dpop+jwt".into()));
196    header.insert("alg".into(), Value::String(key.alg.as_str().into()));
197    header.insert("jwk".into(), Value::Object(key.public_jwk.clone()));
198    key.key.sign_jws(&header, &claims)
199}
200
201/// The service must advertise the key's algorithm (`dpop_signing_alg_values_supported`) before a client sends a proof.
202pub fn assert_dpop_supported(
203    dpop_signing_alg_values_supported: Option<&[String]>,
204    key: &DpopKey,
205) -> Result<(), AuthError> {
206    let Some(algs) = dpop_signing_alg_values_supported else {
207        return Err(AuthError::Config(
208            "The service does not advertise DPoP support".into(),
209        ));
210    };
211    if !algs.iter().any(|a| a == key.alg.as_str()) {
212        return Err(AuthError::Config(format!(
213            "The service does not advertise DPoP with {}",
214            key.alg
215        )));
216    }
217    Ok(())
218}
219
220/// What a request carries besides its DPoP proof.
221#[derive(Clone, Default)]
222pub struct DpopRequest {
223    pub headers: Vec<(String, String)>,
224    pub body: Option<Vec<u8>>,
225}
226
227// Headers hold `Authorization` and the body holds client secrets and tokens: print the shape, never the content.
228impl fmt::Debug for DpopRequest {
229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230        let names: Vec<&str> = self.headers.iter().map(|(n, _)| n.as_str()).collect();
231        f.debug_struct("DpopRequest")
232            .field("header_names", &names)
233            .field("body_len", &self.body.as_ref().map(Vec::len))
234            .finish_non_exhaustive()
235    }
236}
237
238/// A fully read HTTP answer. Header names are lower-case.
239#[derive(Clone)]
240pub struct HttpReply {
241    pub status: u16,
242    pub headers: Vec<(String, String)>,
243    pub body: Vec<u8>,
244}
245
246impl fmt::Debug for HttpReply {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.debug_struct("HttpReply")
249            .field("status", &self.status)
250            .finish_non_exhaustive()
251    }
252}
253
254impl HttpReply {
255    pub fn header(&self, name: &str) -> Option<&str> {
256        self.headers
257            .iter()
258            .find(|(n, _)| n.eq_ignore_ascii_case(name))
259            .map(|(_, v)| v.as_str())
260    }
261    pub fn is_success(&self) -> bool {
262        (200..300).contains(&self.status)
263    }
264    pub fn json(&self) -> Option<Value> {
265        serde_json::from_slice(&self.body).ok()
266    }
267}
268
269/// Send one request; never follow a redirect. A transport failure is a fixed message (the request is not echoed).
270pub(crate) async fn send_request(
271    http: &reqwest::Client,
272    method: &str,
273    url: &str,
274    headers: &[(String, String)],
275    body: Option<&[u8]>,
276) -> Result<HttpReply, AuthError> {
277    let verb = reqwest::Method::from_bytes(method.as_bytes())
278        .map_err(|_| AuthError::Config("The HTTP method is not valid".into()))?;
279    let mut request = http.request(verb, url);
280    for (name, value) in headers {
281        let header_value = reqwest::header::HeaderValue::from_str(value)
282            .map_err(|_| AuthError::Config("A request header value is not valid".into()))?;
283        request = request.header(name.as_str(), header_value);
284    }
285    if let Some(body) = body {
286        request = request.body(body.to_vec());
287    }
288    let response = request
289        .send()
290        .await
291        .map_err(|_| AuthError::Network("The request to the service failed".into()))?;
292    let status = response.status().as_u16();
293    let headers = response
294        .headers()
295        .iter()
296        .filter_map(|(name, value)| {
297            Some((
298                name.as_str().to_ascii_lowercase(),
299                value.to_str().ok()?.to_string(),
300            ))
301        })
302        .collect();
303    let body = response
304        .bytes()
305        .await
306        .map_err(|_| AuthError::Network("The request to the service failed".into()))?
307        .to_vec();
308    Ok(HttpReply {
309        status,
310        headers,
311        body,
312    })
313}
314
315/// `error="use_dpop_nonce"` in a `WWW-Authenticate` value (any letter case, quotes optional).
316fn is_nonce_challenge_header(value: &str) -> bool {
317    const NAME: &str = "use_dpop_nonce";
318    let lower = value.to_ascii_lowercase();
319    let mut from = 0;
320    while let Some(found) = lower[from..].find("error") {
321        let after = from + found + "error".len();
322        let rest = lower[after..].trim_start();
323        if let Some(rest) = rest.strip_prefix('=') {
324            let rest = rest.trim_start();
325            let rest = rest.strip_prefix('"').unwrap_or(rest);
326            if let Some(tail) = rest.strip_prefix(NAME) {
327                let boundary = tail
328                    .chars()
329                    .next()
330                    .is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_'));
331                if boundary {
332                    return true;
333                }
334            }
335        }
336        from = after;
337    }
338    false
339}
340
341fn is_nonce_challenge(reply: &HttpReply, body_error: Option<&str>) -> bool {
342    if reply.status != 400 && reply.status != 401 {
343        return false;
344    }
345    if reply
346        .header("www-authenticate")
347        .is_some_and(is_nonce_challenge_header)
348    {
349        return true;
350    }
351    body_error == Some("use_dpop_nonce")
352}
353
354/// Sends requests with DPoP proofs: a fresh proof per request, the remembered nonce, one retry on a nonce challenge.
355pub struct DpopSession {
356    key: DpopKey,
357    nonces: Mutex<HashMap<String, String>>,
358}
359
360impl fmt::Debug for DpopSession {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        f.debug_struct("DpopSession")
363            .field("key", &self.key)
364            .finish_non_exhaustive()
365    }
366}
367
368impl DpopSession {
369    pub fn new(key: DpopKey) -> Self {
370        Self {
371            key,
372            nonces: Mutex::new(HashMap::new()),
373        }
374    }
375
376    pub fn key(&self) -> &DpopKey {
377        &self.key
378    }
379
380    fn nonce_for(&self, origin: &str) -> Option<String> {
381        self.nonces.lock().ok()?.get(origin).cloned()
382    }
383
384    /// The headers to put on a request: `DPoP` always, `Authorization: DPoP <token>` when a token goes with it.
385    ///
386    /// Call once per request: a proof is single use.
387    pub fn headers(
388        &self,
389        method: &str,
390        url: &str,
391        access_token: Option<&str>,
392    ) -> Result<Vec<(String, String)>, AuthError> {
393        let origin = origin_of(url).ok_or_else(|| {
394            AuthError::Config("The DPoP proof needs an absolute http(s) URL".into())
395        })?;
396        if let Some(token) = access_token {
397            reqwest::header::HeaderValue::from_str(&format!("DPoP {token}")).map_err(|_| {
398                AuthError::Config("The access token is not a valid header value".into())
399            })?;
400        }
401        let nonce = self.nonce_for(&origin);
402        let mut params = DpopProofParams::new(method, url);
403        params.access_token = access_token;
404        params.nonce = nonce.as_deref();
405        let proof = create_dpop_proof(&self.key, &params)?;
406        let mut headers = Vec::new();
407        if let Some(token) = access_token {
408            headers.push(("Authorization".to_string(), format!("DPoP {token}")));
409        }
410        headers.push(("DPoP".to_string(), proof));
411        Ok(headers)
412    }
413
414    fn remember(&self, origin: &str, reply: &HttpReply) -> bool {
415        let Some(nonce) = reply.header("dpop-nonce") else {
416            return false;
417        };
418        if !valid_nonce(nonce) {
419            return false;
420        }
421        if let Ok(mut nonces) = self.nonces.lock() {
422            nonces.insert(origin.to_string(), nonce.to_string());
423        }
424        true
425    }
426
427    /// Send a request with the proof added. A `DPoP` header the caller set is replaced. `access_token` adds `ath` (it
428    /// does not add an Authorization header: the caller owns that).
429    ///
430    /// `request` is called with the attempt number (0, then 1 on the one retry after a nonce challenge): it is called
431    /// again for the retry, so a request that carries a single-use credential (a `private_key_jwt` assertion) can mint a
432    /// new one instead of replaying the first.
433    pub async fn fetch<F>(
434        &self,
435        http: &reqwest::Client,
436        method: &str,
437        url: &str,
438        mut request: F,
439        access_token: Option<&str>,
440    ) -> Result<HttpReply, AuthError>
441    where
442        F: FnMut(u32) -> Result<DpopRequest, AuthError>,
443    {
444        let origin = origin_of(url).ok_or_else(|| {
445            AuthError::Config("The DPoP proof needs an absolute http(s) URL".into())
446        })?;
447        let mut send = |attempt: u32| -> Result<DpopRequest, AuthError> {
448            let built = request(attempt)?;
449            let mut params = DpopProofParams::new(method, url);
450            let nonce = self.nonce_for(&origin);
451            params.access_token = access_token;
452            params.nonce = nonce.as_deref();
453            let proof = create_dpop_proof(&self.key, &params)?;
454            let mut headers: Vec<(String, String)> = built
455                .headers
456                .into_iter()
457                .filter(|(name, _)| !name.eq_ignore_ascii_case("dpop"))
458                .collect();
459            headers.push(("DPoP".to_string(), proof));
460            Ok(DpopRequest {
461                headers,
462                body: built.body,
463            })
464        };
465        let first_request = send(0)?;
466        let first = send_request(
467            http,
468            method,
469            url,
470            &first_request.headers,
471            first_request.body.as_deref(),
472        )
473        .await?;
474        let offered = self.remember(&origin, &first);
475        if !offered || (first.status != 400 && first.status != 401) {
476            return Ok(first);
477        }
478        let mut body_error: Option<String> = None;
479        if first.status == 400 {
480            body_error = first.json().and_then(|body| {
481                body.get("error")
482                    .and_then(Value::as_str)
483                    .map(str::to_string)
484            });
485        }
486        if !is_nonce_challenge(&first, body_error.as_deref()) {
487            return Ok(first);
488        }
489        let second_request = send(1)?;
490        let second = send_request(
491            http,
492            method,
493            url,
494            &second_request.headers,
495            second_request.body.as_deref(),
496        )
497        .await?;
498        self.remember(&origin, &second);
499        Ok(second)
500    }
501}