use crate::time::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use std::sync::Mutex;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use jsonwebtoken::jwk::Jwk;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use crate::AxiamError;
pub const DPOP_IAT_LEEWAY_SECS: u64 = 60;
const PRIVATE_JWK_MEMBERS: &[&str] = &["d", "p", "q", "dp", "dq", "qi", "oth", "k"];
fn auth(message: impl Into<String>) -> AxiamError {
AxiamError::Auth {
message: message.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
}
}
pub trait JtiStore: Send + Sync {
fn claim(&self, jti: &str, expires_at_unix: u64) -> bool;
}
#[derive(Debug, Default)]
pub struct InMemoryJtiStore {
seen: Mutex<HashMap<String, u64>>,
}
impl InMemoryJtiStore {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl JtiStore for InMemoryJtiStore {
fn claim(&self, jti: &str, expires_at_unix: u64) -> bool {
let now = now_unix();
let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
if seen.len() > 128 {
seen.retain(|_, expiry| *expiry > now);
}
if seen.get(jti).is_some_and(|expiry| *expiry > now) {
return false;
}
seen.insert(jti.to_owned(), expires_at_unix);
true
}
}
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
pub fn jwk_thumbprint_s256(jwk: &serde_json::Value) -> Result<String, AxiamError> {
let get = |member: &str| -> Result<String, AxiamError> {
jwk.get(member)
.and_then(serde_json::Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_owned)
.ok_or_else(|| {
auth(format!(
"DPoP proof jwk is missing the required member '{member}'"
))
})
};
let canonical = match jwk.get("kty").and_then(serde_json::Value::as_str) {
Some("RSA") => {
format!(r#"{{"e":"{}","kty":"RSA","n":"{}"}}"#, get("e")?, get("n")?)
}
Some("EC") => format!(
r#"{{"crv":"{}","kty":"EC","x":"{}","y":"{}"}}"#,
get("crv")?,
get("x")?,
get("y")?
),
Some("OKP") => {
format!(
r#"{{"crv":"{}","kty":"OKP","x":"{}"}}"#,
get("crv")?,
get("x")?
)
}
other => {
return Err(auth(format!(
"DPoP proof jwk has an unsupported kty: {}",
other.unwrap_or("<missing>")
)));
}
};
Ok(URL_SAFE_NO_PAD.encode(Sha256::digest(canonical.as_bytes())))
}
#[must_use]
pub fn access_token_hash(access_token: &str) -> String {
URL_SAFE_NO_PAD.encode(Sha256::digest(access_token.as_bytes()))
}
#[must_use]
pub fn canonical_htu(uri: &str) -> &str {
let without_fragment = uri.split('#').next().unwrap_or(uri);
without_fragment
.split('?')
.next()
.unwrap_or(without_fragment)
}
fn expected_alg(jwk: &serde_json::Value) -> Result<Algorithm, AxiamError> {
let kty = jwk.get("kty").and_then(serde_json::Value::as_str);
let crv = jwk.get("crv").and_then(serde_json::Value::as_str);
match (kty, crv) {
(Some("RSA"), _) => Ok(Algorithm::PS256),
(Some("EC"), Some("P-256")) => Ok(Algorithm::ES256),
(Some("OKP"), Some("Ed25519")) => Ok(Algorithm::EdDSA),
_ => Err(auth(format!(
"DPoP proof key type is not permitted by CONTRACT.md §21.7.2 \
(kty={}, crv={}; permitted: ES256, EdDSA, PS256)",
kty.unwrap_or("<missing>"),
crv.unwrap_or("<missing>")
))),
}
}
#[derive(Debug, Deserialize)]
struct DpopClaims {
htm: Option<String>,
htu: Option<String>,
iat: Option<i64>,
jti: Option<String>,
ath: Option<String>,
}
pub struct DpopRequest<'a> {
pub http_method: &'a str,
pub http_uri: &'a str,
pub access_token: &'a str,
pub expected_jkt: Option<&'a str>,
pub leeway_secs: u64,
pub now_unix: Option<u64>,
}
impl<'a> DpopRequest<'a> {
#[must_use]
pub fn new(http_method: &'a str, http_uri: &'a str, access_token: &'a str) -> Self {
Self {
http_method,
http_uri,
access_token,
expected_jkt: None,
leeway_secs: DPOP_IAT_LEEWAY_SECS,
now_unix: None,
}
}
#[must_use]
pub fn with_expected_jkt(mut self, jkt: &'a str) -> Self {
self.expected_jkt = Some(jkt);
self
}
}
pub fn verify_dpop_proof(
proof: &str,
request: &DpopRequest<'_>,
jti_store: &dyn JtiStore,
) -> Result<String, AxiamError> {
if proof.is_empty() {
return Err(auth("DPoP proof is missing or empty"));
}
if proof.contains(',') || proof.trim().contains(char::is_whitespace) {
return Err(auth("DPoP header must carry exactly one proof"));
}
let segments: Vec<&str> = proof.split('.').collect();
if segments.len() != 3 {
return Err(auth("DPoP proof is not a compact JWS with three segments"));
}
let header_bytes = URL_SAFE_NO_PAD
.decode(segments[0])
.map_err(|_| auth("DPoP proof header is not valid base64url"))?;
let header: serde_json::Value = serde_json::from_slice(&header_bytes)
.map_err(|_| auth("DPoP proof header is not valid JSON"))?;
let typ = header
.get("typ")
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
if !typ.eq_ignore_ascii_case("dpop+jwt") {
return Err(auth(format!(
"DPoP proof typ header must be 'dpop+jwt', got '{typ}'"
)));
}
let jwk_value = header
.get("jwk")
.filter(|v| v.is_object())
.ok_or_else(|| auth("DPoP proof header must carry a public 'jwk'"))?;
let leaked: Vec<&str> = PRIVATE_JWK_MEMBERS
.iter()
.copied()
.filter(|m| jwk_value.get(*m).is_some())
.collect();
if !leaked.is_empty() {
return Err(auth(format!(
"DPoP proof jwk carries private key material ({}) — RFC 9449 §4.3",
leaked.join(", ")
)));
}
let alg = expected_alg(jwk_value)?;
let jwk: Jwk = serde_json::from_value(jwk_value.clone())
.map_err(|e| auth(format!("DPoP proof jwk is not a usable public key: {e}")))?;
let key = DecodingKey::from_jwk(&jwk)
.map_err(|e| auth(format!("DPoP proof jwk is not a usable public key: {e}")))?;
let mut validation = Validation::new(alg);
validation.required_spec_claims.clear();
validation.validate_exp = false;
validation.validate_aud = false;
let claims = decode::<DpopClaims>(proof, &key, &validation)
.map_err(|e| auth(format!("DPoP proof signature or claims are invalid: {e}")))?
.claims;
let htm = claims.htm.as_deref().unwrap_or_default();
if htm != request.http_method {
return Err(auth(format!(
"DPoP proof htm '{htm}' does not match request method '{}'",
request.http_method
)));
}
let htu = claims.htu.as_deref().unwrap_or_default();
let expected_htu = canonical_htu(request.http_uri);
if canonical_htu(htu) != expected_htu {
return Err(auth(format!(
"DPoP proof htu '{htu}' does not match request URI '{expected_htu}'"
)));
}
let iat = claims
.iat
.ok_or_else(|| auth("DPoP proof iat must be a number"))?;
let now = i64::try_from(request.now_unix.unwrap_or_else(now_unix)).unwrap_or(i64::MAX);
let leeway = i64::try_from(request.leeway_secs).unwrap_or(i64::MAX);
if (now - iat).abs() > leeway {
return Err(auth(format!(
"DPoP proof iat is outside the {}s freshness window",
request.leeway_secs
)));
}
let ath = claims.ath.as_deref().unwrap_or_default();
if ath.is_empty() {
return Err(auth("DPoP proof is missing the ath claim"));
}
let expected_ath = access_token_hash(request.access_token);
if ath.as_bytes().ct_eq(expected_ath.as_bytes()).unwrap_u8() != 1 {
return Err(auth(
"DPoP proof ath does not match the presented access token",
));
}
let jkt = jwk_thumbprint_s256(jwk_value)?;
if let Some(expected) = request.expected_jkt
&& jkt.as_bytes().ct_eq(expected.as_bytes()).unwrap_u8() != 1
{
return Err(auth("DPoP proof key does not match the token's cnf.jkt"));
}
let jti = claims.jti.as_deref().unwrap_or_default();
if jti.is_empty() {
return Err(auth("DPoP proof is missing a non-empty jti"));
}
let expires_at = u64::try_from(iat)
.unwrap_or(0)
.saturating_add(request.leeway_secs);
if !jti_store.claim(jti, expires_at) {
return Err(auth("DPoP proof jti has already been used (replay)"));
}
Ok(jkt)
}