use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use jsonwebtoken::Header;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use super::key::DpopKey;
use crate::{IdentityError, Result};
pub const DPOP_PROOF_TYP: &str = "dpop+jwt";
const JTI_BYTES: usize = 16;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct ProofClaims {
pub(crate) jti: String,
pub(crate) htm: String,
pub(crate) htu: String,
pub(crate) iat: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) ath: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) nonce: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct DpopProofOptions {
ath: Option<String>,
nonce: Option<String>,
pub(crate) issued_at: Option<i64>,
}
impl DpopProofOptions {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn access_token(mut self, access_token: &str) -> Self {
self.ath = Some(ath(access_token));
self
}
#[must_use]
pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
self.nonce = Some(nonce.into());
self
}
}
impl DpopKey {
pub fn proof(&self, method: &str, uri: &str, options: &DpopProofOptions) -> Result<String> {
let claims = ProofClaims {
jti: new_jti()?,
htm: method.to_string(),
htu: normalize_htu(uri)?,
iat: match options.issued_at {
Some(iat) => iat,
None => unix_now()?,
},
ath: options.ath.clone(),
nonce: options.nonce.clone(),
};
let mut header = Header::new(self.algorithm().jwt());
header.typ = Some(DPOP_PROOF_TYP.to_string());
header.jwk = Some(self.embedded_jwk().clone());
jsonwebtoken::encode(&header, &claims, self.encoding_key())
.map_err(|e| IdentityError::Configuration(format!("sign DPoP proof: {e}")))
}
}
pub fn ath(access_token: &str) -> String {
URL_SAFE_NO_PAD.encode(Sha256::digest(access_token.as_bytes()))
}
pub fn normalize_htu(uri: &str) -> Result<String> {
let mut url = Url::parse(uri).map_err(|e| {
IdentityError::Validation(format!(
"DPoP htu requires a valid absolute URI: {uri:?}: {e}"
))
})?;
if !url.has_host() {
return Err(IdentityError::Validation(format!(
"DPoP htu requires an absolute URI with a scheme and host, got {uri:?}"
)));
}
url.set_query(None);
url.set_fragment(None);
let _ = url.set_username("");
let _ = url.set_password(None);
Ok(url.into())
}
fn new_jti() -> Result<String> {
let mut bytes = [0u8; JTI_BYTES];
getrandom::fill(&mut bytes)
.map_err(|e| IdentityError::Configuration(format!("generate DPoP proof jti: {e}")))?;
Ok(URL_SAFE_NO_PAD.encode(bytes))
}
fn unix_now() -> Result<i64> {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.map_err(|e| {
IdentityError::Configuration(format!(
"read the system clock for the DPoP proof iat: {e}"
))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dpop::key::{DpopAlgorithm, DpopKey};
#[test]
fn normalize_htu_strips_query_fragment_and_userinfo() {
for (input, want) in [
(
"https://server.example.com/token",
"https://server.example.com/token",
),
(
"https://server.example.com/token?x=1",
"https://server.example.com/token",
),
(
"https://server.example.com/token#frag",
"https://server.example.com/token",
),
(
"https://server.example.com/token?x=1#frag",
"https://server.example.com/token",
),
(
"https://user:pw@server.example.com/token",
"https://server.example.com/token",
),
(
"https://server.example.com:8443/token",
"https://server.example.com:8443/token",
),
(
"https://server.example.com:443/token",
"https://server.example.com/token",
),
(
"http://localhost:8080/oauth/token",
"http://localhost:8080/oauth/token",
),
(
"https://server.example.com/Token",
"https://server.example.com/Token",
),
(
"https://server.example.com/a%20b",
"https://server.example.com/a%20b",
),
] {
assert_eq!(normalize_htu(input).expect(input), want, "input {input}");
}
}
#[test]
fn normalize_htu_gives_an_empty_path_a_root_slash() {
assert_eq!(
normalize_htu("https://server.example.com").expect("bare authority"),
"https://server.example.com/"
);
assert_eq!(
normalize_htu("https://server.example.com/").expect("root path"),
"https://server.example.com/"
);
}
#[test]
fn normalize_htu_rejects_non_absolute_uris() {
for input in ["/token", "token", "", "example.com/token", "https://"] {
assert!(
normalize_htu(input).is_err(),
"{input:?} is not an absolute http(s) URI and must be rejected"
);
}
}
#[test]
fn ath_is_unpadded_base64url_sha256() {
assert_eq!(
ath("Kz~8mXK1EalYznwH-LC-1fBAo.4Ljp~zsPE_NeO.gxU"),
"fUHyO2r2Z3DZ53EsNrWBb0xWXoaNy59IiKCAqksmQEo"
);
let hash = ath("");
assert!(!hash.contains('='), "no base64 padding");
assert_eq!(hash.len(), 43);
assert_ne!(ath("a"), ath("b"));
}
#[test]
fn jti_is_fresh_and_128_bits() {
let a = new_jti().expect("jti");
let b = new_jti().expect("jti");
assert_ne!(a, b);
assert_eq!(
URL_SAFE_NO_PAD.decode(&a).expect("base64url jti").len(),
JTI_BYTES
);
}
#[test]
fn proof_options_default_to_no_optional_claims() {
let bare = DpopProofOptions::new();
assert!(bare.ath.is_none());
assert!(bare.nonce.is_none());
let bound = DpopProofOptions::new().access_token("tok").nonce("n-1");
assert_eq!(bound.ath.as_deref(), Some(ath("tok").as_str()));
assert_eq!(bound.nonce.as_deref(), Some("n-1"));
}
#[test]
fn proof_normalizes_the_htu_it_signs() {
let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
let proof = key
.proof(
"POST",
"https://server.example.com/token?scope=openid",
&DpopProofOptions::new(),
)
.expect("build proof");
let payload = proof.split('.').nth(1).expect("payload");
let decoded = URL_SAFE_NO_PAD.decode(payload).expect("base64url payload");
let claims: ProofClaims = serde_json::from_slice(&decoded).expect("claims");
assert_eq!(claims.htu, "https://server.example.com/token");
}
#[test]
fn proof_rejects_a_non_absolute_uri() {
let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
assert!(
key.proof("POST", "/token", &DpopProofOptions::new())
.is_err(),
"a relative URI has no htu"
);
}
#[test]
fn proof_signs_the_method_verbatim() {
let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
for method in ["GET", "POST", "PATCH", "DELETE"] {
let proof = key
.proof(method, "https://rs.example.com/r", &DpopProofOptions::new())
.expect("build proof");
let decoded = URL_SAFE_NO_PAD
.decode(proof.split('.').nth(1).expect("payload"))
.expect("base64url");
let claims: ProofClaims = serde_json::from_slice(&decoded).expect("claims");
assert_eq!(claims.htm, method);
}
}
}