1use 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#[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 pub fn public_jwk(&self) -> &Map<String, Value> {
52 &self.public_jwk
53 }
54 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
75pub fn generate_dpop_key(alg: SigningAlgorithm) -> Result<DpopKey, AuthError> {
77 new_key(SigningKey::generate(alg)?)
78}
79
80pub fn import_dpop_key(alg: SigningAlgorithm, key: PrivateKeyInput) -> Result<DpopKey, AuthError> {
82 new_key(SigningKey::from_input(alg, &key)?)
83}
84
85pub 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
96pub fn dpop_access_token_hash(access_token: &str) -> String {
98 b64url(&Sha256::digest(access_token.as_bytes()))
99}
100
101pub 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
108fn 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#[derive(Debug, Clone)]
119pub struct DpopProofParams<'a> {
120 pub method: &'a str,
122 pub url: &'a str,
124 pub access_token: Option<&'a str>,
126 pub nonce: Option<&'a str>,
128 pub now: Option<i64>,
130 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
155pub 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
201pub 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#[derive(Clone, Default)]
222pub struct DpopRequest {
223 pub headers: Vec<(String, String)>,
224 pub body: Option<Vec<u8>>,
225}
226
227impl 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#[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
269pub(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
315fn 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
354pub 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 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, ¶ms)?;
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 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, ¶ms)?;
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}