Skip to main content

hyprstream_core/services/oauth/
dpop.rs

1//! RFC 9449 DPoP (Demonstrating Proof-of-Possession) proof verification.
2//!
3//! Verifies `DPoP` JWT proofs presented at the token endpoint or as
4//! `Authorization: DPoP` on resource requests.
5//!
6//! DPoP proofs carry:
7//! - `jwk` in the header — the ephemeral client key (used to verify signature)
8//! - `htm` — HTTP method
9//! - `htu` — HTTP URI (scheme + host + path, no query)
10//! - `iat` — issued-at (must be within ±60s of server clock)
11//! - `jti` — unique identifier (replay prevention)
12//! - `ath` — base64url(SHA-256(access_token)) — required when the proof
13//!   accompanies an access token on a resource request
14//!
15//! Supported algorithms:
16//! - EdDSA (Ed25519) — native hyprstream identity keys
17//! - ES256 (ECDSA P-256 + SHA-256) — atproto interop (required by atproto OAuth)
18
19use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
20use ed25519_dalek::VerifyingKey;
21use hyprstream_rpc::auth::{jwk_thumbprint, JwkThumbprintInput};
22use sha2::{Digest, Sha256};
23use subtle::ConstantTimeEq;
24
25/// The public key from a verified DPoP proof, algorithm-polymorphic.
26#[derive(Debug, Clone)]
27pub enum DpopKey {
28    Ed25519 { bytes: [u8; 32] },
29    Es256 { x: [u8; 32], y: [u8; 32] },
30    MlDsa65 { pub_bytes: Vec<u8> },
31    MlDsa65Ed25519 { pub_bytes: Vec<u8> },
32}
33
34impl DpopKey {
35    pub fn jkt(&self) -> String {
36        match self {
37            DpopKey::Ed25519 { bytes } => jwk_thumbprint(&JwkThumbprintInput::Ed25519 { x: bytes }),
38            DpopKey::Es256 { x, y } => jwk_thumbprint(&JwkThumbprintInput::Es256 { x, y }),
39            DpopKey::MlDsa65 { pub_bytes } => jwk_thumbprint(&JwkThumbprintInput::Akp {
40                alg: "ML-DSA-65",
41                pub_bytes,
42            }),
43            DpopKey::MlDsa65Ed25519 { pub_bytes } => jwk_thumbprint(&JwkThumbprintInput::Akp {
44                alg: "ML-DSA-65-Ed25519",
45                pub_bytes,
46            }),
47        }
48    }
49
50    /// Returns Ed25519 raw bytes if this is an Ed25519 key, None otherwise.
51    pub fn ed25519_bytes(&self) -> Option<&[u8; 32]> {
52        match self {
53            DpopKey::Ed25519 { bytes } => Some(bytes),
54            _ => None,
55        }
56    }
57}
58
59/// Parsed and verified DPoP proof.
60#[derive(Debug, Clone)]
61pub struct DpopProof {
62    /// The verified public key from the proof's `jwk` header.
63    pub key: DpopKey,
64    /// RFC 7638 JWK thumbprint of the key (SHA-256, base64url).
65    pub jkt: String,
66    /// Unique token identifier for replay prevention.
67    pub jti: String,
68    /// HTTP method from the proof.
69    pub htm: String,
70    /// HTTP URI from the proof.
71    pub htu: String,
72    /// Issued-at timestamp (Unix seconds).
73    pub iat: i64,
74    /// `ath` — base64url(SHA-256(access_token)) when present.
75    pub ath: Option<String>,
76    /// Optional server-issued nonce.
77    pub nonce: Option<String>,
78}
79
80impl DpopProof {
81    /// Backwards-compat: raw Ed25519 key bytes (panics if ES256).
82    /// Prefer `key` field for new code.
83    pub fn public_key_bytes(&self) -> Option<[u8; 32]> {
84        self.key.ed25519_bytes().copied()
85    }
86}
87
88#[derive(Debug, thiserror::Error)]
89pub enum DpopError {
90    #[error("DPoP proof header is not a valid JWT: {0}")]
91    InvalidFormat(String),
92    #[error("DPoP JWT typ must be 'dpop+jwt', got '{0}'")]
93    WrongTyp(String),
94    #[error("DPoP JWT must use EdDSA or ES256, got '{0}'")]
95    WrongAlg(String),
96    #[error("DPoP JWT jwk header must be an OKP/Ed25519 or EC/P-256 JWK")]
97    InvalidJwk,
98    #[error("DPoP proof signature verification failed")]
99    SignatureInvalid,
100    #[error("DPoP proof missing claim '{0}'")]
101    MissingClaim(&'static str),
102    #[error("DPoP proof htm '{actual}' does not match expected '{expected}'")]
103    HtmMismatch { expected: String, actual: String },
104    #[error("DPoP proof htu '{actual}' does not match expected '{expected}'")]
105    HtuMismatch { expected: String, actual: String },
106    #[error("DPoP proof iat {iat} is outside the ±60s window (server time: {now})")]
107    IatOutOfWindow { iat: i64, now: i64 },
108    #[error("DPoP proof ath mismatch — access token binding failed")]
109    AthMismatch,
110    #[error("DPoP proof jti has been seen before (replay)")]
111    JtiReplayed,
112}
113
114/// Verify a DPoP proof JWT string.
115///
116/// - `expected_htm`: uppercase HTTP method (e.g. "POST")
117/// - `expected_htu`: scheme + host + path (no query string)
118/// - `access_token`: when `Some`, the `ath` claim is required and verified
119pub fn verify_dpop_proof(
120    dpop_header: &str,
121    expected_htm: &str,
122    expected_htu: &str,
123    access_token: Option<&str>,
124) -> Result<DpopProof, DpopError> {
125    // Split JWT into three parts.
126    let parts: Vec<&str> = dpop_header.splitn(3, '.').collect();
127    if parts.len() != 3 {
128        return Err(DpopError::InvalidFormat("not a three-part JWT".to_owned()));
129    }
130
131    // Decode header.
132    let header_bytes = URL_SAFE_NO_PAD
133        .decode(parts[0])
134        .map_err(|e| DpopError::InvalidFormat(format!("header base64: {e}")))?;
135    let header: serde_json::Value = serde_json::from_slice(&header_bytes)
136        .map_err(|e| DpopError::InvalidFormat(format!("header JSON: {e}")))?;
137
138    // Validate typ.
139    let typ = header["typ"].as_str().unwrap_or("");
140    if !typ.eq_ignore_ascii_case("dpop+jwt") {
141        return Err(DpopError::WrongTyp(typ.to_owned()));
142    }
143
144    // Validate alg + extract key + verify signature.
145    let alg = header["alg"].as_str().unwrap_or("");
146    let signing_input = format!("{}.{}", parts[0], parts[1]);
147    let sig_bytes = URL_SAFE_NO_PAD
148        .decode(parts[2])
149        .map_err(|e| DpopError::InvalidFormat(format!("signature base64: {e}")))?;
150
151    let jwk = &header["jwk"];
152    let key = if alg.eq_ignore_ascii_case("EdDSA") {
153        let key_bytes = extract_ed25519_key(jwk)?;
154        verify_ed25519(&key_bytes, signing_input.as_bytes(), &sig_bytes)?;
155        DpopKey::Ed25519 { bytes: key_bytes }
156    } else if alg.eq_ignore_ascii_case("ES256") {
157        let (x, y) = extract_p256_key(jwk)?;
158        verify_es256(&x, &y, signing_input.as_bytes(), &sig_bytes)?;
159        DpopKey::Es256 { x, y }
160    } else if alg == "ML-DSA-65" {
161        {
162            let pub_bytes = extract_akp_pub(jwk)?;
163            let vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&pub_bytes)
164                .map_err(|_| DpopError::InvalidJwk)?;
165            hyprstream_rpc::crypto::pq::ml_dsa_verify(&vk, signing_input.as_bytes(), &sig_bytes)
166                .map_err(|_| DpopError::SignatureInvalid)?;
167            DpopKey::MlDsa65 { pub_bytes }
168        }
169    } else if alg == "ML-DSA-65-Ed25519" {
170        {
171            let pub_bytes = extract_akp_pub(jwk)?;
172            // Composite: ML-DSA-65 vk (1952) + Ed25519 vk (32) = 1984
173            if pub_bytes.len() != 1952 + 32 {
174                return Err(DpopError::InvalidJwk);
175            }
176            let (ml_dsa_pub, ed25519_pub) = pub_bytes.split_at(1952);
177            let ml_dsa_vk = hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(ml_dsa_pub)
178                .map_err(|_| DpopError::InvalidJwk)?;
179            let ed25519_vk = ed25519_dalek::VerifyingKey::from_bytes(
180                ed25519_pub.try_into().map_err(|_| DpopError::InvalidJwk)?,
181            )
182            .map_err(|_| DpopError::InvalidJwk)?;
183            // Composite sig: ML-DSA-65 (3309) + Ed25519 (64)
184            if sig_bytes.len() != 3309 + 64 {
185                return Err(DpopError::SignatureInvalid);
186            }
187            let (ml_sig, ed_sig) = sig_bytes.split_at(3309);
188            hyprstream_rpc::crypto::pq::ml_dsa_verify(&ml_dsa_vk, signing_input.as_bytes(), ml_sig)
189                .map_err(|_| DpopError::SignatureInvalid)?;
190            let mut ed_sig_arr = [0u8; 64];
191            ed_sig_arr.copy_from_slice(ed_sig);
192            let ed_signature = ed25519_dalek::Signature::from_bytes(&ed_sig_arr);
193            ed25519_vk
194                .verify_strict(signing_input.as_bytes(), &ed_signature)
195                .map_err(|_| DpopError::SignatureInvalid)?;
196            DpopKey::MlDsa65Ed25519 { pub_bytes }
197        }
198    } else {
199        return Err(DpopError::WrongAlg(alg.to_owned()));
200    };
201
202    // Decode payload.
203    let payload_bytes = URL_SAFE_NO_PAD
204        .decode(parts[1])
205        .map_err(|e| DpopError::InvalidFormat(format!("payload base64: {e}")))?;
206    let payload: serde_json::Value = serde_json::from_slice(&payload_bytes)
207        .map_err(|e| DpopError::InvalidFormat(format!("payload JSON: {e}")))?;
208
209    // Required claims.
210    let jti = payload["jti"]
211        .as_str()
212        .ok_or(DpopError::MissingClaim("jti"))?
213        .to_owned();
214    let htm = payload["htm"]
215        .as_str()
216        .ok_or(DpopError::MissingClaim("htm"))?
217        .to_owned();
218    let htu = payload["htu"]
219        .as_str()
220        .ok_or(DpopError::MissingClaim("htu"))?
221        .to_owned();
222    let iat = payload["iat"]
223        .as_i64()
224        .ok_or(DpopError::MissingClaim("iat"))?;
225
226    // Validate htm and htu.
227    if !htm.eq_ignore_ascii_case(expected_htm) {
228        return Err(DpopError::HtmMismatch {
229            expected: expected_htm.to_owned(),
230            actual: htm,
231        });
232    }
233    // htu comparison: strip trailing slash, ignore query/fragment.
234    let htu_normalized = htu.split('?').next().unwrap_or(&htu).trim_end_matches('/');
235    let expected_htu_norm = expected_htu
236        .split('?')
237        .next()
238        .unwrap_or(expected_htu)
239        .trim_end_matches('/');
240    if htu_normalized != expected_htu_norm {
241        return Err(DpopError::HtuMismatch {
242            expected: expected_htu.to_owned(),
243            actual: htu.clone(),
244        });
245    }
246
247    // Validate iat within ±60s.
248    let now = chrono::Utc::now().timestamp();
249    if iat.abs_diff(now) > 60 {
250        return Err(DpopError::IatOutOfWindow { iat, now });
251    }
252
253    // Validate ath when access_token is provided.
254    let ath = payload["ath"].as_str().map(str::to_owned);
255    if let Some(token) = access_token {
256        let expected_ath = URL_SAFE_NO_PAD.encode(Sha256::digest(token.as_bytes()));
257        match &ath {
258            Some(a) if a.as_bytes().ct_eq(expected_ath.as_bytes()).unwrap_u8() == 1 => {}
259            _ => return Err(DpopError::AthMismatch),
260        }
261    }
262
263    let nonce = payload["nonce"].as_str().map(str::to_owned);
264    let jkt = key.jkt();
265
266    Ok(DpopProof {
267        key,
268        jkt,
269        jti,
270        htm,
271        htu,
272        iat,
273        ath,
274        nonce,
275    })
276}
277
278fn extract_ed25519_key(jwk: &serde_json::Value) -> Result<[u8; 32], DpopError> {
279    if jwk["kty"].as_str() != Some("OKP") || jwk["crv"].as_str() != Some("Ed25519") {
280        return Err(DpopError::InvalidJwk);
281    }
282    let x = jwk["x"].as_str().ok_or(DpopError::InvalidJwk)?;
283    let bytes = URL_SAFE_NO_PAD
284        .decode(x)
285        .map_err(|_| DpopError::InvalidJwk)?;
286    bytes.try_into().map_err(|_| DpopError::InvalidJwk)
287}
288
289fn extract_p256_key(jwk: &serde_json::Value) -> Result<([u8; 32], [u8; 32]), DpopError> {
290    if jwk["kty"].as_str() != Some("EC") || jwk["crv"].as_str() != Some("P-256") {
291        return Err(DpopError::InvalidJwk);
292    }
293    let x_str = jwk["x"].as_str().ok_or(DpopError::InvalidJwk)?;
294    let y_str = jwk["y"].as_str().ok_or(DpopError::InvalidJwk)?;
295    let x_bytes: [u8; 32] = URL_SAFE_NO_PAD
296        .decode(x_str)
297        .map_err(|_| DpopError::InvalidJwk)?
298        .try_into()
299        .map_err(|_| DpopError::InvalidJwk)?;
300    let y_bytes: [u8; 32] = URL_SAFE_NO_PAD
301        .decode(y_str)
302        .map_err(|_| DpopError::InvalidJwk)?
303        .try_into()
304        .map_err(|_| DpopError::InvalidJwk)?;
305    Ok((x_bytes, y_bytes))
306}
307
308fn extract_akp_pub(jwk: &serde_json::Value) -> Result<Vec<u8>, DpopError> {
309    if jwk["kty"].as_str() != Some("AKP") {
310        return Err(DpopError::InvalidJwk);
311    }
312    let pub_str = jwk["pub"].as_str().ok_or(DpopError::InvalidJwk)?;
313    URL_SAFE_NO_PAD
314        .decode(pub_str)
315        .map_err(|_| DpopError::InvalidJwk)
316}
317
318fn verify_ed25519(key_bytes: &[u8; 32], msg: &[u8], sig_bytes: &[u8]) -> Result<(), DpopError> {
319    let verifying_key = VerifyingKey::from_bytes(key_bytes).map_err(|_| DpopError::InvalidJwk)?;
320    let sig_array: [u8; 64] = sig_bytes
321        .try_into()
322        .map_err(|_| DpopError::SignatureInvalid)?;
323    let signature = ed25519_dalek::Signature::from_bytes(&sig_array);
324    use ed25519_dalek::Verifier;
325    verifying_key
326        .verify(msg, &signature)
327        .map_err(|_| DpopError::SignatureInvalid)
328}
329
330fn verify_es256(x: &[u8; 32], y: &[u8; 32], msg: &[u8], sig_bytes: &[u8]) -> Result<(), DpopError> {
331    use p256::ecdsa::{signature::Verifier, Signature, VerifyingKey};
332    use p256::EncodedPoint;
333
334    let point = EncodedPoint::from_affine_coordinates(x.into(), y.into(), false);
335    let verifying_key =
336        VerifyingKey::from_encoded_point(&point).map_err(|_| DpopError::InvalidJwk)?;
337
338    // JWS ES256 signatures are fixed-size r||s (64 bytes), not DER.
339    let signature = Signature::from_slice(sig_bytes).map_err(|_| DpopError::SignatureInvalid)?;
340
341    verifying_key
342        .verify(msg, &signature)
343        .map_err(|_| DpopError::SignatureInvalid)
344}
345
346#[cfg(test)]
347mod dpop_nonce_tests {
348    //! Unit tests for the per-client nonce-enforcement bookkeeping logic.
349    //! Building a full `OAuthState` requires a live `PolicyClient` (ZMQ),
350    //! so we mirror the `HashMap<jkt, expiry>` shape used in `state.rs`
351    //! and assert the invariants the verifier relies on.
352    use parking_lot::Mutex;
353    use std::collections::HashMap;
354
355    struct NonceState {
356        nonces: Mutex<HashMap<String, i64>>,
357        clients: Mutex<HashMap<String, i64>>,
358    }
359    impl NonceState {
360        fn new() -> Self {
361            Self {
362                nonces: Mutex::new(HashMap::new()),
363                clients: Mutex::new(HashMap::new()),
364            }
365        }
366        fn issue_nonce(&self) -> String {
367            use base64::Engine as _;
368            use rand::RngCore;
369            let mut b = [0u8; 16];
370            rand::rngs::OsRng.fill_bytes(&mut b);
371            let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b);
372            let exp = chrono::Utc::now().timestamp() + 300;
373            #[allow(clippy::unwrap_used)]
374            self.nonces.lock().insert(n.clone(), exp);
375            n
376        }
377        fn verify_nonce(&self, n: &str) -> bool {
378            let now = chrono::Utc::now().timestamp();
379            #[allow(clippy::unwrap_used)]
380            let g = self.nonces.lock();
381            g.get(n).is_some_and(|&e| e > now)
382        }
383        fn client_requires_nonce(&self, jkt: &str) -> bool {
384            let now = chrono::Utc::now().timestamp();
385            #[allow(clippy::unwrap_used)]
386            let mut g = self.clients.lock();
387            g.retain(|_, e| *e > now);
388            g.contains_key(jkt)
389        }
390        fn mark_nonced(&self, jkt: &str) {
391            let exp = chrono::Utc::now().timestamp() + 300;
392            #[allow(clippy::unwrap_used)]
393            self.clients.lock().insert(jkt.to_owned(), exp);
394        }
395    }
396
397    /// dpop_bootstrap_accepted_first_request:
398    /// First proof from a jkt with no nonce is accepted as a bootstrap.
399    #[test]
400    fn dpop_bootstrap_accepted_first_request() {
401        let s = NonceState::new();
402        assert!(!s.client_requires_nonce("jkt-1"));
403    }
404
405    /// dpop_subsequent_without_nonce_rejected:
406    /// After `mark_nonced`, the same jkt is required to present a nonce.
407    #[test]
408    fn dpop_subsequent_without_nonce_rejected() {
409        let s = NonceState::new();
410        let _n = s.issue_nonce();
411        s.mark_nonced("jkt-1");
412        assert!(s.client_requires_nonce("jkt-1"));
413    }
414
415    /// dpop_valid_nonce_accepted:
416    /// A presented nonce that we issued and not yet expired verifies.
417    #[test]
418    fn dpop_valid_nonce_accepted() {
419        let s = NonceState::new();
420        let n = s.issue_nonce();
421        s.mark_nonced("jkt-1");
422        assert!(s.verify_nonce(&n));
423    }
424
425    /// dpop_unknown_nonce_rejected:
426    /// A nonce we never issued is rejected.
427    #[test]
428    fn dpop_unknown_nonce_rejected() {
429        let s = NonceState::new();
430        s.mark_nonced("jkt-1");
431        assert!(!s.verify_nonce("not-a-real-nonce"));
432    }
433
434    /// dpop_jkt_isolation:
435    /// Different jkts have independent enforcement state.
436    #[test]
437    fn dpop_jkt_isolation() {
438        let s = NonceState::new();
439        s.mark_nonced("jkt-A");
440        assert!(s.client_requires_nonce("jkt-A"));
441        assert!(!s.client_requires_nonce("jkt-B"));
442    }
443}
444
445/// Regression test: take a JWT-style DPoP proof signed with a composite alg,
446/// strip the ML-DSA-65 sig half, confirm `verify_dpop_proof` rejects.
447#[cfg(test)]
448mod dpop_stripping_tests {
449    use super::*;
450    use ed25519_dalek::Signer as _;
451
452    fn signed_ed25519_proof(iat: i64) -> String {
453        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x33; 32]);
454        let header = serde_json::json!({
455            "typ": "dpop+jwt",
456            "alg": "EdDSA",
457            "jwk": {
458                "kty": "OKP",
459                "crv": "Ed25519",
460                "x": URL_SAFE_NO_PAD.encode(signing_key.verifying_key().to_bytes()),
461            },
462        });
463        let payload = serde_json::json!({
464            "jti": "extreme-iat",
465            "htm": "POST",
466            "htu": "https://example.test/oauth/token",
467            "iat": iat,
468        });
469        let signing_input = format!(
470            "{}.{}",
471            URL_SAFE_NO_PAD.encode(header.to_string()),
472            URL_SAFE_NO_PAD.encode(payload.to_string()),
473        );
474        let signature = signing_key.sign(signing_input.as_bytes());
475        format!(
476            "{signing_input}.{}",
477            URL_SAFE_NO_PAD.encode(signature.to_bytes())
478        )
479    }
480
481    #[test]
482    fn dpop_composite_stripped_signature_rejected() {
483        let (ml_sk, ml_vk) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
484        let ml_vk_bytes = hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(&ml_vk);
485        let ed_sk = ed25519_dalek::SigningKey::from_bytes(&[42u8; 32]);
486        let ed_vk_bytes = ed_sk.verifying_key().to_bytes();
487        let mut composite_pub = Vec::with_capacity(ml_vk_bytes.len() + 32);
488        composite_pub.extend_from_slice(&ml_vk_bytes);
489        composite_pub.extend_from_slice(&ed_vk_bytes);
490        let pub_b64 = URL_SAFE_NO_PAD.encode(&composite_pub);
491
492        let header = serde_json::json!({
493            "typ": "dpop+jwt",
494            "alg": "ML-DSA-65-Ed25519",
495            "jwk": { "kty": "AKP", "alg": "ML-DSA-65-Ed25519", "pub": pub_b64 },
496        });
497        let now = chrono::Utc::now().timestamp();
498        let payload = serde_json::json!({
499            "jti": "test-jti-1",
500            "htm": "POST",
501            "htu": "https://example.test/oauth/token",
502            "iat": now,
503        });
504        let h_b64 = URL_SAFE_NO_PAD.encode(header.to_string());
505        let p_b64 = URL_SAFE_NO_PAD.encode(payload.to_string());
506        let signing_input = format!("{h_b64}.{p_b64}");
507        let ml_sig = hyprstream_rpc::crypto::pq::ml_dsa_sign(&ml_sk, signing_input.as_bytes());
508        let ed_sig = ed_sk.sign(signing_input.as_bytes());
509
510        // Properly composed composite proof verifies.
511        let mut composite = Vec::with_capacity(ml_sig.len() + 64);
512        composite.extend_from_slice(&ml_sig);
513        composite.extend_from_slice(&ed_sig.to_bytes());
514        let good = format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(&composite));
515        assert!(verify_dpop_proof(&good, "POST", "https://example.test/oauth/token", None).is_ok());
516
517        // Stripped: only Ed25519 half (64 bytes) — composite-alg verifier
518        // requires 3309 + 64 bytes. Stripping must fail.
519        let stripped = format!(
520            "{signing_input}.{}",
521            URL_SAFE_NO_PAD.encode(ed_sig.to_bytes())
522        );
523        let err =
524            verify_dpop_proof(&stripped, "POST", "https://example.test/oauth/token", None).err();
525        assert!(
526            matches!(err, Some(DpopError::SignatureInvalid)),
527            "expected SignatureInvalid, got {err:?}"
528        );
529    }
530
531    #[test]
532    fn dpop_extreme_iat_is_rejected_without_signed_overflow() {
533        let proof = signed_ed25519_proof(i64::MIN);
534        assert!(matches!(
535            verify_dpop_proof(&proof, "POST", "https://example.test/oauth/token", None),
536            Err(DpopError::IatOutOfWindow { iat: i64::MIN, .. })
537        ));
538    }
539}