From 7fb6aecfd9924265cffdda3b94020b7b223446dc Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 20 Oct 2026 17:19:57 +0200 Subject: [PATCH 01/26] feat(dpop): add dpop proof --- rust/Cargo.lock | 13 ++ rust/Cargo.toml | 1 + rust/crates/keygo-core/Cargo.toml | 2 +- rust/crates/keygo-dpop/Cargo.toml | 14 ++ rust/crates/keygo-dpop/src/jwk.rs | 80 ++++++++ rust/crates/keygo-dpop/src/lib.rs | 4 + rust/crates/keygo-dpop/src/proof.rs | 290 ++++++++++++++++++++++++++++ rust/crates/keygo-opaque/Cargo.toml | 2 +- rust/crates/keygo-server/Cargo.toml | 3 +- 9 files changed, 406 insertions(+), 3 deletions(-) create mode 100644 rust/crates/keygo-dpop/Cargo.toml create mode 100644 rust/crates/keygo-dpop/src/jwk.rs create mode 100644 rust/crates/keygo-dpop/src/lib.rs create mode 100644 rust/crates/keygo-dpop/src/proof.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 26dbc4964..9b7ad51a3 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1606,6 +1606,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "keygo-dpop" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "getrandom 0.4.3", + "p256", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror", +] + [[package]] name = "keygo-opaque" version = "0.1.0" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 49a59cffe..983f4c55f 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -15,6 +15,7 @@ tokio = "1.48.0" uuid = { version = "1.23.1", features = ["serde", "v4"] } uniffi = "0.32.0" zeroize = "1.8.2" +base64 = "0.23.1" [profile.release] lto = true diff --git a/rust/crates/keygo-core/Cargo.toml b/rust/crates/keygo-core/Cargo.toml index 22e4981a7..69ef5f93f 100644 --- a/rust/crates/keygo-core/Cargo.toml +++ b/rust/crates/keygo-core/Cargo.toml @@ -7,6 +7,7 @@ edition.workspace = true thiserror.workspace = true uuid.workspace = true zeroize.workspace = true +base64.workspace = true aead = "0.6.0" aes-gcm-siv = "0.12.1" @@ -19,7 +20,6 @@ passkey-authenticator = { version = "0.6.0", features = ["tokio"] } passkey-types = { version = "0.6.0", features = ["serialize_bytes_as_base64_string"] } argon2 = "0.6.0" -base64 = "0.23.1" bcs = "0.2.0" csv = "1.4.0" email_address = "0.2.9" diff --git a/rust/crates/keygo-dpop/Cargo.toml b/rust/crates/keygo-dpop/Cargo.toml new file mode 100644 index 000000000..192ded20b --- /dev/null +++ b/rust/crates/keygo-dpop/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "keygo-dpop" +version.workspace = true +edition.workspace = true + +[dependencies] +thiserror.workspace = true +base64.workspace = true + +p256 = { version = "0.14.0", default-features = false, features = ["ecdsa", "getrandom"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11.1" +getrandom = "0.4.3" \ No newline at end of file diff --git a/rust/crates/keygo-dpop/src/jwk.rs b/rust/crates/keygo-dpop/src/jwk.rs new file mode 100644 index 000000000..83c1be657 --- /dev/null +++ b/rust/crates/keygo-dpop/src/jwk.rs @@ -0,0 +1,80 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use p256::ecdsa::VerifyingKey; +use serde::Serialize; +use sha2::{Digest, Sha256}; + +/// Public P-256 key as a JWK. +/// +/// Field order is load-bearing: RFC 7638 hashes the required members in lexicographic order. +#[derive(Debug, Serialize)] +pub struct Jwk { + crv: &'static str, + kty: &'static str, + x: String, + y: String, +} + +impl Jwk { + pub fn thumbprint(&self) -> [u8; 32] { + let canonical = serde_json::to_vec(self).expect("Jwk always serializes"); + Sha256::digest(canonical).into() + } +} + +impl From<&VerifyingKey> for Jwk { + fn from(v: &VerifyingKey) -> Self { + let point = v.to_sec1_point(false); + + let x = URL_SAFE_NO_PAD.encode(point.x().expect("x coordinate")); + let y = URL_SAFE_NO_PAD.encode(point.y().expect("y coordinate")); + + Self { + crv: "P-256", + kty: "EC", + x, + y, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use p256::ecdsa::SigningKey; + + fn jwk() -> Jwk { + let key = SigningKey::from_slice(&[7u8; 32]).unwrap(); + Jwk::from(key.verifying_key()) + } + + #[test] + fn serializes_members_in_rfc7638_order() { + let jwk = jwk(); + let expected = format!( + r#"{{"crv":"P-256","kty":"EC","x":"{}","y":"{}"}}"#, + jwk.x, jwk.y, + ); + + assert_eq!(serde_json::to_string(&jwk).unwrap(), expected); + } + + #[test] + fn coordinates_are_32_byte_base64url() { + let jwk = jwk(); + + assert_eq!(URL_SAFE_NO_PAD.decode(&jwk.x).unwrap().len(), 32); + assert_eq!(URL_SAFE_NO_PAD.decode(&jwk.y).unwrap().len(), 32); + } + + #[test] + fn thumbprint_is_sha256_of_canonical_json() { + let jwk = jwk(); + let canonical = serde_json::to_vec(&jwk).unwrap(); + + assert_eq!( + jwk.thumbprint(), + <[u8; 32]>::from(Sha256::digest(canonical)) + ); + } +} diff --git a/rust/crates/keygo-dpop/src/lib.rs b/rust/crates/keygo-dpop/src/lib.rs new file mode 100644 index 000000000..d543bfdb1 --- /dev/null +++ b/rust/crates/keygo-dpop/src/lib.rs @@ -0,0 +1,4 @@ +pub mod jwk; +mod proof; + +pub use proof::{DpopError, DpopProver, DpopSigner, Htm, ProofRequest}; diff --git a/rust/crates/keygo-dpop/src/proof.rs b/rust/crates/keygo-dpop/src/proof.rs new file mode 100644 index 000000000..a39f7089c --- /dev/null +++ b/rust/crates/keygo-dpop/src/proof.rs @@ -0,0 +1,290 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use p256::ecdsa::{Signature, VerifyingKey}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::jwk::Jwk; + +pub trait DpopSigner { + type Error: std::error::Error; + + fn verifying_key(&self) -> &VerifyingKey; + /// ES256 over `msg`. DER-producing backends (Android Keystore) convert with + /// [`Signature::from_der`]; JWS needs the fixed-size `r || s` form. + fn sign(&self, msg: &[u8]) -> Result; +} + +#[derive(Serialize)] +struct Header<'a> { + typ: &'static str, + alg: &'static str, + jwk: &'a Jwk, +} + +#[derive(Debug, Clone, Copy, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum Htm { + Get, + Post, + Delete, +} + +pub struct ProofRequest<'a> { + pub htm: Htm, + pub htu: &'a str, + pub access_token: Option<&'a str>, + pub nonce: Option<&'a str>, +} + +#[derive(Serialize)] +struct Claims<'a> { + jti: &'a str, + htm: Htm, + htu: &'a str, + iat: u64, + #[serde(skip_serializing_if = "Option::is_none")] + ath: Option, + #[serde(skip_serializing_if = "Option::is_none")] + nonce: Option<&'a str>, +} + +pub struct DpopProver { + signer: S, + jwk: Jwk, + jkt: [u8; 32], +} + +impl DpopProver { + pub fn new(signer: S) -> Self { + let jwk: Jwk = signer.verifying_key().into(); + let jkt = jwk.thumbprint(); + Self { signer, jwk, jkt } + } + + pub fn jkt(&self) -> &[u8; 32] { + &self.jkt + } + + pub fn proof(&self, req: &ProofRequest<'_>) -> Result> { + self.proof_at(req, unix_now(), &random_jti()?) + .map_err(DpopError::Signer) + } + + fn proof_at(&self, req: &ProofRequest<'_>, iat: u64, jti: &str) -> Result { + let header = Header { + typ: "dpop+jwt", + alg: "ES256", + jwk: &self.jwk, + }; + + let claims = Claims { + jti, + htm: req.htm, + htu: req.htu, + iat, + ath: req + .access_token + .map(|t| URL_SAFE_NO_PAD.encode(Sha256::digest(t))), + nonce: req.nonce, + }; + + let header = + URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("Header serializes")); + let claims = + URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("Claims serializes")); + let input = format!("{header}.{claims}"); + + let sig = self.signer.sign(input.as_bytes())?; + Ok(format!( + "{input}.{}", + URL_SAFE_NO_PAD.encode(sig.to_bytes()) + )) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum DpopError { + #[error("signer failed")] + Signer(#[source] E), + #[error("random number generator failed")] + Rng(#[from] getrandom::Error), +} + +fn random_jti() -> Result> { + let mut buf = [0u8; 16]; + getrandom::fill(&mut buf)?; + Ok(URL_SAFE_NO_PAD.encode(buf)) +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock is set before the Unix epoch") + .as_secs() +} + +#[cfg(test)] +mod tests { + use super::*; + use p256::ecdsa::SigningKey; + use p256::ecdsa::signature::{Signer, Verifier}; + use serde_json::Value; + use std::convert::Infallible; + + struct TestSigner { + key: SigningKey, + verifying: VerifyingKey, + } + + impl TestSigner { + fn new() -> Self { + let key = SigningKey::from_slice(&[7u8; 32]).unwrap(); + let verifying = *key.verifying_key(); + Self { key, verifying } + } + } + + impl DpopSigner for TestSigner { + type Error = Infallible; + + fn verifying_key(&self) -> &VerifyingKey { + &self.verifying + } + + fn sign(&self, msg: &[u8]) -> Result { + Ok(self.key.sign(msg)) + } + } + + const HTU: &str = "https://sync.example/api/v1/items"; + + fn request<'a>(access_token: Option<&'a str>, nonce: Option<&'a str>) -> ProofRequest<'a> { + ProofRequest { + htm: Htm::Post, + htu: HTU, + access_token, + nonce, + } + } + + struct Parts { + header: Value, + claims: Value, + signing_input: String, + signature: Vec, + } + + fn split(jwt: &str) -> Parts { + let parts: Vec<&str> = jwt.split('.').collect(); + assert_eq!(parts.len(), 3, "compact JWS has three segments"); + + let json = |s: &str| serde_json::from_slice(&URL_SAFE_NO_PAD.decode(s).unwrap()).unwrap(); + Parts { + header: json(parts[0]), + claims: json(parts[1]), + signing_input: format!("{}.{}", parts[0], parts[1]), + signature: URL_SAFE_NO_PAD.decode(parts[2]).unwrap(), + } + } + + #[test] + fn header_declares_dpop_type_and_es256() { + let dpop = DpopProver::new(TestSigner::new()); + let parts = split( + &dpop + .proof_at(&request(None, None), 1_700_000_000, "jti") + .unwrap(), + ); + + assert_eq!(parts.header["typ"], "dpop+jwt"); + assert_eq!(parts.header["alg"], "ES256"); + assert_eq!( + parts.header["jwk"], + serde_json::to_value(Jwk::from(&TestSigner::new().verifying)).unwrap(), + ); + assert_eq!(parts.header.as_object().unwrap().len(), 3); + } + + #[test] + fn signature_is_raw_r_s_and_verifies_against_embedded_key() { + let signer = TestSigner::new(); + let verifying = signer.verifying; + let dpop = DpopProver::new(signer); + let parts = split( + &dpop + .proof_at(&request(None, None), 1_700_000_000, "jti") + .unwrap(), + ); + + assert_eq!(parts.signature.len(), 64); + let sig = Signature::from_slice(&parts.signature).unwrap(); + assert!( + verifying + .verify(parts.signing_input.as_bytes(), &sig) + .is_ok() + ); + } + + #[test] + fn claims_carry_request_binding() { + let dpop = DpopProver::new(TestSigner::new()); + let parts = split( + &dpop + .proof_at(&request(None, None), 1_700_000_000, "abc") + .unwrap(), + ); + + assert_eq!(parts.claims["jti"], "abc"); + assert_eq!(parts.claims["htm"], "POST"); + assert_eq!(parts.claims["htu"], HTU); + assert_eq!(parts.claims["iat"], 1_700_000_000); + } + + #[test] + fn optional_claims_are_omitted_when_absent() { + let dpop = DpopProver::new(TestSigner::new()); + let parts = split(&dpop.proof_at(&request(None, None), 0, "jti").unwrap()); + let claims = parts.claims.as_object().unwrap(); + + assert!(!claims.contains_key("ath")); + assert!(!claims.contains_key("nonce")); + } + + #[test] + fn ath_is_base64url_sha256_of_access_token() { + let dpop = DpopProver::new(TestSigner::new()); + let parts = split( + &dpop + .proof_at(&request(Some("token"), Some("n0nce")), 0, "jti") + .unwrap(), + ); + + // SHA-256("token"), base64url without padding + assert_eq!( + parts.claims["ath"], + "PEaenWxYddN6Q_NT1PiOYfz4EsZu7jRXRlpAsNpBU-A" + ); + assert_eq!(parts.claims["nonce"], "n0nce"); + } + + #[test] + fn jkt_is_thumbprint_of_signer_key() { + let dpop = DpopProver::new(TestSigner::new()); + + assert_eq!( + dpop.jkt(), + &Jwk::from(&TestSigner::new().verifying).thumbprint() + ); + } + + #[test] + fn proof_uses_fresh_jti_each_call() { + let dpop = DpopProver::new(TestSigner::new()); + let a = split(&dpop.proof(&request(None, None)).unwrap()); + let b = split(&dpop.proof(&request(None, None)).unwrap()); + + assert_ne!(a.claims["jti"], b.claims["jti"]); + } +} diff --git a/rust/crates/keygo-opaque/Cargo.toml b/rust/crates/keygo-opaque/Cargo.toml index b4bbf8cab..cff48a988 100644 --- a/rust/crates/keygo-opaque/Cargo.toml +++ b/rust/crates/keygo-opaque/Cargo.toml @@ -6,8 +6,8 @@ edition.workspace = true [dependencies] thiserror.workspace = true zeroize.workspace = true +base64.workspace = true -base64 = "0.23.1" serde = "1.0.229" opaque-ke = { version = "4.0.1", default-features = false, features = ["argon2", "ristretto255"] } diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 358321d9c..9d839fcaa 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -8,11 +8,12 @@ edition.workspace = true keygo-opaque = { path = "../keygo-opaque" } zeroize.workspace = true thiserror.workspace = true +base64.workspace = true + anstream = "1.0.0" anstyle = "1.0.14" anyhow = "1.0.104" clap = { version = "4.6.7", features = ["derive", "env"] } -base64 = "0.23.1" getrandom = "0.4.3" hex = "0.4.3" secrecy = "0.10.3" From 266617f260ed35a5e920796fb6d4adb0719065bb Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 20 Oct 2026 20:27:16 +0200 Subject: [PATCH 02/26] feat(dpop): add basic dpop verification --- rust/crates/keygo-dpop/src/jwk.rs | 67 ++++++- rust/crates/keygo-dpop/src/lib.rs | 7 +- rust/crates/keygo-dpop/src/proof.rs | 103 +++-------- rust/crates/keygo-dpop/src/testing.rs | 33 ++++ rust/crates/keygo-dpop/src/verify.rs | 244 ++++++++++++++++++++++++++ rust/crates/keygo-dpop/src/wire.rs | 117 ++++++++++++ 6 files changed, 489 insertions(+), 82 deletions(-) create mode 100644 rust/crates/keygo-dpop/src/testing.rs create mode 100644 rust/crates/keygo-dpop/src/verify.rs create mode 100644 rust/crates/keygo-dpop/src/wire.rs diff --git a/rust/crates/keygo-dpop/src/jwk.rs b/rust/crates/keygo-dpop/src/jwk.rs index 83c1be657..f097ff36f 100644 --- a/rust/crates/keygo-dpop/src/jwk.rs +++ b/rust/crates/keygo-dpop/src/jwk.rs @@ -1,18 +1,38 @@ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::VerifyingKey; -use serde::Serialize; +use p256::{FieldBytes, Sec1Point}; +use serde::de::IgnoredAny; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; +use thiserror::Error; /// Public P-256 key as a JWK. /// /// Field order is load-bearing: RFC 7638 hashes the required members in lexicographic order. -#[derive(Debug, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Jwk { - crv: &'static str, - kty: &'static str, + crv: Crv, + kty: Kty, x: String, y: String, + + // Only read so a received private key can be rejected; never serialized, so it cannot leak + // into a header or change the thumbprint. + #[serde(default, skip_serializing)] + d: Option, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +enum Crv { + #[serde(rename = "P-256")] + P256, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +enum Kty { + #[serde(rename = "EC")] + Ec, } impl Jwk { @@ -30,11 +50,46 @@ impl From<&VerifyingKey> for Jwk { let y = URL_SAFE_NO_PAD.encode(point.y().expect("y coordinate")); Self { - crv: "P-256", - kty: "EC", + crv: Crv::P256, + kty: Kty::Ec, x, y, + d: None, + } + } +} + +#[derive(Debug, Error)] +pub enum JwkError { + #[error("jwk contains a private key")] + PrivateKey, + #[error("invalid base64url in coordinate")] + Base64(#[from] base64::DecodeError), + #[error("coordinate must be 32 bytes")] + CoordinateLength, + #[error("point is not on the P-256 curve")] + InvalidPoint, +} + +impl Jwk { + pub(crate) fn verifying_key(&self) -> Result { + if self.d.is_some() { + return Err(JwkError::PrivateKey); } + + let x = URL_SAFE_NO_PAD.decode(&self.x)?; + let y = URL_SAFE_NO_PAD.decode(&self.y)?; + let x: &FieldBytes = x + .as_slice() + .try_into() + .map_err(|_| JwkError::CoordinateLength)?; + let y: &FieldBytes = y + .as_slice() + .try_into() + .map_err(|_| JwkError::CoordinateLength)?; + + let point = Sec1Point::from_affine_coordinates(x, y, false); + VerifyingKey::from_sec1_point(&point).map_err(|_| JwkError::InvalidPoint) } } diff --git a/rust/crates/keygo-dpop/src/lib.rs b/rust/crates/keygo-dpop/src/lib.rs index d543bfdb1..2e377203e 100644 --- a/rust/crates/keygo-dpop/src/lib.rs +++ b/rust/crates/keygo-dpop/src/lib.rs @@ -1,4 +1,9 @@ pub mod jwk; mod proof; +#[cfg(test)] +mod testing; +pub mod verify; +pub mod wire; -pub use proof::{DpopError, DpopProver, DpopSigner, Htm, ProofRequest}; +pub use proof::{DpopError, DpopProver, DpopSigner, ProofRequest}; +pub use wire::Htm; diff --git a/rust/crates/keygo-dpop/src/proof.rs b/rust/crates/keygo-dpop/src/proof.rs index a39f7089c..4e2d4545f 100644 --- a/rust/crates/keygo-dpop/src/proof.rs +++ b/rust/crates/keygo-dpop/src/proof.rs @@ -1,12 +1,12 @@ +use crate::Htm; +use crate::jwk::Jwk; +use crate::wire::{self, Alg, Claims, Header, Typ}; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::{Signature, VerifyingKey}; -use serde::Serialize; use sha2::{Digest, Sha256}; use std::time::{SystemTime, UNIX_EPOCH}; -use crate::jwk::Jwk; - pub trait DpopSigner { type Error: std::error::Error; @@ -16,21 +16,6 @@ pub trait DpopSigner { fn sign(&self, msg: &[u8]) -> Result; } -#[derive(Serialize)] -struct Header<'a> { - typ: &'static str, - alg: &'static str, - jwk: &'a Jwk, -} - -#[derive(Debug, Clone, Copy, Serialize)] -#[serde(rename_all = "UPPERCASE")] -pub enum Htm { - Get, - Post, - Delete, -} - pub struct ProofRequest<'a> { pub htm: Htm, pub htu: &'a str, @@ -38,21 +23,9 @@ pub struct ProofRequest<'a> { pub nonce: Option<&'a str>, } -#[derive(Serialize)] -struct Claims<'a> { - jti: &'a str, - htm: Htm, - htu: &'a str, - iat: u64, - #[serde(skip_serializing_if = "Option::is_none")] - ath: Option, - #[serde(skip_serializing_if = "Option::is_none")] - nonce: Option<&'a str>, -} - pub struct DpopProver { signer: S, - jwk: Jwk, + encoded_header: String, jkt: [u8; 32], } @@ -60,7 +33,17 @@ impl DpopProver { pub fn new(signer: S) -> Self { let jwk: Jwk = signer.verifying_key().into(); let jkt = jwk.thumbprint(); - Self { signer, jwk, jkt } + let encoded_header = wire::encode(&Header { + typ: Typ::DpopJwt, + alg: Alg::Es256, + jwk, + }); + + Self { + signer, + encoded_header, + jkt, + } } pub fn jkt(&self) -> &[u8; 32] { @@ -72,29 +55,24 @@ impl DpopProver { .map_err(DpopError::Signer) } - fn proof_at(&self, req: &ProofRequest<'_>, iat: u64, jti: &str) -> Result { - let header = Header { - typ: "dpop+jwt", - alg: "ES256", - jwk: &self.jwk, - }; - + pub(crate) fn proof_at( + &self, + req: &ProofRequest<'_>, + iat: u64, + jti: &str, + ) -> Result { let claims = Claims { - jti, + jti: jti.to_owned(), htm: req.htm, - htu: req.htu, + htu: req.htu.to_owned(), iat, ath: req .access_token .map(|t| URL_SAFE_NO_PAD.encode(Sha256::digest(t))), - nonce: req.nonce, + nonce: req.nonce.map(str::to_owned), }; - let header = - URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("Header serializes")); - let claims = - URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("Claims serializes")); - let input = format!("{header}.{claims}"); + let input = format!("{}.{}", self.encoded_header, wire::encode(&claims)); let sig = self.signer.sign(input.as_bytes())?; Ok(format!( @@ -128,35 +106,10 @@ fn unix_now() -> u64 { #[cfg(test)] mod tests { use super::*; - use p256::ecdsa::SigningKey; - use p256::ecdsa::signature::{Signer, Verifier}; + use crate::Htm; + use crate::testing::TestSigner; + use p256::ecdsa::signature::Verifier; use serde_json::Value; - use std::convert::Infallible; - - struct TestSigner { - key: SigningKey, - verifying: VerifyingKey, - } - - impl TestSigner { - fn new() -> Self { - let key = SigningKey::from_slice(&[7u8; 32]).unwrap(); - let verifying = *key.verifying_key(); - Self { key, verifying } - } - } - - impl DpopSigner for TestSigner { - type Error = Infallible; - - fn verifying_key(&self) -> &VerifyingKey { - &self.verifying - } - - fn sign(&self, msg: &[u8]) -> Result { - Ok(self.key.sign(msg)) - } - } const HTU: &str = "https://sync.example/api/v1/items"; diff --git a/rust/crates/keygo-dpop/src/testing.rs b/rust/crates/keygo-dpop/src/testing.rs new file mode 100644 index 000000000..2a6d0e797 --- /dev/null +++ b/rust/crates/keygo-dpop/src/testing.rs @@ -0,0 +1,33 @@ +use crate::DpopSigner; +use p256::ecdsa::signature::Signer; +use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; +use std::convert::Infallible; + +pub(crate) struct TestSigner { + key: SigningKey, + pub(crate) verifying: VerifyingKey, +} + +impl TestSigner { + pub(crate) fn new() -> Self { + Self::from_seed(7) + } + + pub(crate) fn from_seed(seed: u8) -> Self { + let key = SigningKey::from_slice(&[seed; 32]).unwrap(); + let verifying = *key.verifying_key(); + Self { key, verifying } + } +} + +impl DpopSigner for TestSigner { + type Error = Infallible; + + fn verifying_key(&self) -> &VerifyingKey { + &self.verifying + } + + fn sign(&self, msg: &[u8]) -> Result { + Ok(self.key.sign(msg)) + } +} diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs new file mode 100644 index 000000000..a493c4a4f --- /dev/null +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -0,0 +1,244 @@ +use crate::wire::{Claims, Header}; +use crate::{Htm, jwk, wire}; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use p256::ecdsa::Signature; +use p256::ecdsa::signature::Verifier; +use sha2::{Digest, Sha256}; +use thiserror::Error; + +pub struct Expected<'a> { + pub htm: Htm, + pub htu: &'a str, + pub access_token: Option<&'a str>, +} + +pub struct VerifiedProof { + pub jkt: [u8; 32], + pub jti: String, + pub iat: u64, +} + +#[derive(Debug, Error)] +pub enum VerifyError { + #[error("proof malformed")] + Malformed, + #[error(transparent)] + DecodeError(#[from] wire::DecodeError), + #[error(transparent)] + JwkError(#[from] jwk::JwkError), + #[error("Signature verification failed")] + Signature, + #[error("invalid request")] + Request, + #[error("invalid access token")] + AccessTokenHash, +} + +type VerifyResult = Result; + +pub fn verify(proof: &str, expected: Expected) -> VerifyResult { + let (input, sign) = proof.rsplit_once('.').ok_or(VerifyError::Malformed)?; + let (header, claims) = input.split_once('.').ok_or(VerifyError::Malformed)?; + + let header = wire::decode::
(header)?; + let key = header.jwk.verifying_key()?; + let sign = URL_SAFE_NO_PAD + .decode(sign) + .map_err(|_| VerifyError::Signature)?; + let sign = Signature::from_slice(&sign).map_err(|_| VerifyError::Signature)?; + key.verify(input.as_bytes(), &sign) + .map_err(|_| VerifyError::Signature)?; + + let Claims { + jti, + htm, + htu, + iat, + ath, + nonce: _, + } = wire::decode(claims)?; + + if htm != expected.htm || htu != expected.htu { + return Err(VerifyError::Request); + } + + let expected_ath = expected + .access_token + .map(|t| URL_SAFE_NO_PAD.encode(Sha256::digest(t))); + if ath != expected_ath { + return Err(VerifyError::AccessTokenHash); + } + + Ok(VerifiedProof { + jkt: header.jwk.thumbprint(), + jti, + iat, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TestSigner; + use crate::{DpopProver, ProofRequest}; + + const HTU: &str = "https://sync.example/api/v1/items"; + const NOW: u64 = 1_700_000_000; + + fn proof(iat: u64, access_token: Option<&str>) -> String { + let req = ProofRequest { + htm: Htm::Post, + htu: HTU, + access_token, + nonce: None, + }; + DpopProver::new(TestSigner::new()) + .proof_at(&req, iat, "jti") + .unwrap() + } + + fn expected(access_token: Option<&str>) -> Expected<'_> { + Expected { + htm: Htm::Post, + htu: HTU, + access_token, + } + } + + /// Swaps one segment of a compact JWS, leaving the others untouched. + fn replace_segment(proof: &str, index: usize, segment: &str) -> String { + let mut parts: Vec<&str> = proof.split('.').collect(); + parts[index] = segment; + parts.join(".") + } + + #[test] + fn accepts_own_proof() { + let verified = verify(&proof(NOW, None), expected(None)).unwrap(); + + assert_eq!(&verified.jkt, DpopProver::new(TestSigner::new()).jkt()); + assert_eq!(verified.jti, "jti"); + assert_eq!(verified.iat, NOW); + } + + #[test] + fn accepts_matching_access_token() { + assert!(verify(&proof(NOW, Some("token")), expected(Some("token"))).is_ok()); + } + + #[test] + fn rejects_wrong_access_token() { + let result = verify(&proof(NOW, Some("token")), expected(Some("other"))); + + assert!(matches!(result, Err(VerifyError::AccessTokenHash))); + } + + #[test] + fn rejects_missing_ath_when_token_present() { + let result = verify(&proof(NOW, None), expected(Some("token"))); + + assert!(matches!(result, Err(VerifyError::AccessTokenHash))); + } + + #[test] + fn rejects_unexpected_ath() { + let result = verify(&proof(NOW, Some("token")), expected(None)); + + assert!(matches!(result, Err(VerifyError::AccessTokenHash))); + } + + #[test] + fn rejects_other_method_or_uri() { + let mut wrong_htm = expected(None); + wrong_htm.htm = Htm::Get; + let mut wrong_htu = expected(None); + wrong_htu.htu = "https://sync.example/api/v1/other"; + + assert!(matches!( + verify(&proof(NOW, None), wrong_htm), + Err(VerifyError::Request) + )); + assert!(matches!( + verify(&proof(NOW, None), wrong_htu), + Err(VerifyError::Request) + )); + } + + #[test] + fn rejects_tampered_claims() { + let other = proof(NOW + 1, None); + let claims = other.split('.').nth(1).unwrap(); + let tampered = replace_segment(&proof(NOW, None), 1, claims); + + assert!(matches!( + verify(&tampered, expected(None)), + Err(VerifyError::Signature) + )); + } + + #[test] + fn rejects_proof_signed_by_another_key() { + let foreign = DpopProver::new(TestSigner::from_seed(9)) + .proof_at( + &ProofRequest { + htm: Htm::Post, + htu: HTU, + access_token: None, + nonce: None, + }, + NOW, + "jti", + ) + .unwrap(); + let signature = foreign.rsplit('.').next().unwrap(); + let forged = replace_segment(&proof(NOW, None), 2, signature); + + assert!(matches!( + verify(&forged, expected(None)), + Err(VerifyError::Signature) + )); + } + + #[test] + fn rejects_jwk_with_private_key() { + let header = proof(NOW, None).split('.').next().unwrap().to_owned(); + let mut json: serde_json::Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header).unwrap()).unwrap(); + json["jwk"]["d"] = "c2VjcmV0".into(); + let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json).unwrap()); + let leaked = replace_segment(&proof(NOW, None), 0, &header); + + assert!(matches!( + verify(&leaked, expected(None)), + Err(VerifyError::JwkError(jwk::JwkError::PrivateKey)), + )); + } + + #[test] + fn rejects_non_base64_jwk_coordinate_without_panicking() { + let header = proof(NOW, None).split('.').next().unwrap().to_owned(); + let mut json: serde_json::Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header).unwrap()).unwrap(); + json["jwk"]["x"] = "not base64!".into(); + let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json).unwrap()); + let broken = replace_segment(&proof(NOW, None), 0, &header); + + assert!(matches!( + verify(&broken, expected(None)), + Err(VerifyError::JwkError(jwk::JwkError::Base64(_))), + )); + } + + #[test] + fn rejects_missing_segments() { + assert!(matches!( + verify("abc", expected(None)), + Err(VerifyError::Malformed) + )); + assert!(matches!( + verify("abc.def", expected(None)), + Err(VerifyError::Malformed) + )); + } +} diff --git a/rust/crates/keygo-dpop/src/wire.rs b/rust/crates/keygo-dpop/src/wire.rs new file mode 100644 index 000000000..f2a17c406 --- /dev/null +++ b/rust/crates/keygo-dpop/src/wire.rs @@ -0,0 +1,117 @@ +use crate::jwk::Jwk; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive(Serialize, Deserialize)] +pub(crate) struct Header { + pub(crate) typ: Typ, + pub(crate) alg: Alg, + pub(crate) jwk: Jwk, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct Claims { + pub(crate) jti: String, + pub(crate) htm: Htm, + pub(crate) htu: String, + pub(crate) iat: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) ath: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) nonce: Option, +} + +pub(crate) fn encode(value: &T) -> String { + URL_SAFE_NO_PAD.encode(serde_json::to_vec(value).expect("wire types always serialize")) +} + +#[derive(Debug, Error)] +pub enum DecodeError { + #[error("invalid base64: {0}")] + Base64(#[from] base64::DecodeError), + #[error("invalid json: {0}")] + Json(#[from] serde_json::Error), +} + +pub(crate) fn decode(value: &str) -> Result { + let bytes = URL_SAFE_NO_PAD.decode(value)?; + Ok(serde_json::from_slice(bytes.as_slice())?) +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub(crate) enum Typ { + #[serde(rename = "dpop+jwt")] + DpopJwt, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +pub(crate) enum Alg { + #[serde(rename = "ES256")] + Es256, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum Htm { + Get, + Post, + Delete, +} + +#[cfg(test)] +mod tests { + use super::*; + use p256::ecdsa::SigningKey; + + fn jwk_json() -> String { + let key = SigningKey::from_slice(&[7u8; 32]).unwrap(); + serde_json::to_string(&Jwk::from(key.verifying_key())).unwrap() + } + + fn header_json(typ: &str, alg: &str, jwk: &str) -> String { + format!(r#"{{"typ":"{typ}","alg":"{alg}","jwk":{jwk}}}"#) + } + + #[test] + fn header_round_trips() { + let json = header_json("dpop+jwt", "ES256", &jwk_json()); + let header: Header = serde_json::from_str(&json).unwrap(); + + assert_eq!(serde_json::to_string(&header).unwrap(), json); + } + + #[test] + fn header_rejects_other_alg() { + let json = header_json("dpop+jwt", "none", &jwk_json()); + + assert!(serde_json::from_str::
(&json).is_err()); + } + + #[test] + fn header_rejects_other_typ() { + let json = header_json("JWT", "ES256", &jwk_json()); + + assert!(serde_json::from_str::
(&json).is_err()); + } + + #[test] + fn header_rejects_other_curve() { + let jwk = jwk_json().replace("P-256", "P-384"); + let json = header_json("dpop+jwt", "ES256", &jwk); + + assert!(serde_json::from_str::
(&json).is_err()); + } + + #[test] + fn claims_accept_escaped_strings() { + let json = r#"{"jti":"j","htm":"GET","htu":"https:\/\/sync.example\/x","iat":1}"#; + let claims: Claims = serde_json::from_str(json).unwrap(); + + assert_eq!(claims.htu, "https://sync.example/x"); + assert!(claims.ath.is_none()); + assert!(claims.nonce.is_none()); + } +} From 9ebf66947d449585c74a1e3541f1aa5e351b61f3 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 21 Oct 2026 14:37:15 +0200 Subject: [PATCH 03/26] feat(dpop): add jti ttl and seen checks --- rust/Cargo.lock | 41 +++ rust/crates/keygo-dpop/Cargo.toml | 4 + rust/crates/keygo-dpop/src/htu.rs | 121 +++++++ rust/crates/keygo-dpop/src/lib.rs | 13 + rust/crates/keygo-dpop/src/nonce.rs | 148 +++++++++ rust/crates/keygo-dpop/src/proof.rs | 48 ++- rust/crates/keygo-dpop/src/seen_jtis.rs | 105 ++++++ rust/crates/keygo-dpop/src/verify.rs | 411 ++++++++++++++++++++---- rust/crates/keygo-dpop/src/wire.rs | 18 +- 9 files changed, 835 insertions(+), 74 deletions(-) create mode 100644 rust/crates/keygo-dpop/src/htu.rs create mode 100644 rust/crates/keygo-dpop/src/nonce.rs create mode 100644 rust/crates/keygo-dpop/src/seen_jtis.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 9b7ad51a3..bdc26ce42 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -394,6 +394,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + [[package]] name = "bumpalo" version = "3.20.3" @@ -1048,6 +1054,17 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + [[package]] name = "flume" version = "0.12.0" @@ -1611,12 +1628,16 @@ name = "keygo-dpop" version = "0.1.0" dependencies = [ "base64 0.23.1", + "fluent-uri", "getrandom 0.4.3", + "hmac 0.13.0", + "moka", "p256", "serde", "serde_json", "sha2 0.11.1", "thiserror", + "zeroize", ] [[package]] @@ -2233,6 +2254,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.7", +] + [[package]] name = "regex-automata" version = "0.4.18" diff --git a/rust/crates/keygo-dpop/Cargo.toml b/rust/crates/keygo-dpop/Cargo.toml index 192ded20b..d35d987fd 100644 --- a/rust/crates/keygo-dpop/Cargo.toml +++ b/rust/crates/keygo-dpop/Cargo.toml @@ -5,8 +5,12 @@ edition.workspace = true [dependencies] thiserror.workspace = true +zeroize.workspace = true base64.workspace = true +fluent-uri = "0.4.1" +hmac = "0.13.0" +moka = { version = "0.12.16", features = ["sync"] } p256 = { version = "0.14.0", default-features = false, features = ["ecdsa", "getrandom"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" diff --git a/rust/crates/keygo-dpop/src/htu.rs b/rust/crates/keygo-dpop/src/htu.rs new file mode 100644 index 000000000..037866847 --- /dev/null +++ b/rust/crates/keygo-dpop/src/htu.rs @@ -0,0 +1,121 @@ +use fluent_uri::Uri; + +/// Compares a proof's `htu` with the request URI as RFC 9449 §4.3 asks: ignoring query and fragment, +/// after RFC 3986 syntax-based (§6.2.2) and scheme-based (§6.2.3) normalization. Either side failing +/// to parse as an absolute URI is a mismatch. +pub(crate) fn matches(htu: &str, request: &str) -> bool { + match (canonical(htu), canonical(request)) { + (Some(htu), Some(request)) => htu == request, + _ => false, + } +} + +/// The RFC 9449 §4.2 form of `uri`: normalized, without query and fragment. `None` unless `uri` is +/// absolute. +pub(crate) fn canonical(uri: &str) -> Option { + let uri = Uri::parse(uri).ok()?.normalize(); + let mut canonical = format!("{}:", uri.scheme().as_str()); + + if let Some(authority) = uri.authority() { + canonical.push_str("//"); + canonical.push_str(authority.as_str()); + } + match uri.path().as_str() { + // RFC 3986 §6.2.3: with an authority, an empty path means "/". + "" if uri.authority().is_some() => canonical.push('/'), + path => canonical.push_str(path), + } + + Some(canonical) +} + +#[cfg(test)] +mod tests { + use super::*; + + const REQUEST: &str = "https://vault.example.org/v1/auth/token"; + + #[test] + fn identical_uris_match() { + assert!(matches(REQUEST, REQUEST)); + } + + #[test] + fn ignores_query_and_fragment() { + assert!(matches( + "https://vault.example.org/v1/auth/token?a=b#c", + REQUEST + )); + assert!(matches( + REQUEST, + "https://vault.example.org/v1/auth/token?x=1" + )); + } + + #[test] + fn scheme_and_host_are_case_insensitive() { + assert!(matches("HTTPS://Vault.EXAMPLE.org/v1/auth/token", REQUEST)); + } + + #[test] + fn path_is_case_sensitive() { + assert!(!matches("https://vault.example.org/v1/Auth/token", REQUEST)); + } + + #[test] + fn default_port_is_dropped() { + assert!(matches( + "https://vault.example.org:443/v1/auth/token", + REQUEST + )); + assert!(!matches( + "https://vault.example.org:8443/v1/auth/token", + REQUEST + )); + } + + #[test] + fn unreserved_percent_encoding_is_decoded() { + assert!(matches( + "https://vault.example.org/v1/%61uth/token", + REQUEST + )); + } + + #[test] + fn reserved_percent_encoding_is_kept() { + assert!(!matches( + "https://vault.example.org/v1%2Fauth/token", + REQUEST + )); + } + + #[test] + fn dot_segments_are_removed() { + assert!(matches( + "https://vault.example.org/v1/x/../auth/./token", + REQUEST + )); + } + + #[test] + fn empty_path_equals_root() { + assert!(matches( + "https://vault.example.org", + "https://vault.example.org/" + )); + } + + #[test] + fn other_scheme_or_host_does_not_match() { + assert!(!matches("http://vault.example.org/v1/auth/token", REQUEST)); + assert!(!matches("https://evil.example.org/v1/auth/token", REQUEST)); + } + + #[test] + fn unparsable_uri_does_not_match() { + assert!(!matches("not a uri", REQUEST)); + assert!(!matches("/v1/auth/token", REQUEST)); + assert!(!matches(REQUEST, "not a uri")); + } +} diff --git a/rust/crates/keygo-dpop/src/lib.rs b/rust/crates/keygo-dpop/src/lib.rs index 2e377203e..2791577c2 100644 --- a/rust/crates/keygo-dpop/src/lib.rs +++ b/rust/crates/keygo-dpop/src/lib.rs @@ -1,9 +1,22 @@ +mod htu; pub mod jwk; +mod nonce; mod proof; +mod seen_jtis; #[cfg(test)] mod testing; pub mod verify; pub mod wire; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub use nonce::{Nonce, NonceKey}; pub use proof::{DpopError, DpopProver, DpopSigner, ProofRequest}; pub use wire::Htm; + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock is set before the Unix epoch") + .as_secs() +} diff --git a/rust/crates/keygo-dpop/src/nonce.rs b/rust/crates/keygo-dpop/src/nonce.rs new file mode 100644 index 000000000..765475fc9 --- /dev/null +++ b/rust/crates/keygo-dpop/src/nonce.rs @@ -0,0 +1,148 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use hmac::{Hmac, KeyInit, Mac}; +use sha2::Sha256; +use std::fmt::{Display, Formatter}; +use std::time::Duration; +use zeroize::Zeroizing; + +const NONCE_LIFETIME: Duration = Duration::from_mins(5); + +const TIMESTAMP_LEN: usize = size_of::(); +/// HMAC-SHA256 truncated to its leftmost 16 bytes (spec §10). +const TAG_LEN: usize = 16; +const NONCE_LEN: usize = TIMESTAMP_LEN + TAG_LEN; + +pub struct NonceKey(Zeroizing<[u8; 32]>); + +impl NonceKey { + pub fn new(bytes: [u8; 32]) -> Self { + Self(Zeroizing::new(bytes)) + } + + fn mac(&self, created_at: u64) -> Hmac { + let mut mac = + Hmac::::new_from_slice(self.0.as_slice()).expect("HMAC accepts any key length"); + mac.update(&created_at.to_be_bytes()); + mac + } + + fn tag(&self, created_at: u64) -> [u8; TAG_LEN] { + self.mac(created_at).finalize().into_bytes()[..TAG_LEN] + .try_into() + .expect("SHA-256 output is longer than TAG_LEN") + } + + pub(crate) fn issue(&self, now: u64) -> Nonce { + Nonce { + created_at: now, + tag: self.tag(now), + } + } + + /// Returns the nonce if this key issued it. Freshness is the caller's call: it depends on the + /// server start, which the key does not know. + pub(crate) fn open(&self, value: &str) -> Option { + let bytes: [u8; NONCE_LEN] = URL_SAFE_NO_PAD.decode(value).ok()?.try_into().ok()?; + let (created_at, tag) = bytes + .split_first_chunk::() + .expect("NONCE_LEN holds the timestamp"); + let created_at = u64::from_be_bytes(*created_at); + + // `verify_truncated_left` checks only as many bytes as it is given; `bytes` has a fixed + // length, so the tag is always exactly TAG_LEN. + self.mac(created_at).verify_truncated_left(tag).ok()?; + + Some(Nonce { + created_at, + tag: tag.try_into().expect("NONCE_LEN holds the tag after it"), + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Nonce { + created_at: u64, + tag: [u8; TAG_LEN], +} + +impl Nonce { + pub(crate) fn created_at(&self) -> u64 { + self.created_at + } + + pub(crate) fn expires_at(&self) -> u64 { + self.created_at + NONCE_LIFETIME.as_secs() + } +} + +impl Display for Nonce { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut bytes = [0u8; NONCE_LEN]; + bytes[..TIMESTAMP_LEN].copy_from_slice(&self.created_at.to_be_bytes()); + bytes[TIMESTAMP_LEN..].copy_from_slice(&self.tag); + + f.write_str(&URL_SAFE_NO_PAD.encode(bytes)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW: u64 = 1_700_000_000; + + fn key() -> NonceKey { + NonceKey::new([1; 32]) + } + + #[test] + fn opens_own_nonce() { + let nonce = key().issue(NOW); + + assert_eq!(key().open(&nonce.to_string()), Some(nonce)); + } + + #[test] + fn encodes_created_at_big_endian_before_tag() { + let bytes = URL_SAFE_NO_PAD + .decode(key().issue(NOW).to_string()) + .unwrap(); + + assert_eq!(bytes.len(), NONCE_LEN); + assert_eq!(&bytes[..TIMESTAMP_LEN], &NOW.to_be_bytes()); + } + + #[test] + fn expires_after_lifetime() { + assert_eq!( + key().issue(NOW).expires_at(), + NOW + NONCE_LIFETIME.as_secs() + ); + } + + #[test] + fn rejects_nonce_from_another_key() { + let foreign = NonceKey::new([2; 32]).issue(NOW).to_string(); + + assert_eq!(key().open(&foreign), None); + } + + #[test] + fn rejects_shifted_timestamp() { + let mut bytes = URL_SAFE_NO_PAD + .decode(key().issue(NOW).to_string()) + .unwrap(); + bytes[TIMESTAMP_LEN - 1] ^= 1; + + assert_eq!(key().open(&URL_SAFE_NO_PAD.encode(bytes)), None); + } + + #[test] + fn rejects_malformed_nonce() { + let truncated = &key().issue(NOW).to_string()[..10]; + + assert_eq!(key().open("not base64!"), None); + assert_eq!(key().open(truncated), None); + } +} diff --git a/rust/crates/keygo-dpop/src/proof.rs b/rust/crates/keygo-dpop/src/proof.rs index 4e2d4545f..8e5c2e819 100644 --- a/rust/crates/keygo-dpop/src/proof.rs +++ b/rust/crates/keygo-dpop/src/proof.rs @@ -1,11 +1,10 @@ -use crate::Htm; use crate::jwk::Jwk; use crate::wire::{self, Alg, Claims, Header, Typ}; +use crate::{Htm, htu, unix_now}; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::{Signature, VerifyingKey}; use sha2::{Digest, Sha256}; -use std::time::{SystemTime, UNIX_EPOCH}; pub trait DpopSigner { type Error: std::error::Error; @@ -18,6 +17,7 @@ pub trait DpopSigner { pub struct ProofRequest<'a> { pub htm: Htm, + /// The request URL. Query and fragment are dropped before it goes into the proof. pub htu: &'a str, pub access_token: Option<&'a str>, pub nonce: Option<&'a str>, @@ -37,6 +37,7 @@ impl DpopProver { typ: Typ::DpopJwt, alg: Alg::Es256, jwk, + crit: None, }); Self { @@ -52,7 +53,6 @@ impl DpopProver { pub fn proof(&self, req: &ProofRequest<'_>) -> Result> { self.proof_at(req, unix_now(), &random_jti()?) - .map_err(DpopError::Signer) } pub(crate) fn proof_at( @@ -60,11 +60,11 @@ impl DpopProver { req: &ProofRequest<'_>, iat: u64, jti: &str, - ) -> Result { + ) -> Result> { let claims = Claims { jti: jti.to_owned(), htm: req.htm, - htu: req.htu.to_owned(), + htu: htu::canonical(req.htu).ok_or(DpopError::Htu)?, iat, ath: req .access_token @@ -74,7 +74,10 @@ impl DpopProver { let input = format!("{}.{}", self.encoded_header, wire::encode(&claims)); - let sig = self.signer.sign(input.as_bytes())?; + let sig = self + .signer + .sign(input.as_bytes()) + .map_err(DpopError::Signer)?; Ok(format!( "{input}.{}", URL_SAFE_NO_PAD.encode(sig.to_bytes()) @@ -88,6 +91,8 @@ pub enum DpopError { Signer(#[source] E), #[error("random number generator failed")] Rng(#[from] getrandom::Error), + #[error("htu is not an absolute URI")] + Htu, } fn random_jti() -> Result> { @@ -96,17 +101,9 @@ fn random_jti() -> Result> { Ok(URL_SAFE_NO_PAD.encode(buf)) } -fn unix_now() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system clock is set before the Unix epoch") - .as_secs() -} - #[cfg(test)] mod tests { use super::*; - use crate::Htm; use crate::testing::TestSigner; use p256::ecdsa::signature::Verifier; use serde_json::Value; @@ -195,6 +192,29 @@ mod tests { assert_eq!(parts.claims["iat"], 1_700_000_000); } + #[test] + fn htu_drops_query_and_fragment() { + let dpop = DpopProver::new(TestSigner::new()); + let req = ProofRequest { + htu: "HTTPS://Sync.Example:443/api/v1/items?page=2#top", + ..request(None, None) + }; + let parts = split(&dpop.proof_at(&req, 0, "jti").unwrap()); + + assert_eq!(parts.claims["htu"], HTU); + } + + #[test] + fn rejects_relative_htu() { + let dpop = DpopProver::new(TestSigner::new()); + let req = ProofRequest { + htu: "/api/v1/items", + ..request(None, None) + }; + + assert!(matches!(dpop.proof_at(&req, 0, "jti"), Err(DpopError::Htu))); + } + #[test] fn optional_claims_are_omitted_when_absent() { let dpop = DpopProver::new(TestSigner::new()); diff --git a/rust/crates/keygo-dpop/src/seen_jtis.rs b/rust/crates/keygo-dpop/src/seen_jtis.rs new file mode 100644 index 000000000..f1309e1b1 --- /dev/null +++ b/rust/crates/keygo-dpop/src/seen_jtis.rs @@ -0,0 +1,105 @@ +use moka::Expiry; +use moka::sync::Cache; +use sha2::{Digest, Sha256}; +use std::time::{Duration, Instant}; + +const MAX_ENTRIES: u64 = 100_000; + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Record { + New, + Replay, + Full, +} + +/// Every `jti` accepted within its proof's acceptance span. Entries are never evicted +/// early: a dropped `jti` could be replayed, so a full cache refuses new proofs instead. +pub(crate) struct SeenJtis(Cache<[u8; 32], Duration>); + +struct EntryTtl; + +impl Expiry<[u8; 32], Duration> for EntryTtl { + fn expire_after_create(&self, _: &[u8; 32], ttl: &Duration, _: Instant) -> Option { + Some(*ttl) + } +} + +impl SeenJtis { + pub(crate) fn new() -> Self { + Self(Cache::builder().expire_after(EntryTtl).build()) + } + + pub(crate) fn record(&self, jkt: &[u8; 32], jti: &str, ttl: Duration) -> Record { + let key: [u8; 32] = Sha256::new() + .chain_update(jkt) + .chain_update(jti) + .finalize() + .into(); + + if self.0.contains_key(&key) { + return Record::Replay; + } + if self.0.entry_count() >= MAX_ENTRIES { + return Record::Full; + } + + if self.0.entry(key).or_insert(ttl).is_fresh() { + Record::New + } else { + Record::Replay + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TTL: Duration = Duration::from_mins(2); + + #[test] + fn a_jti_is_accepted_once() { + let seen = SeenJtis::new(); + + assert_eq!(seen.record(&[1; 32], "jti", TTL), Record::New); + assert_eq!(seen.record(&[1; 32], "jti", TTL), Record::Replay); + } + + #[test] + fn jtis_are_scoped_to_the_key() { + let seen = SeenJtis::new(); + + assert_eq!(seen.record(&[1; 32], "jti", TTL), Record::New); + assert_eq!(seen.record(&[2; 32], "jti", TTL), Record::New); + } + + #[test] + fn concurrent_copies_are_accepted_once() { + let seen = SeenJtis::new(); + + let accepted = std::thread::scope(|scope| { + let handles: Vec<_> = (0..8) + .map(|_| scope.spawn(|| seen.record(&[1; 32], "jti", TTL) == Record::New)) + .collect(); + handles + .into_iter() + .map(|handle| handle.join().unwrap()) + .filter(|&accepted| accepted) + .count() + }); + + assert_eq!(accepted, 1); + } + + #[test] + fn a_jti_can_be_reused_after_its_ttl() { + let seen = SeenJtis::new(); + seen.record(&[1; 32], "jti", Duration::from_millis(10)); + std::thread::sleep(Duration::from_millis(50)); + + assert_eq!( + seen.record(&[1; 32], "jti", Duration::from_millis(10)), + Record::New + ); + } +} diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index a493c4a4f..ed1567fe6 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -1,80 +1,177 @@ +use crate::nonce::{Nonce, NonceKey}; +use crate::seen_jtis::{Record, SeenJtis}; use crate::wire::{Claims, Header}; -use crate::{Htm, jwk, wire}; +use crate::{Htm, htu, jwk, unix_now, wire}; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::Signature; use p256::ecdsa::signature::Verifier; use sha2::{Digest, Sha256}; +use std::time::Duration; use thiserror::Error; pub struct Expected<'a> { pub htm: Htm, pub htu: &'a str, pub access_token: Option<&'a str>, + /// The session's bound key. `None` on the token-issuing `*/finish` endpoints, where the proof's + /// key becomes the bound one. + pub jkt: Option<&'a [u8; 32]>, } -pub struct VerifiedProof { - pub jkt: [u8; 32], - pub jti: String, - pub iat: u64, +/// What went wrong, grouped by how the server answers (spec §10, §15). The 400/401 split is the +/// endpoint's, not the error's: token-issuing endpoints answer 400, everything else 401 with a +/// `WWW-Authenticate: DPoP` challenge. +#[derive(Debug, Error)] +pub enum VerifyError { + /// Answer `invalid_dpop_proof`. The reason is for logs only; the client reacts to every one + /// the same way. + #[error("invalid dpop proof: {0}")] + Invalid(#[from] InvalidProof), + /// Answer `use_dpop_nonce` and send this nonce in the `DPoP-Nonce` header. + #[error("dpop nonce required")] + UseNonce(Nonce), + /// The replay cache is full. Answer `429 rate_limited`: the proof itself may be fine. + #[error("too many recent proofs")] + Busy, } #[derive(Debug, Error)] -pub enum VerifyError { - #[error("proof malformed")] +pub enum InvalidProof { + #[error("not a compact JWS")] Malformed, #[error(transparent)] - DecodeError(#[from] wire::DecodeError), + Decode(#[from] wire::DecodeError), + #[error("header lists critical extensions")] + Critical, #[error(transparent)] - JwkError(#[from] jwk::JwkError), - #[error("Signature verification failed")] + Jwk(#[from] jwk::JwkError), + #[error("signature does not verify")] Signature, - #[error("invalid request")] + #[error("htm or htu does not match the request")] Request, - #[error("invalid access token")] + #[error("ath does not match the access token")] AccessTokenHash, + #[error("proof key is not the bound key")] + KeyMismatch, + #[error("jti already used")] + Replay, +} + +impl From for VerifyError { + fn from(e: wire::DecodeError) -> Self { + InvalidProof::from(e).into() + } +} + +impl From for VerifyError { + fn from(e: jwk::JwkError) -> Self { + InvalidProof::from(e).into() + } } type VerifyResult = Result; -pub fn verify(proof: &str, expected: Expected) -> VerifyResult { - let (input, sign) = proof.rsplit_once('.').ok_or(VerifyError::Malformed)?; - let (header, claims) = input.split_once('.').ok_or(VerifyError::Malformed)?; +const IAT_WINDOW: u64 = 60; +/// A proof without a nonce is accepted while the server's clock is within `IAT_WINDOW` of its +/// `iat`, so its `jti` must be remembered for the whole span. +const JTI_TTL: u64 = 2 * IAT_WINDOW; - let header = wire::decode::
(header)?; - let key = header.jwk.verifying_key()?; - let sign = URL_SAFE_NO_PAD - .decode(sign) - .map_err(|_| VerifyError::Signature)?; - let sign = Signature::from_slice(&sign).map_err(|_| VerifyError::Signature)?; - key.verify(input.as_bytes(), &sign) - .map_err(|_| VerifyError::Signature)?; +pub struct DpopVerifier { + nonce_key: NonceKey, + started_at: u64, + seen_jtis: SeenJtis, +} - let Claims { - jti, - htm, - htu, - iat, - ath, - nonce: _, - } = wire::decode(claims)?; +impl DpopVerifier { + pub fn new(nonce_key: NonceKey) -> Self { + Self::started_at(nonce_key, unix_now()) + } - if htm != expected.htm || htu != expected.htu { - return Err(VerifyError::Request); + pub(crate) fn started_at(nonce_key: NonceKey, started_at: u64) -> Self { + Self { + nonce_key, + started_at, + seen_jtis: SeenJtis::new(), + } + } + + pub fn verify(&self, proof: &str, expected: Expected) -> VerifyResult<[u8; 32]> { + self.verify_at(proof, expected, unix_now()) } - let expected_ath = expected - .access_token - .map(|t| URL_SAFE_NO_PAD.encode(Sha256::digest(t))); - if ath != expected_ath { - return Err(VerifyError::AccessTokenHash); + fn verify_at(&self, proof: &str, expected: Expected, now: u64) -> VerifyResult<[u8; 32]> { + let (input, sign) = proof.rsplit_once('.').ok_or(InvalidProof::Malformed)?; + let (header, claims) = input.split_once('.').ok_or(InvalidProof::Malformed)?; + + // Alg + Typ allowlist is checked during wire::decode, as they are typed enums + let header = wire::decode::
(header)?; + if header.crit.is_some() { + return Err(InvalidProof::Critical.into()); + } + verify_signature(input, &header, sign)?; + + let Claims { + jti, + htm, + htu, + iat, + ath, + nonce, + } = wire::decode(claims)?; + + if htm != expected.htm || !htu::matches(&htu, expected.htu) { + return Err(InvalidProof::Request.into()); + } + + let expected_ath = expected + .access_token + .map(|t| URL_SAFE_NO_PAD.encode(Sha256::digest(t))); + if ath != expected_ath { + return Err(InvalidProof::AccessTokenHash.into()); + } + + let jkt = header.jwk.thumbprint(); + if expected.jkt.is_some_and(|bound| bound != &jkt) { + return Err(InvalidProof::KeyMismatch.into()); + } + + // A proof with a nonce is judged by the nonce alone, one without by its `iat` (spec §10). + // Neither may predate the start: the `jti`s seen before it are gone. + let jti_ttl = match nonce { + Some(nonce) => self + .nonce_key + .open(&nonce) + .filter(|nonce| nonce.created_at() >= self.started_at && now <= nonce.expires_at()) + .map(|nonce| JTI_TTL.max(nonce.expires_at() - now)), + None => (now.abs_diff(iat) <= IAT_WINDOW && iat >= self.started_at + IAT_WINDOW) + .then_some(JTI_TTL), + }; + let Some(jti_ttl) = jti_ttl else { + return Err(VerifyError::UseNonce(self.nonce_key.issue(now))); + }; + + // Recorded last: a proof that fails any check above never takes an entry (spec §10). + match self + .seen_jtis + .record(&jkt, &jti, Duration::from_secs(jti_ttl)) + { + Record::New => Ok(jkt), + Record::Replay => Err(InvalidProof::Replay.into()), + Record::Full => Err(VerifyError::Busy), + } } +} - Ok(VerifiedProof { - jkt: header.jwk.thumbprint(), - jti, - iat, - }) +fn verify_signature(input: &str, header: &Header, sign: &str) -> Result<(), InvalidProof> { + let key = header.jwk.verifying_key()?; + let sign = URL_SAFE_NO_PAD + .decode(sign) + .map_err(|_| InvalidProof::Signature)?; + let sign = Signature::from_slice(&sign).map_err(|_| InvalidProof::Signature)?; + key.verify(input.as_bytes(), &sign) + .map_err(|_| InvalidProof::Signature)?; + Ok(()) } #[cfg(test)] @@ -85,24 +182,48 @@ mod tests { const HTU: &str = "https://sync.example/api/v1/items"; const NOW: u64 = 1_700_000_000; + const WINDOW: u64 = IAT_WINDOW; + const NONCE_LIFETIME: u64 = 5 * 60; + + fn verifier_started_at(started_at: u64) -> DpopVerifier { + DpopVerifier::started_at(NonceKey::new([3; 32]), started_at) + } + + /// Verifies at `NOW` against a server that has been up long enough to accept nonce-less proofs. + fn verify(proof: &str, expected: Expected) -> VerifyResult<[u8; 32]> { + verifier_started_at(NOW - WINDOW).verify_at(proof, expected, NOW) + } fn proof(iat: u64, access_token: Option<&str>) -> String { + proof_with_nonce(iat, access_token, None) + } + + fn proof_with_nonce(iat: u64, access_token: Option<&str>, nonce: Option<&str>) -> String { let req = ProofRequest { htm: Htm::Post, htu: HTU, access_token, - nonce: None, + nonce, }; DpopProver::new(TestSigner::new()) .proof_at(&req, iat, "jti") .unwrap() } + fn required_nonce(result: VerifyResult<[u8; 32]>) -> Nonce { + match result { + Err(VerifyError::UseNonce(nonce)) => nonce, + Err(e) => panic!("expected a nonce challenge, got {e:?}"), + Ok(_) => panic!("expected a nonce challenge, got a verified proof"), + } + } + fn expected(access_token: Option<&str>) -> Expected<'_> { Expected { htm: Htm::Post, htu: HTU, access_token, + jkt: None, } } @@ -115,11 +236,9 @@ mod tests { #[test] fn accepts_own_proof() { - let verified = verify(&proof(NOW, None), expected(None)).unwrap(); + let jkt = verify(&proof(NOW, None), expected(None)).unwrap(); - assert_eq!(&verified.jkt, DpopProver::new(TestSigner::new()).jkt()); - assert_eq!(verified.jti, "jti"); - assert_eq!(verified.iat, NOW); + assert_eq!(&jkt, DpopProver::new(TestSigner::new()).jkt()); } #[test] @@ -131,21 +250,30 @@ mod tests { fn rejects_wrong_access_token() { let result = verify(&proof(NOW, Some("token")), expected(Some("other"))); - assert!(matches!(result, Err(VerifyError::AccessTokenHash))); + assert!(matches!( + result, + Err(VerifyError::Invalid(InvalidProof::AccessTokenHash)) + )); } #[test] fn rejects_missing_ath_when_token_present() { let result = verify(&proof(NOW, None), expected(Some("token"))); - assert!(matches!(result, Err(VerifyError::AccessTokenHash))); + assert!(matches!( + result, + Err(VerifyError::Invalid(InvalidProof::AccessTokenHash)) + )); } #[test] fn rejects_unexpected_ath() { let result = verify(&proof(NOW, Some("token")), expected(None)); - assert!(matches!(result, Err(VerifyError::AccessTokenHash))); + assert!(matches!( + result, + Err(VerifyError::Invalid(InvalidProof::AccessTokenHash)) + )); } #[test] @@ -157,11 +285,11 @@ mod tests { assert!(matches!( verify(&proof(NOW, None), wrong_htm), - Err(VerifyError::Request) + Err(VerifyError::Invalid(InvalidProof::Request)) )); assert!(matches!( verify(&proof(NOW, None), wrong_htu), - Err(VerifyError::Request) + Err(VerifyError::Invalid(InvalidProof::Request)) )); } @@ -173,7 +301,7 @@ mod tests { assert!(matches!( verify(&tampered, expected(None)), - Err(VerifyError::Signature) + Err(VerifyError::Invalid(InvalidProof::Signature)) )); } @@ -196,7 +324,7 @@ mod tests { assert!(matches!( verify(&forged, expected(None)), - Err(VerifyError::Signature) + Err(VerifyError::Invalid(InvalidProof::Signature)) )); } @@ -211,7 +339,9 @@ mod tests { assert!(matches!( verify(&leaked, expected(None)), - Err(VerifyError::JwkError(jwk::JwkError::PrivateKey)), + Err(VerifyError::Invalid(InvalidProof::Jwk( + jwk::JwkError::PrivateKey + ))), )); } @@ -226,7 +356,9 @@ mod tests { assert!(matches!( verify(&broken, expected(None)), - Err(VerifyError::JwkError(jwk::JwkError::Base64(_))), + Err(VerifyError::Invalid(InvalidProof::Jwk( + jwk::JwkError::Base64(_) + ))), )); } @@ -234,11 +366,172 @@ mod tests { fn rejects_missing_segments() { assert!(matches!( verify("abc", expected(None)), - Err(VerifyError::Malformed) + Err(VerifyError::Invalid(InvalidProof::Malformed)) )); assert!(matches!( verify("abc.def", expected(None)), - Err(VerifyError::Malformed) + Err(VerifyError::Invalid(InvalidProof::Malformed)) + )); + } + + #[test] + fn rejects_crit_header() { + let header = proof(NOW, None).split('.').next().unwrap().to_owned(); + let mut json: serde_json::Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header).unwrap()).unwrap(); + json["crit"] = serde_json::json!(["exp"]); + let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json).unwrap()); + let critical = replace_segment(&proof(NOW, None), 0, &header); + + assert!(matches!( + verify(&critical, expected(None)), + Err(VerifyError::Invalid(InvalidProof::Critical)) + )); + } + + #[test] + fn requires_nonce_until_a_window_after_start() { + let verifier = verifier_started_at(NOW); + + required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)); + required_nonce(verifier.verify_at( + &proof(NOW + WINDOW - 1, None), + expected(None), + NOW + WINDOW - 1, + )); + assert!( + verifier + .verify_at(&proof(NOW + WINDOW, None), expected(None), NOW + WINDOW) + .is_ok() + ); + } + + #[test] + fn requires_nonce_for_iat_outside_window() { + let verifier = verifier_started_at(NOW - 10 * WINDOW); + + required_nonce(verifier.verify_at(&proof(NOW - WINDOW - 1, None), expected(None), NOW)); + required_nonce(verifier.verify_at(&proof(NOW + WINDOW + 1, None), expected(None), NOW)); + } + + #[test] + fn accepts_iat_at_window_edges() { + // One verifier per proof: both carry the same jti. + for iat in [NOW - WINDOW, NOW + WINDOW] { + let verifier = verifier_started_at(NOW - 10 * WINDOW); + + assert!( + verifier + .verify_at(&proof(iat, None), expected(None), NOW) + .is_ok() + ); + } + } + + #[test] + fn accepts_proof_carrying_issued_nonce() { + let verifier = verifier_started_at(NOW); + let nonce = required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)); + + // The nonce replaces the iat check, so even a broken client clock passes. + let proof = proof_with_nonce(0, None, Some(&nonce.to_string())); + assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + } + + #[test] + fn accepts_nonce_until_it_expires() { + let verifier = verifier_started_at(NOW); + let nonce = + required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)).to_string(); + let proof = |iat| proof_with_nonce(iat, None, Some(&nonce)); + let expires_at = NOW + NONCE_LIFETIME; + + assert!( + verifier + .verify_at(&proof(1), expected(None), expires_at) + .is_ok() + ); + required_nonce(verifier.verify_at(&proof(2), expected(None), expires_at + 1)); + } + + #[test] + fn rejects_nonce_from_previous_run() { + let previous = verifier_started_at(NOW); + let nonce = required_nonce(previous.verify_at(&proof(NOW, None), expected(None), NOW)); + let restarted = verifier_started_at(NOW + 1); + + required_nonce(restarted.verify_at( + &proof_with_nonce(NOW, None, Some(&nonce.to_string())), + expected(None), + NOW + 1, + )); + } + + #[test] + fn rejects_forged_nonce() { + let verifier = verifier_started_at(NOW); + + required_nonce(verifier.verify_at( + &proof_with_nonce(NOW, None, Some("forged")), + expected(None), + NOW, + )); + } + + #[test] + fn accepts_proof_from_bound_key() { + let jkt = *DpopProver::new(TestSigner::new()).jkt(); + let mut bound = expected(None); + bound.jkt = Some(&jkt); + + assert!(verify(&proof(NOW, None), bound).is_ok()); + } + + #[test] + fn rejects_proof_from_other_than_bound_key() { + let mut bound = expected(None); + bound.jkt = Some(&[0; 32]); + + assert!(matches!( + verify(&proof(NOW, None), bound), + Err(VerifyError::Invalid(InvalidProof::KeyMismatch)) + )); + } + + #[test] + fn rejects_replayed_proof() { + let verifier = verifier_started_at(NOW - WINDOW); + let proof = proof(NOW, None); + + assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + assert!(matches!( + verifier.verify_at(&proof, expected(None), NOW), + Err(VerifyError::Invalid(InvalidProof::Replay)) + )); + } + + #[test] + fn rejects_replayed_proof_carrying_nonce() { + let verifier = verifier_started_at(NOW); + let nonce = required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)); + let proof = proof_with_nonce(NOW, None, Some(&nonce.to_string())); + + assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + assert!(matches!( + verifier.verify_at(&proof, expected(None), NOW), + Err(VerifyError::Invalid(InvalidProof::Replay)) + )); + } + + #[test] + fn rejected_proof_does_not_take_its_jti() { + let verifier = verifier_started_at(NOW - WINDOW); + let proof = proof(NOW, None); + + assert!(matches!( + verifier.verify_at(&proof, expected(Some("token")), NOW), + Err(VerifyError::Invalid(InvalidProof::AccessTokenHash)) )); + assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); } } diff --git a/rust/crates/keygo-dpop/src/wire.rs b/rust/crates/keygo-dpop/src/wire.rs index f2a17c406..b4cb79cf3 100644 --- a/rust/crates/keygo-dpop/src/wire.rs +++ b/rust/crates/keygo-dpop/src/wire.rs @@ -1,7 +1,7 @@ use crate::jwk::Jwk; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use serde::de::DeserializeOwned; +use serde::de::{DeserializeOwned, IgnoredAny}; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -10,6 +10,11 @@ pub(crate) struct Header { pub(crate) typ: Typ, pub(crate) alg: Alg, pub(crate) jwk: Jwk, + + // RFC 7515 §4.1.11: extensions listed in `crit` must be understood. This verifier understands + // none, so only read it to reject it; never serialized. + #[serde(default, skip_serializing)] + pub(crate) crit: Option, } #[derive(Serialize, Deserialize)] @@ -105,6 +110,17 @@ mod tests { assert!(serde_json::from_str::
(&json).is_err()); } + #[test] + fn header_reads_crit() { + let json = format!( + r#"{{"typ":"dpop+jwt","alg":"ES256","jwk":{},"crit":["exp"]}}"#, + jwk_json() + ); + let header: Header = serde_json::from_str(&json).unwrap(); + + assert!(header.crit.is_some()); + } + #[test] fn claims_accept_escaped_strings() { let json = r#"{"jti":"j","htm":"GET","htu":"https:\/\/sync.example\/x","iat":1}"#; From b5b072da9a2685584cce68608ceefb44094dd846 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 22 Oct 2026 14:30:00 +0200 Subject: [PATCH 04/26] refactor(dpop): move to hashmap to drop moka --- rust/Cargo.lock | 1 - rust/crates/keygo-dpop/Cargo.toml | 1 - rust/crates/keygo-dpop/src/seen_jtis.rs | 134 ++++++++++++++++++------ rust/crates/keygo-dpop/src/verify.rs | 46 +++++--- 4 files changed, 132 insertions(+), 50 deletions(-) diff --git a/rust/Cargo.lock b/rust/Cargo.lock index bdc26ce42..1d45da826 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1631,7 +1631,6 @@ dependencies = [ "fluent-uri", "getrandom 0.4.3", "hmac 0.13.0", - "moka", "p256", "serde", "serde_json", diff --git a/rust/crates/keygo-dpop/Cargo.toml b/rust/crates/keygo-dpop/Cargo.toml index d35d987fd..cf300b53b 100644 --- a/rust/crates/keygo-dpop/Cargo.toml +++ b/rust/crates/keygo-dpop/Cargo.toml @@ -10,7 +10,6 @@ base64.workspace = true fluent-uri = "0.4.1" hmac = "0.13.0" -moka = { version = "0.12.16", features = ["sync"] } p256 = { version = "0.14.0", default-features = false, features = ["ecdsa", "getrandom"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" diff --git a/rust/crates/keygo-dpop/src/seen_jtis.rs b/rust/crates/keygo-dpop/src/seen_jtis.rs index f1309e1b1..b8b73d834 100644 --- a/rust/crates/keygo-dpop/src/seen_jtis.rs +++ b/rust/crates/keygo-dpop/src/seen_jtis.rs @@ -1,9 +1,8 @@ -use moka::Expiry; -use moka::sync::Cache; use sha2::{Digest, Sha256}; -use std::time::{Duration, Instant}; +use std::collections::HashMap; +use std::sync::{Mutex, PoisonError}; -const MAX_ENTRIES: u64 = 100_000; +const CAPACITY: usize = 100_000; #[derive(Debug, PartialEq, Eq)] pub(crate) enum Record { @@ -12,42 +11,81 @@ pub(crate) enum Record { Full, } -/// Every `jti` accepted within its proof's acceptance span. Entries are never evicted -/// early: a dropped `jti` could be replayed, so a full cache refuses new proofs instead. -pub(crate) struct SeenJtis(Cache<[u8; 32], Duration>); - -struct EntryTtl; +/// The `jti` of every accepted proof, kept until that proof could no longer be accepted. +/// +/// Entries are never dropped early: a dropped `jti` could be replayed, so a full store refuses new +/// proofs instead. Deadlines are seconds on the clock the verifier judges proofs by, so a clock +/// step cannot expire an entry while its proof is still acceptable. +pub(crate) struct SeenJtis { + capacity: usize, + state: Mutex, +} -impl Expiry<[u8; 32], Duration> for EntryTtl { - fn expire_after_create(&self, _: &[u8; 32], ttl: &Duration, _: Instant) -> Option { - Some(*ttl) - } +struct State { + /// SHA-256(`jkt` ‖ `jti`) → the last second at which its proof can be accepted. + deadlines: HashMap<[u8; 32], u64>, + /// No entry expires before this second. A lower bound: it is exact again after every sweep. + earliest_deadline: u64, } impl SeenJtis { pub(crate) fn new() -> Self { - Self(Cache::builder().expire_after(EntryTtl).build()) + Self::with_capacity(CAPACITY) } - pub(crate) fn record(&self, jkt: &[u8; 32], jti: &str, ttl: Duration) -> Record { + pub(crate) fn with_capacity(capacity: usize) -> Self { + Self { + capacity, + state: Mutex::new(State { + deadlines: HashMap::with_capacity(capacity), + earliest_deadline: u64::MAX, + }), + } + } + + pub(crate) fn record(&self, jkt: &[u8; 32], jti: &str, deadline: u64, now: u64) -> Record { + debug_assert!(deadline >= now, "the proof is acceptable now"); + let key: [u8; 32] = Sha256::new() .chain_update(jkt) .chain_update(jti) .finalize() .into(); - if self.0.contains_key(&key) { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + + // An expired entry counts as absent: correctness never waits for a sweep. + if state.deadlines.get(&key).is_some_and(|&d| d >= now) { return Record::Replay; } - if self.0.entry_count() >= MAX_ENTRIES { - return Record::Full; + if state.deadlines.len() >= self.capacity { + state.remove_expired(now); + if state.deadlines.len() >= self.capacity { + return Record::Full; + } } - if self.0.entry(key).or_insert(ttl).is_fresh() { - Record::New - } else { - Record::Replay + state.deadlines.insert(key, deadline); + state.earliest_deadline = state.earliest_deadline.min(deadline); + Record::New + } +} + +impl State { + fn remove_expired(&mut self, now: u64) { + if self.earliest_deadline >= now { + return; } + + let mut earliest = u64::MAX; + self.deadlines.retain(|_, &mut deadline| { + let live = deadline >= now; + if live { + earliest = earliest.min(deadline); + } + live + }); + self.earliest_deadline = earliest; } } @@ -55,22 +93,23 @@ impl SeenJtis { mod tests { use super::*; - const TTL: Duration = Duration::from_mins(2); + const NOW: u64 = 1_700_000_000; + const KEY: [u8; 32] = [1; 32]; #[test] fn a_jti_is_accepted_once() { let seen = SeenJtis::new(); - assert_eq!(seen.record(&[1; 32], "jti", TTL), Record::New); - assert_eq!(seen.record(&[1; 32], "jti", TTL), Record::Replay); + assert_eq!(seen.record(&KEY, "jti", NOW, NOW), Record::New); + assert_eq!(seen.record(&KEY, "jti", NOW, NOW), Record::Replay); } #[test] fn jtis_are_scoped_to_the_key() { let seen = SeenJtis::new(); - assert_eq!(seen.record(&[1; 32], "jti", TTL), Record::New); - assert_eq!(seen.record(&[2; 32], "jti", TTL), Record::New); + assert_eq!(seen.record(&[1; 32], "jti", NOW, NOW), Record::New); + assert_eq!(seen.record(&[2; 32], "jti", NOW, NOW), Record::New); } #[test] @@ -79,7 +118,7 @@ mod tests { let accepted = std::thread::scope(|scope| { let handles: Vec<_> = (0..8) - .map(|_| scope.spawn(|| seen.record(&[1; 32], "jti", TTL) == Record::New)) + .map(|_| scope.spawn(|| seen.record(&KEY, "jti", NOW, NOW) == Record::New)) .collect(); handles .into_iter() @@ -92,14 +131,43 @@ mod tests { } #[test] - fn a_jti_can_be_reused_after_its_ttl() { + fn a_jti_is_kept_until_its_deadline() { let seen = SeenJtis::new(); - seen.record(&[1; 32], "jti", Duration::from_millis(10)); - std::thread::sleep(Duration::from_millis(50)); + seen.record(&KEY, "jti", NOW + 60, NOW); + assert_eq!(seen.record(&KEY, "jti", NOW + 60, NOW + 60), Record::Replay); + assert_eq!(seen.record(&KEY, "jti", NOW + 61, NOW + 61), Record::New); + } + + #[test] + fn a_full_store_refuses_new_jtis() { + let seen = SeenJtis::with_capacity(2); + seen.record(&KEY, "a", NOW, NOW); + seen.record(&KEY, "b", NOW, NOW); + + assert_eq!(seen.record(&KEY, "c", NOW, NOW), Record::Full); + assert_eq!(seen.record(&KEY, "a", NOW, NOW), Record::Replay); + } + + #[test] + fn a_full_store_makes_room_once_entries_expire() { + let seen = SeenJtis::with_capacity(1); + seen.record(&KEY, "a", NOW, NOW); + + assert_eq!(seen.record(&KEY, "b", NOW, NOW), Record::Full); + assert_eq!(seen.record(&KEY, "b", NOW + 1, NOW + 1), Record::New); + } + + #[test] + fn making_room_keeps_live_entries() { + let seen = SeenJtis::with_capacity(2); + seen.record(&KEY, "long", NOW + 100, NOW); + seen.record(&KEY, "short", NOW + 1, NOW); + + assert_eq!(seen.record(&KEY, "new", NOW + 2, NOW + 2), Record::New); assert_eq!( - seen.record(&[1; 32], "jti", Duration::from_millis(10)), - Record::New + seen.record(&KEY, "long", NOW + 100, NOW + 2), + Record::Replay ); } } diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index ed1567fe6..fc857934a 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -7,7 +7,6 @@ use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::Signature; use p256::ecdsa::signature::Verifier; use sha2::{Digest, Sha256}; -use std::time::Duration; use thiserror::Error; pub struct Expected<'a> { @@ -73,9 +72,6 @@ impl From for VerifyError { type VerifyResult = Result; const IAT_WINDOW: u64 = 60; -/// A proof without a nonce is accepted while the server's clock is within `IAT_WINDOW` of its -/// `iat`, so its `jti` must be remembered for the whole span. -const JTI_TTL: u64 = 2 * IAT_WINDOW; pub struct DpopVerifier { nonce_key: NonceKey, @@ -136,26 +132,20 @@ impl DpopVerifier { return Err(InvalidProof::KeyMismatch.into()); } - // A proof with a nonce is judged by the nonce alone, one without by its `iat` (spec §10). - // Neither may predate the start: the `jti`s seen before it are gone. - let jti_ttl = match nonce { + let deadline = match nonce { Some(nonce) => self .nonce_key .open(&nonce) .filter(|nonce| nonce.created_at() >= self.started_at && now <= nonce.expires_at()) - .map(|nonce| JTI_TTL.max(nonce.expires_at() - now)), + .map(|nonce| nonce.expires_at()), None => (now.abs_diff(iat) <= IAT_WINDOW && iat >= self.started_at + IAT_WINDOW) - .then_some(JTI_TTL), + .then(|| iat + IAT_WINDOW), }; - let Some(jti_ttl) = jti_ttl else { + let Some(deadline) = deadline else { return Err(VerifyError::UseNonce(self.nonce_key.issue(now))); }; - // Recorded last: a proof that fails any check above never takes an entry (spec §10). - match self - .seen_jtis - .record(&jkt, &jti, Duration::from_secs(jti_ttl)) - { + match self.seen_jtis.record(&jkt, &jti, deadline, now) { Record::New => Ok(jkt), Record::Replay => Err(InvalidProof::Replay.into()), Record::Full => Err(VerifyError::Busy), @@ -523,6 +513,32 @@ mod tests { )); } + #[test] + fn replay_is_refused_for_as_long_as_the_proof_is_acceptable() { + let verifier = verifier_started_at(NOW - WINDOW); + let proof = proof(NOW, None); + verifier.verify_at(&proof, expected(None), NOW).unwrap(); + + assert!(matches!( + verifier.verify_at(&proof, expected(None), NOW + WINDOW), + Err(VerifyError::Invalid(InvalidProof::Replay)) + )); + required_nonce(verifier.verify_at(&proof, expected(None), NOW + WINDOW + 1)); + } + + #[test] + fn full_replay_store_is_busy() { + let verifier = DpopVerifier { + seen_jtis: SeenJtis::with_capacity(0), + ..verifier_started_at(NOW - WINDOW) + }; + + assert!(matches!( + verifier.verify_at(&proof(NOW, None), expected(None), NOW), + Err(VerifyError::Busy) + )); + } + #[test] fn rejected_proof_does_not_take_its_jti() { let verifier = verifier_started_at(NOW - WINDOW); From 3ccc7072aac8ebb13b4e92fc2fb65bce90dfc22d Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 22 Oct 2026 14:47:46 +0200 Subject: [PATCH 05/26] feat(api): add dpop crate --- rust/Cargo.lock | 1 + rust/crates/keygo-server/Cargo.toml | 2 + rust/crates/keygo-server/src/api/mod.rs | 3 ++ .../src/api/routes/auth/register.rs | 1 - rust/crates/keygo-server/src/api/state.rs | 3 ++ rust/crates/keygo-server/src/config.rs | 7 +++- rust/crates/keygo-server/src/secrets.rs | 37 ++++++++++++++++--- rust/crates/keygo-server/src/testing.rs | 3 ++ 8 files changed, 49 insertions(+), 8 deletions(-) diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 1d45da826..e6a14a322 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1669,6 +1669,7 @@ dependencies = [ "hmac 0.13.0", "http-body-util", "humantime", + "keygo-dpop", "keygo-opaque", "moka", "secrecy", diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 9d839fcaa..da5313714 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -6,6 +6,8 @@ edition.workspace = true [dependencies] keygo-opaque = { path = "../keygo-opaque" } +keygo-dpop = { path = "../keygo-dpop" } + zeroize.workspace = true thiserror.workspace = true base64.workspace = true diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 901095bc0..4fcbd6d3b 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -38,6 +38,8 @@ mod tests { use axum::body::Body; use axum::http::{Request, StatusCode}; use http_body_util::BodyExt; + use keygo_dpop::NonceKey; + use keygo_dpop::verify::DpopVerifier; use routes::auth::MAX_BODY_BYTES; use serde_json::{Value, json}; use std::sync::Arc; @@ -70,6 +72,7 @@ mod tests { db: sqlx::postgres::PgPoolOptions::new() .connect_lazy_with(sqlx::postgres::PgConnectOptions::new()), login_states: LoginStates::new(), + dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new([0; 32]))), } } diff --git a/rust/crates/keygo-server/src/api/routes/auth/register.rs b/rust/crates/keygo-server/src/api/routes/auth/register.rs index 7aef518da..368f51fcc 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/register.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/register.rs @@ -98,7 +98,6 @@ async fn finish( let finished = registration::finish(&state.db, input).await?; - // 201 is the client's commit point (§8): only then does it write anything locally. Ok(( StatusCode::CREATED, Json(FinishResponse { diff --git a/rust/crates/keygo-server/src/api/state.rs b/rust/crates/keygo-server/src/api/state.rs index 1c1c86c4f..b40930cab 100644 --- a/rust/crates/keygo-server/src/api/state.rs +++ b/rust/crates/keygo-server/src/api/state.rs @@ -1,6 +1,7 @@ use crate::cache::LoginStates; use crate::config::DeploymentConfig; use crate::service::registration::Signup; +use keygo_dpop::verify::DpopVerifier; use sqlx::PgPool; use std::sync::Arc; @@ -10,6 +11,7 @@ pub struct AppState { pub opaque_state: keygo_opaque::server::ServerSetup, pub db: PgPool, pub login_states: LoginStates, + pub dpop_verifier: Arc, } impl AppState { @@ -24,6 +26,7 @@ impl AppState { opaque_state: secrets.opaque_setup()?, db, login_states: LoginStates::new(), + dpop_verifier: Arc::new(DpopVerifier::new(secrets.dpop_nonce_key()?)), }) } } diff --git a/rust/crates/keygo-server/src/config.rs b/rust/crates/keygo-server/src/config.rs index 7df9e11cd..b9859b1ff 100644 --- a/rust/crates/keygo-server/src/config.rs +++ b/rust/crates/keygo-server/src/config.rs @@ -1,6 +1,7 @@ use crate::domain::InvitePepper; -use crate::secrets::{DbPassword, OpaqueSetup, SecretStore}; +use crate::secrets::{DbPassword, DpopNonceKey, OpaqueSetup, SecretStore}; use clap::{Args, ValueEnum}; +use keygo_dpop::NonceKey; use keygo_opaque::server::ServerSetup; use secrecy::SecretString; use std::path::PathBuf; @@ -106,4 +107,8 @@ impl SecretsConfig { pub(crate) fn invite_pepper(&self) -> anyhow::Result { self.store().read::() } + + pub(crate) fn dpop_nonce_key(&self) -> anyhow::Result { + self.store().read::() + } } diff --git a/rust/crates/keygo-server/src/secrets.rs b/rust/crates/keygo-server/src/secrets.rs index 8cdad8e78..53fa4be39 100644 --- a/rust/crates/keygo-server/src/secrets.rs +++ b/rust/crates/keygo-server/src/secrets.rs @@ -1,5 +1,6 @@ use crate::domain::InvitePepper; use anyhow::{Context, anyhow, ensure}; +use keygo_dpop::NonceKey; use keygo_opaque::server::ServerSetup; use secrecy::{ExposeSecret, SecretString}; use std::fs::{self, DirBuilder, File, Permissions}; @@ -106,22 +107,46 @@ impl TypedSecret for InvitePepper { type Value = Self; fn generate() -> anyhow::Result { - let mut raw = Zeroizing::new([0u8; 32]); - getrandom::fill(raw.as_mut_slice()).map_err(|e| anyhow!("getrandom: {}", e))?; - Ok(hex::encode(raw.as_slice()).into()) + random_key() } fn decode(stored: &str) -> anyhow::Result { - let raw = Zeroizing::new(hex::decode(stored).context("not hex")?); - let bytes: [u8; 32] = raw.as_slice().try_into().context("not 32 bytes")?; - Ok(Self::new(bytes)) + Ok(Self::new(decode(stored)?)) } } +pub struct DpopNonceKey; + +impl TypedSecret for DpopNonceKey { + const NAME: &'static str = "dpop_nonce_key"; + type Value = NonceKey; + + fn generate() -> anyhow::Result { + random_key() + } + + fn decode(stored: &str) -> anyhow::Result { + Ok(NonceKey::new(decode(stored)?)) + } +} + +fn random_key() -> anyhow::Result { + let mut raw = Zeroizing::new([0u8; 32]); + getrandom::fill(raw.as_mut_slice()).map_err(|e| anyhow!("getrandom: {}", e))?; + Ok(hex::encode(raw.as_slice()).into()) +} + +fn decode(stored: &str) -> anyhow::Result<[u8; 32]> { + let raw = Zeroizing::new(hex::decode(stored).context("not hex")?); + let bytes = raw.as_slice().try_into().context("not 32 bytes")?; + Ok(bytes) +} + secrets! { DbPassword, OpaqueSetup, InvitePepper, + DpopNonceKey, } #[derive(Debug, PartialEq, Eq)] diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 3f789aaf4..42bcc0875 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -8,6 +8,8 @@ use crate::service::registration::{self, FinishRegistration, Signup, StartRegist use axum::body::Body; use axum::http::{Request, StatusCode}; use http_body_util::BodyExt; +use keygo_dpop::NonceKey; +use keygo_dpop::verify::DpopVerifier; use keygo_opaque::client::{ClientLogin, ClientRegistration}; use keygo_opaque::server::ServerSetup; use serde_json::Value; @@ -128,6 +130,7 @@ pub fn app_state(db: &PgPool, setup: &ServerSetup) -> AppState { opaque_state: setup.clone(), db: db.clone(), login_states: LoginStates::new(), + dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new([0; 32]))), } } pub async fn post(db: &PgPool, setup: &ServerSetup, uri: &str, body: Value) -> (StatusCode, Value) { From d063432c5fb3ad7af0eab31cb3a02d7982e4c09c Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 22 Oct 2026 21:00:19 +0200 Subject: [PATCH 06/26] feat(opaque): add dpop binding --- rust/Cargo.lock | 1 + rust/crates/keygo-opaque/Cargo.toml | 2 + rust/crates/keygo-opaque/src/dpop_binding.rs | 130 +++++++++++++++++++ rust/crates/keygo-opaque/src/keys.rs | 10 +- rust/crates/keygo-opaque/src/lib.rs | 2 + rust/crates/keygo-opaque/src/macros.rs | 32 +++++ rust/crates/keygo-opaque/src/messages.rs | 31 ----- rust/crates/keygo-opaque/tests/protocol.rs | 38 +++++- 8 files changed, 208 insertions(+), 38 deletions(-) create mode 100644 rust/crates/keygo-opaque/src/dpop_binding.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index e6a14a322..9e387e28d 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1644,6 +1644,7 @@ name = "keygo-opaque" version = "0.1.0" dependencies = [ "base64 0.23.1", + "hkdf 0.12.4", "opaque-ke", "rand_core 0.6.4", "serde", diff --git a/rust/crates/keygo-opaque/Cargo.toml b/rust/crates/keygo-opaque/Cargo.toml index cff48a988..b9cb9bd11 100644 --- a/rust/crates/keygo-opaque/Cargo.toml +++ b/rust/crates/keygo-opaque/Cargo.toml @@ -17,5 +17,7 @@ sha2 = "0.10.9" # Only to classify the OPRF errors opaque-ke passes through. voprf = { version = "0.5.0", default-features = false } +hkdf = "0.12.4" + [dev-dependencies] serde_json = "1.0.154" diff --git a/rust/crates/keygo-opaque/src/dpop_binding.rs b/rust/crates/keygo-opaque/src/dpop_binding.rs new file mode 100644 index 000000000..871745b13 --- /dev/null +++ b/rust/crates/keygo-opaque/src/dpop_binding.rs @@ -0,0 +1,130 @@ +use crate::error::{OpaqueError, OpaqueResult}; +use crate::keys::SessionKey; +use hkdf::Hkdf; +use hkdf::hmac::{Hmac, Mac}; +use sha2::Sha256; +use zeroize::Zeroizing; + +const DPOP_BINDING_LABEL: &[u8] = b"v1:bind/dpop"; + +/// `HMAC-SHA256(HKDF-SHA256(session_key, salt = "", info = "v1:bind/dpop"), jkt)`. +pub struct DpopBinding([u8; 32]); + +impl DpopBinding { + pub fn to_bytes(&self) -> [u8; 32] { + self.0 + } + + pub fn from_bytes(bytes: &[u8]) -> OpaqueResult { + Ok(Self(bytes.try_into().map_err(|_| OpaqueError::Malformed)?)) + } +} + +wire_message!(DpopBinding); + +impl SessionKey { + pub fn dpop_binding(&self, jkt: &[u8; 32]) -> DpopBinding { + DpopBinding(self.binding_mac(jkt).finalize().into_bytes().into()) + } + + pub fn verify_dpop_binding(&self, jkt: &[u8; 32], binding: &DpopBinding) -> OpaqueResult<()> { + self.binding_mac(jkt) + .verify_slice(&binding.0) + .map_err(|_| OpaqueError::InvalidLogin) + } + + fn binding_mac(&self, jkt: &[u8; 32]) -> Hmac { + let mut key = Zeroizing::new([0u8; 32]); + Hkdf::::new(None, self.as_bytes()) + .expand(DPOP_BINDING_LABEL, key.as_mut()) + .expect("32 bytes is a valid HKDF-SHA256 output length"); + + let mut mac = + Hmac::::new_from_slice(key.as_ref()).expect("HMAC accepts any key length"); + mac.update(jkt); + mac + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opaque_ke::generic_array::GenericArray; + + const JKT: [u8; 32] = [0x40; 32]; + + fn session_key(bytes: &[u8; 64]) -> SessionKey { + SessionKey::take(GenericArray::clone_from_slice(bytes)) + } + + fn sequence(start: u8) -> [u8; N] { + core::array::from_fn(|i| start + i as u8) + } + + /// Computed independently (Python `hmac`/`hashlib`), so a change to the derivation, the label + /// or the salt fails here instead of between a released client and server. + #[test] + fn binding_is_pinned() { + let key = session_key(&sequence(0x00)); + let jkt = sequence(0x40); + + assert_eq!( + key.dpop_binding(&jkt).to_bytes(), + [ + 0x1e, 0x38, 0xaf, 0x83, 0x21, 0x81, 0x20, 0xa2, 0x40, 0xb4, 0x85, 0x29, 0x07, 0x13, + 0xd9, 0x9b, 0x8e, 0x4e, 0xeb, 0xaa, 0x1a, 0x63, 0x91, 0x8c, 0xf5, 0xf9, 0x27, 0xff, + 0x1b, 0x39, 0x0d, 0x23, + ], + ); + } + + #[test] + fn verifies_own_binding() { + let key = session_key(&[1; 64]); + + assert_eq!( + key.verify_dpop_binding(&JKT, &key.dpop_binding(&JKT)), + Ok(()) + ); + } + + #[test] + fn rejects_binding_for_another_key() { + let key = session_key(&[1; 64]); + + assert_eq!( + key.verify_dpop_binding(&[0x41; 32], &key.dpop_binding(&JKT)), + Err(OpaqueError::InvalidLogin), + ); + } + + #[test] + fn rejects_binding_from_another_session() { + let binding = session_key(&[2; 64]).dpop_binding(&JKT); + + assert_eq!( + session_key(&[1; 64]).verify_dpop_binding(&JKT, &binding), + Err(OpaqueError::InvalidLogin), + ); + } + + #[test] + fn survives_base64() { + let binding = session_key(&[1; 64]).dpop_binding(&JKT); + let restored = DpopBinding::from_base64(&binding.to_base64()).unwrap(); + + assert_eq!(restored.to_bytes(), binding.to_bytes()); + } + + #[test] + fn wrong_length_is_malformed() { + assert!(matches!( + DpopBinding::from_bytes(&[0; 31]), + Err(OpaqueError::Malformed) + )); + assert!(matches!( + DpopBinding::from_base64("not base64!"), + Err(OpaqueError::Malformed) + )); + } +} diff --git a/rust/crates/keygo-opaque/src/keys.rs b/rust/crates/keygo-opaque/src/keys.rs index 9ffc62f94..5a3e3054a 100644 --- a/rust/crates/keygo-opaque/src/keys.rs +++ b/rust/crates/keygo-opaque/src/keys.rs @@ -4,12 +4,14 @@ use zeroize::{Zeroize, Zeroizing}; pub const KEY_LEN: usize = 64; +/// `$as_bytes` is the accessor's visibility: keep it crate-private for keys whose derivations +/// live in this crate. macro_rules! secret_key { - ($name:ident) => { + ($name:ident, as_bytes = $as_bytes:vis) => { pub struct $name(Zeroizing<[u8; KEY_LEN]>); impl $name { - pub fn as_bytes(&self) -> &[u8; KEY_LEN] { + $as_bytes fn as_bytes(&self) -> &[u8; KEY_LEN] { &self.0 } @@ -29,5 +31,5 @@ macro_rules! secret_key { }; } -secret_key!(SessionKey); -secret_key!(ExportKey); +secret_key!(SessionKey, as_bytes = pub(crate)); +secret_key!(ExportKey, as_bytes = pub); diff --git a/rust/crates/keygo-opaque/src/lib.rs b/rust/crates/keygo-opaque/src/lib.rs index becfe37cf..da22b6967 100644 --- a/rust/crates/keygo-opaque/src/lib.rs +++ b/rust/crates/keygo-opaque/src/lib.rs @@ -6,11 +6,13 @@ mod macros; pub mod client; pub mod server; +mod dpop_binding; mod error; mod keys; mod messages; mod suite; +pub use dpop_binding::DpopBinding; pub use error::{OpaqueError, OpaqueResult}; pub use keys::{ExportKey, KEY_LEN, SessionKey}; pub use messages::{ diff --git a/rust/crates/keygo-opaque/src/macros.rs b/rust/crates/keygo-opaque/src/macros.rs index a05f5268f..9de44d265 100644 --- a/rust/crates/keygo-opaque/src/macros.rs +++ b/rust/crates/keygo-opaque/src/macros.rs @@ -17,3 +17,35 @@ macro_rules! opaque_newtype { } )+}; } + +macro_rules! wire_message { + ($($name:ident),+ $(,)?) => {$( + impl $name { + pub fn to_base64(&self) -> String { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(self.to_bytes()) + } + + pub fn from_base64(text: &str) -> $crate::OpaqueResult { + use base64::Engine; + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(text) + .map_err(|_| $crate::OpaqueError::Malformed)?; + Self::from_bytes(&bytes) + } + } + + impl serde::Serialize for $name { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.to_base64()) + } + } + + impl<'de> serde::Deserialize<'de> for $name { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::from_base64(&text).map_err(serde::de::Error::custom) + } + } + )+}; +} diff --git a/rust/crates/keygo-opaque/src/messages.rs b/rust/crates/keygo-opaque/src/messages.rs index 3a11b8410..fa68d0029 100644 --- a/rust/crates/keygo-opaque/src/messages.rs +++ b/rust/crates/keygo-opaque/src/messages.rs @@ -1,6 +1,3 @@ -use crate::error::{OpaqueError, OpaqueResult}; -use base64::Engine; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; use zeroize::Zeroizing; opaque_newtype! { @@ -26,34 +23,6 @@ opaque_newtype! { PasswordFile(ServerRegistration) as Zeroizing>; } -macro_rules! wire_message { - ($($name:ident),+ $(,)?) => {$( - impl $name { - pub fn to_base64(&self) -> String { - URL_SAFE_NO_PAD.encode(self.to_bytes()) - } - - pub fn from_base64(text: &str) -> OpaqueResult { - let bytes = URL_SAFE_NO_PAD.decode(text).map_err(|_| OpaqueError::Malformed)?; - Self::from_bytes(&bytes) - } - } - - impl serde::Serialize for $name { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(&self.to_base64()) - } - } - - impl<'de> serde::Deserialize<'de> for $name { - fn deserialize>(deserializer: D) -> Result { - let text = String::deserialize(deserializer)?; - Self::from_base64(&text).map_err(serde::de::Error::custom) - } - } - )+}; -} - wire_message!( RegistrationRequest, RegistrationResponse, diff --git a/rust/crates/keygo-opaque/tests/protocol.rs b/rust/crates/keygo-opaque/tests/protocol.rs index 3eeb97ebe..63c106ac6 100644 --- a/rust/crates/keygo-opaque/tests/protocol.rs +++ b/rust/crates/keygo-opaque/tests/protocol.rs @@ -1,12 +1,13 @@ use keygo_opaque::client::{ClientLogin, ClientRegistration, LoginFinish}; use keygo_opaque::server::{self, ServerLogin, ServerSetup}; use keygo_opaque::{ - CredentialFinalization, CredentialRequest, CredentialResponse, OpaqueError, PasswordFile, - RegistrationRequest, + CredentialFinalization, CredentialRequest, CredentialResponse, DpopBinding, OpaqueError, + PasswordFile, RegistrationRequest, }; const ID: &[u8] = b"account-1"; const PASSWORD: &[u8] = b"correct horse battery staple"; +const JKT: [u8; 32] = [0x40; 32]; fn register(setup: &ServerSetup, password: &[u8]) -> (PasswordFile, Vec) { let (client, request) = ClientRegistration::start(password).unwrap(); @@ -39,8 +40,13 @@ fn register_then_login_agrees_on_keys() { let (client, server) = login(&setup, Some(file), PASSWORD).unwrap(); let finalization = CredentialFinalization::from_bytes(&client.finalization.to_bytes()).unwrap(); let server_session_key = server.finish(finalization).unwrap(); + let binding = client.session_key.dpop_binding(&JKT); + let binding = DpopBinding::from_base64(&binding.to_base64()).unwrap(); - assert_eq!(client.session_key.as_bytes(), server_session_key.as_bytes()); + assert_eq!( + server_session_key.verify_dpop_binding(&JKT, &binding), + Ok(()) + ); assert_eq!( client.export_key.as_bytes().as_slice(), registration_export_key @@ -48,6 +54,32 @@ fn register_then_login_agrees_on_keys() { assert_eq!(client.server_public_key, setup.public_key()); } +/// A relay that forwards one run's KE3 cannot pair it with a binding from another run. +#[test] +fn dpop_binding_from_another_login_is_rejected() { + let setup = ServerSetup::generate(); + let (file, _) = register(&setup, PASSWORD); + let file_bytes = file.to_bytes(); + + let (client, server) = login(&setup, Some(file), PASSWORD).unwrap(); + let (other, _) = login( + &setup, + Some(PasswordFile::from_bytes(&file_bytes).unwrap()), + PASSWORD, + ) + .unwrap(); + let server_session_key = server.finish(client.finalization).unwrap(); + + assert_eq!( + server_session_key.verify_dpop_binding(&JKT, &other.session_key.dpop_binding(&JKT)), + Err(OpaqueError::InvalidLogin), + ); + assert_eq!( + server_session_key.verify_dpop_binding(&[0x41; 32], &client.session_key.dpop_binding(&JKT)), + Err(OpaqueError::InvalidLogin), + ); +} + #[test] fn wrong_password_is_rejected_by_the_client() { let setup = ServerSetup::generate(); From 9c2ea303265b738b5e1b70eedfb0752e373da648 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 24 Oct 2026 01:04:51 +0200 Subject: [PATCH 07/26] feat(api): add dpop extractor --- rust/crates/keygo-dpop/src/verify.rs | 2 +- rust/crates/keygo-server/src/api/dpop.rs | 169 ++++++++++++++++++++++ rust/crates/keygo-server/src/api/error.rs | 46 +++++- rust/crates/keygo-server/src/api/mod.rs | 4 +- rust/crates/keygo-server/src/api/state.rs | 4 + rust/crates/keygo-server/src/testing.rs | 1 + 6 files changed, 222 insertions(+), 4 deletions(-) create mode 100644 rust/crates/keygo-server/src/api/dpop.rs diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index fc857934a..53da513a4 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -25,7 +25,7 @@ pub struct Expected<'a> { pub enum VerifyError { /// Answer `invalid_dpop_proof`. The reason is for logs only; the client reacts to every one /// the same way. - #[error("invalid dpop proof: {0}")] + #[error("invalid dpop proof")] Invalid(#[from] InvalidProof), /// Answer `use_dpop_nonce` and send this nonce in the `DPoP-Nonce` header. #[error("dpop nonce required")] diff --git a/rust/crates/keygo-server/src/api/dpop.rs b/rust/crates/keygo-server/src/api/dpop.rs new file mode 100644 index 000000000..1bdeb11b4 --- /dev/null +++ b/rust/crates/keygo-server/src/api/dpop.rs @@ -0,0 +1,169 @@ +use crate::api::{AppState, ErrorCode, HttpError, ServerError}; +use axum::extract::{FromRequestParts, OriginalUri}; +use axum::http::request::Parts; +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use keygo_dpop::Htm; +use keygo_dpop::verify::{Expected, InvalidProof, VerifyError}; +use url::Url; + +const DPOP: HeaderName = HeaderName::from_static("dpop"); +const DPOP_NONCE: HeaderName = HeaderName::from_static("dpop-nonce"); + +pub struct DpopProof { + pub jkt: [u8; 32], +} + +impl FromRequestParts for DpopProof { + type Rejection = ServerError; + + async fn from_request_parts( + parts: &mut Parts, + state: &AppState, + ) -> Result { + let proof = single_header(&parts.headers, &DPOP) + .and_then(|value| value.to_str().ok()) + .ok_or(VerifyError::Invalid(InvalidProof::Malformed))?; + let htm = htm(&parts.method).ok_or(VerifyError::Invalid(InvalidProof::Request))?; + let htu = expected_htu(parts, &state.public_url); + + let expected = Expected { + htm, + htu: htu.as_str(), + access_token: None, + jkt: None, + }; + let jkt = state + .dpop_verifier + .verify(proof, expected) + .inspect_err(|err| tracing::debug!(?err, "dpop proof rejected"))?; + Ok(DpopProof { jkt }) + } +} + +impl HttpError for VerifyError { + fn status_and_code(&self) -> (StatusCode, ErrorCode) { + match self { + Self::Invalid(_) => (StatusCode::BAD_REQUEST, ErrorCode::InvalidDpopProof), + Self::UseNonce(_) => (StatusCode::BAD_REQUEST, ErrorCode::UseDpopNonce), + Self::Busy => (StatusCode::TOO_MANY_REQUESTS, ErrorCode::RateLimited), + } + } + + fn headers(&self) -> HeaderMap { + match self { + Self::UseNonce(nonce) => { + let nonce = HeaderValue::try_from(nonce.to_string()).expect("nonces are base64url"); + HeaderMap::from_iter([(DPOP_NONCE, nonce)]) + } + Self::Invalid(_) | Self::Busy => HeaderMap::new(), + } + } +} + +fn single_header<'a>(headers: &'a HeaderMap, name: &HeaderName) -> Option<&'a HeaderValue> { + let mut values = headers.get_all(name).iter(); + match (values.next(), values.next()) { + (Some(value), None) => Some(value), + _ => None, + } +} + +fn htm(method: &Method) -> Option { + match *method { + Method::GET => Some(Htm::Get), + Method::POST => Some(Htm::Post), + Method::DELETE => Some(Htm::Delete), + _ => None, + } +} + +fn expected_htu(parts: &Parts, public_url: &Url) -> Url { + let path = parts + .extensions + .get::() + .map_or(parts.uri.path(), |OriginalUri(uri)| uri.path()); + + let mut url = public_url.clone(); + url.set_path(path); + url.set_query(None); + url.set_fragment(None); + url +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::api::error::render; + use axum::Router; + use axum::body::Body; + use axum::http::Request; + use axum::routing::post; + use serde_json::json; + use tower::ServiceExt; + + fn public_url() -> Url { + Url::parse("https://sync.example").unwrap() + } + + async fn finish(request: Request) -> StatusCode { + let state = AppState { + public_url: public_url(), + ..crate::api::tests::state() + }; + let app = Router::new() + .nest( + "/auth", + Router::new().route("/finish", post(|_: DpopProof| async {})), + ) + .with_state(state); + app.oneshot(request).await.unwrap().status() + } + + #[test] + fn htu_uses_public_url_and_the_unnested_path() { + let (parts, ()) = Request::post("/finish") + .extension(OriginalUri( + "/api/v1/auth/login/finish?a=b".parse().unwrap(), + )) + .body(()) + .unwrap() + .into_parts(); + + assert_eq!( + expected_htu(&parts, &public_url()).as_str(), + "https://sync.example/api/v1/auth/login/finish", + ); + } + + #[tokio::test] + async fn missing_or_repeated_header_is_an_invalid_proof() { + let missing = Request::post("/auth/finish").body(Body::empty()).unwrap(); + let repeated = Request::post("/auth/finish") + .header(DPOP, "a.b.c") + .header(DPOP, "a.b.c") + .body(Body::empty()) + .unwrap(); + + assert_eq!(finish(missing).await, StatusCode::BAD_REQUEST); + assert_eq!(finish(repeated).await, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn invalid_proof_hides_its_reason() { + let (status, body) = render(VerifyError::from(InvalidProof::Replay)).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!( + body, + json!({ "code": "invalid_dpop_proof", "message": "invalid dpop proof" }), + ); + } + + #[tokio::test] + async fn full_replay_cache_is_rate_limited() { + let (status, body) = render(VerifyError::Busy).await; + + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(body["code"], "rate_limited"); + } +} diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index 9b7166929..abfb628ba 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -1,6 +1,6 @@ use crate::domain::UsernameError; use axum::extract::rejection::JsonRejection; -use axum::http::StatusCode; +use axum::http::{HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use keygo_opaque::OpaqueError; use serde::Serialize; @@ -16,6 +16,7 @@ pub enum ErrorCode { Internal, InvalidRequest, NotFound, + RateLimited, // auth InvalidUsername, InvalidCredentials, @@ -25,16 +26,24 @@ pub enum ErrorCode { InviteInvalid, RegistrationExpired, LoginExpired, + // dpop + InvalidDpopProof, + UseDpopNonce, } pub trait HttpError: std::error::Error + Send + Sync + 'static { fn status_and_code(&self) -> (StatusCode, ErrorCode); + + fn headers(&self) -> HeaderMap { + HeaderMap::new() + } } pub struct ServerError { status: StatusCode, code: ErrorCode, message: String, + headers: HeaderMap, source: Option, } @@ -46,6 +55,7 @@ impl ServerError { status, code, message: message.into(), + headers: HeaderMap::new(), source: None, } } @@ -63,6 +73,7 @@ impl ServerError { status: StatusCode::INTERNAL_SERVER_ERROR, code: ErrorCode::Internal, message: "internal server error".to_owned(), + headers: HeaderMap::new(), source: Some(source), } } @@ -71,15 +82,20 @@ impl ServerError { impl From for ServerError { fn from(err: E) -> Self { let (status, code) = err.status_and_code(); + let headers = err.headers(); if status.is_server_error() { return Self { status, code, + headers, ..Self::internal(err.into()) }; } - Self::new(status, code, err.to_string()) + Self { + headers, + ..Self::new(status, code, err.to_string()) + } } } @@ -97,6 +113,7 @@ impl IntoResponse for ServerError { ( self.status, + self.headers, axum::Json(json!({"code": self.code, "message": self.message})), ) .into_response() @@ -225,4 +242,29 @@ mod tests { json!({ "code": "not_found", "message": "resource not found" }), ); } + + #[derive(Debug, thiserror::Error)] + #[error("challenge")] + struct Challenge; + + impl HttpError for Challenge { + fn status_and_code(&self) -> (StatusCode, ErrorCode) { + (StatusCode::UNAUTHORIZED, ErrorCode::InvalidCredentials) + } + + fn headers(&self) -> HeaderMap { + HeaderMap::from_iter([( + axum::http::header::WWW_AUTHENTICATE, + "DPoP".parse().unwrap(), + )]) + } + } + + #[tokio::test] + async fn error_headers_reach_the_response() { + let response = ServerError::from(Challenge).into_response(); + + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!(response.headers()["www-authenticate"], "DPoP"); + } } diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 4fcbd6d3b..36d843a8b 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -1,3 +1,4 @@ +mod dpop; mod error; mod extract; mod routes; @@ -64,8 +65,9 @@ mod tests { (status, body.to_vec()) } - fn state() -> AppState { + pub(super) fn state() -> AppState { AppState { + public_url: url::Url::parse("http://localhost").unwrap(), signup: Signup::InviteOnly(Arc::new(InvitePepper::new([0; 32]))), opaque_state: keygo_opaque::server::ServerSetup::generate(), // Lazy pools never connect until queried, so routes without a query need no database. diff --git a/rust/crates/keygo-server/src/api/state.rs b/rust/crates/keygo-server/src/api/state.rs index b40930cab..9d73389b3 100644 --- a/rust/crates/keygo-server/src/api/state.rs +++ b/rust/crates/keygo-server/src/api/state.rs @@ -1,12 +1,15 @@ use crate::cache::LoginStates; use crate::config::DeploymentConfig; use crate::service::registration::Signup; +use anyhow::Context; use keygo_dpop::verify::DpopVerifier; use sqlx::PgPool; use std::sync::Arc; +use url::Url; #[derive(Clone)] pub struct AppState { + pub public_url: Url, pub signup: Signup, pub opaque_state: keygo_opaque::server::ServerSetup, pub db: PgPool, @@ -18,6 +21,7 @@ impl AppState { pub fn new(config: &DeploymentConfig, db: PgPool) -> anyhow::Result { let secrets = &config.secrets; Ok(Self { + public_url: Url::parse(&config.server.public_url).context("invalid public url")?, signup: if config.server.allow_signups { Signup::Open } else { diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 42bcc0875..f6ca5bcee 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -126,6 +126,7 @@ pub async fn expires_in_secs(db: &PgPool, table: &str) -> f64 { /// Requests that must see each other's login states share one `AppState` through `post_to`. pub fn app_state(db: &PgPool, setup: &ServerSetup) -> AppState { AppState { + public_url: url::Url::parse("http://localhost").unwrap(), signup: Signup::Open, opaque_state: setup.clone(), db: db.clone(), From 1dc989ec630bbd402df76de9ccc338db99e6a6f7 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 24 Oct 2026 21:20:05 +0200 Subject: [PATCH 08/26] feat(api): bind login finish to dpop proof --- rust/crates/keygo-dpop/Cargo.toml | 6 +- rust/crates/keygo-dpop/src/lib.rs | 4 +- rust/crates/keygo-dpop/src/testing.rs | 12 +- rust/crates/keygo-server/Cargo.toml | 2 + rust/crates/keygo-server/src/api/error.rs | 47 ++++--- .../keygo-server/src/api/routes/auth/login.rs | 122 +++++++++++++----- .../keygo-server/src/service/login/finish.rs | 58 ++++++--- rust/crates/keygo-server/src/testing.rs | 68 +++++++++- 8 files changed, 240 insertions(+), 79 deletions(-) diff --git a/rust/crates/keygo-dpop/Cargo.toml b/rust/crates/keygo-dpop/Cargo.toml index cf300b53b..1afdab863 100644 --- a/rust/crates/keygo-dpop/Cargo.toml +++ b/rust/crates/keygo-dpop/Cargo.toml @@ -3,6 +3,10 @@ name = "keygo-dpop" version.workspace = true edition.workspace = true +[features] +# Exposes `testing::TestSigner` so other crates' tests can sign proofs. +test-support = [] + [dependencies] thiserror.workspace = true zeroize.workspace = true @@ -14,4 +18,4 @@ p256 = { version = "0.14.0", default-features = false, features = ["ecdsa", "get serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" sha2 = "0.11.1" -getrandom = "0.4.3" \ No newline at end of file +getrandom = "0.4.3" diff --git a/rust/crates/keygo-dpop/src/lib.rs b/rust/crates/keygo-dpop/src/lib.rs index 2791577c2..cf279ac65 100644 --- a/rust/crates/keygo-dpop/src/lib.rs +++ b/rust/crates/keygo-dpop/src/lib.rs @@ -3,8 +3,8 @@ pub mod jwk; mod nonce; mod proof; mod seen_jtis; -#[cfg(test)] -mod testing; +#[cfg(any(test, feature = "test-support"))] +pub mod testing; pub mod verify; pub mod wire; diff --git a/rust/crates/keygo-dpop/src/testing.rs b/rust/crates/keygo-dpop/src/testing.rs index 2a6d0e797..93066cfbe 100644 --- a/rust/crates/keygo-dpop/src/testing.rs +++ b/rust/crates/keygo-dpop/src/testing.rs @@ -3,23 +3,29 @@ use p256::ecdsa::signature::Signer; use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; use std::convert::Infallible; -pub(crate) struct TestSigner { +pub struct TestSigner { key: SigningKey, pub(crate) verifying: VerifyingKey, } impl TestSigner { - pub(crate) fn new() -> Self { + pub fn new() -> Self { Self::from_seed(7) } - pub(crate) fn from_seed(seed: u8) -> Self { + pub fn from_seed(seed: u8) -> Self { let key = SigningKey::from_slice(&[seed; 32]).unwrap(); let verifying = *key.verifying_key(); Self { key, verifying } } } +impl Default for TestSigner { + fn default() -> Self { + Self::new() + } +} + impl DpopSigner for TestSigner { type Error = Infallible; diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index da5313714..0f64da62f 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -38,6 +38,8 @@ time = { version = "0.3.55", features = ["formatting", "macros"] } moka = { version = "0.12.16", features = ["sync"] } [dev-dependencies] +keygo-dpop = { path = "../keygo-dpop", features = ["test-support"] } + http-body-util = "0.1.5" serde_json = "1.0.154" tower = { version = "0.5.3", features = ["util"] } diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index abfb628ba..fd5d2f569 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -39,7 +39,9 @@ pub trait HttpError: std::error::Error + Send + Sync + 'static { } } -pub struct ServerError { +pub struct ServerError(Box); + +struct Inner { status: StatusCode, code: ErrorCode, message: String, @@ -51,13 +53,13 @@ pub type ServerResult = Result; impl ServerError { pub fn new(status: StatusCode, code: ErrorCode, message: impl Into) -> Self { - Self { + Self(Box::new(Inner { status, code, message: message.into(), headers: HeaderMap::new(), source: None, - } + })) } pub fn not_found() -> Self { @@ -67,7 +69,9 @@ impl ServerError { "resource not found", ) } +} +impl Inner { fn internal(source: anyhow::Error) -> Self { Self { status: StatusCode::INTERNAL_SERVER_ERROR, @@ -83,38 +87,43 @@ impl From for ServerError { fn from(err: E) -> Self { let (status, code) = err.status_and_code(); let headers = err.headers(); - if status.is_server_error() { - return Self { + let inner = if status.is_server_error() { + Inner { status, code, headers, - ..Self::internal(err.into()) - }; - } - - Self { - headers, - ..Self::new(status, code, err.to_string()) - } + ..Inner::internal(err.into()) + } + } else { + Inner { + status, + code, + message: err.to_string(), + headers, + source: None, + } + }; + Self(Box::new(inner)) } } impl From for ServerError { fn from(err: anyhow::Error) -> Self { - Self::internal(err) + Self(Box::new(Inner::internal(err))) } } impl IntoResponse for ServerError { fn into_response(self) -> Response { - if let Some(source) = &self.source { - tracing::error!(code = ?self.code, "request failed: {source:#}"); + let err = *self.0; + if let Some(source) = &err.source { + tracing::error!(code = ?err.code, "request failed: {source:#}"); } ( - self.status, - self.headers, - axum::Json(json!({"code": self.code, "message": self.message})), + err.status, + err.headers, + axum::Json(json!({"code": err.code, "message": err.message})), ) .into_response() } diff --git a/rust/crates/keygo-server/src/api/routes/auth/login.rs b/rust/crates/keygo-server/src/api/routes/auth/login.rs index 8537a5a97..b64476928 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/login.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/login.rs @@ -1,3 +1,4 @@ +use crate::api::dpop::DpopProof; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; use crate::domain::{LoginId, Username}; use crate::service::login::{self, FinishLogin, StartLogin}; @@ -5,7 +6,7 @@ use axum::Router; use axum::extract::State; use axum::http::StatusCode; use axum::routing::post; -use keygo_opaque::{CredentialFinalization, CredentialRequest, CredentialResponse}; +use keygo_opaque::{CredentialFinalization, CredentialRequest, CredentialResponse, DpopBinding}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -60,6 +61,7 @@ async fn start( struct FinishRequest { login_id: LoginId, credential_finalization: CredentialFinalization, + dpop_binding: DpopBinding, } #[derive(Serialize)] @@ -80,11 +82,14 @@ impl HttpError for login::FinishError { async fn finish( State(state): State, + proof: DpopProof, Json(request): Json, ) -> ServerResult> { let input = FinishLogin { login_id: request.login_id, credential_finalization: request.credential_finalization, + binding: request.dpop_binding, + jkt: proof.jkt, }; let finished = login::finish(&state.db, &state.login_states, input).await?; @@ -99,7 +104,9 @@ async fn finish( mod tests { use super::*; use crate::api::error::render; - use crate::testing::{PASSWORD, app_state, post_to, register}; + use crate::testing::{ + PASSWORD, app_state, post_to, post_with_proof, proof_post, prover, register, send, + }; use keygo_opaque::OpaqueError; use keygo_opaque::client::ClientLogin; use keygo_opaque::server::ServerSetup; @@ -117,15 +124,21 @@ mod tests { (client, started) } - fn finalization(client: ClientLogin, started: &Value) -> String { + fn finish_body( + login_id: &Value, + client: ClientLogin, + started: &Value, + jkt: &[u8; 32], + ) -> Value { let response = CredentialResponse::from_base64(started["credential_response"].as_str().unwrap()) .unwrap(); - client - .finish(PASSWORD, response) - .unwrap() - .finalization - .to_base64() + let finish = client.finish(PASSWORD, response).unwrap(); + json!({ + "login_id": login_id, + "credential_finalization": finish.finalization.to_base64(), + "dpop_binding": finish.session_key.dpop_binding(jkt).to_base64(), + }) } #[tokio::test] @@ -152,18 +165,69 @@ mod tests { let (client, started) = start_over_http(&state, "Ada").await; assert_eq!(started["expires_in"], login::TTL.as_secs()); - let body = json!({ - "login_id": started["login_id"], - "credential_finalization": finalization(client, &started), - }); + let prover = prover(); + let body = finish_body(&started["login_id"], client, &started, prover.jkt()); - let (status, finished) = post_to(state.clone(), FINISH, body).await; + let (status, finished) = post_with_proof(&state, &prover, FINISH, body).await; assert_eq!(status, StatusCode::OK); assert_eq!(finished, json!({ "user_id": user_id, "username": "ada" })); assert_eq!(state.login_states.count(), 0); } + #[sqlx::test] + async fn finish_without_a_proof_keeps_the_login(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let (client, started) = start_over_http(&state, "ada").await; + let body = finish_body(&started["login_id"], client, &started, prover().jkt()); + + let (status, body) = post_to(state.clone(), FINISH, body).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "invalid_dpop_proof"); + assert_eq!(state.login_states.count(), 1); + } + + #[sqlx::test] + async fn nonce_challenge_keeps_the_login(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let (client, started) = start_over_http(&state, "ada").await; + let prover = prover(); + let body = finish_body(&started["login_id"], client, &started, prover.jkt()); + + // A verifier that just started accepts no proof without one of its own nonces. + let request = proof_post(&state, &prover, FINISH, &body, None); + let (status, headers, challenge) = send(&state, request).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(challenge["code"], "use_dpop_nonce"); + assert!(headers.contains_key("dpop-nonce")); + assert_eq!(state.login_states.count(), 1); + + let (status, _) = post_with_proof(&state, &prover, FINISH, body).await; + + assert_eq!(status, StatusCode::OK); + } + + #[sqlx::test] + async fn binding_for_another_key_is_unauthorized(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let (client, started) = start_over_http(&state, "ada").await; + let body = finish_body(&started["login_id"], client, &started, &[0x41; 32]); + + let (status, body) = post_with_proof(&state, &prover(), FINISH, body).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_credentials"); + assert_eq!(state.login_states.count(), 0); + } + #[sqlx::test] async fn unknown_user_starts_like_a_known_one(db: PgPool) { let setup = ServerSetup::generate(); @@ -214,12 +278,10 @@ mod tests { register(&db, &setup, "ada").await; let (_, target) = start_over_http(&state, "ada").await; let (client, other) = start_over_http(&state, "ada").await; - let body = json!({ - "login_id": target["login_id"], - "credential_finalization": finalization(client, &other), - }); + let prover = prover(); + let body = finish_body(&target["login_id"], client, &other, prover.jkt()); - let (status, body) = post_to(state.clone(), FINISH, body).await; + let (status, body) = post_with_proof(&state, &prover, FINISH, body).await; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!(body["code"], "invalid_credentials"); @@ -232,12 +294,10 @@ mod tests { register(&db, &setup, "ada").await; let (_, fake) = start_over_http(&state, "bob").await; let (client, real) = start_over_http(&state, "ada").await; - let body = json!({ - "login_id": fake["login_id"], - "credential_finalization": finalization(client, &real), - }); + let prover = prover(); + let body = finish_body(&fake["login_id"], client, &real, prover.jkt()); - let (status, body) = post_to(state.clone(), FINISH, body).await; + let (status, body) = post_with_proof(&state, &prover, FINISH, body).await; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!(body["code"], "invalid_credentials"); @@ -249,12 +309,10 @@ mod tests { let state = app_state(&db, &setup); register(&db, &setup, "ada").await; let (client, started) = start_over_http(&state, "ada").await; - let body = json!({ - "login_id": LoginId::random(), - "credential_finalization": finalization(client, &started), - }); + let prover = prover(); + let body = finish_body(&json!(LoginId::random()), client, &started, prover.jkt()); - let (status, body) = post_to(state.clone(), FINISH, body).await; + let (status, body) = post_with_proof(&state, &prover, FINISH, body).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(body["code"], "login_expired"); @@ -263,9 +321,13 @@ mod tests { #[sqlx::test] async fn finish_rejects_a_malformed_login_id(db: PgPool) { let state = app_state(&db, &ServerSetup::generate()); - let body = json!({ "login_id": "short", "credential_finalization": "AAAA" }); + let body = json!({ + "login_id": "short", + "credential_finalization": "AAAA", + "dpop_binding": "AAAA", + }); - let (status, body) = post_to(state, FINISH, body).await; + let (status, body) = post_with_proof(&state, &prover(), FINISH, body).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(body["code"], "invalid_request"); diff --git a/rust/crates/keygo-server/src/service/login/finish.rs b/rust/crates/keygo-server/src/service/login/finish.rs index 864678393..6c7401a11 100644 --- a/rust/crates/keygo-server/src/service/login/finish.rs +++ b/rust/crates/keygo-server/src/service/login/finish.rs @@ -1,7 +1,7 @@ use crate::cache::LoginStates; use crate::db::users; use crate::domain::{LoginId, Username}; -use keygo_opaque::{CredentialFinalization, OpaqueError}; +use keygo_opaque::{CredentialFinalization, DpopBinding, OpaqueError}; use sqlx::PgPool; use thiserror::Error; use uuid::Uuid; @@ -19,6 +19,8 @@ pub enum FinishError { pub struct FinishLogin { pub login_id: LoginId, pub credential_finalization: CredentialFinalization, + pub binding: DpopBinding, + pub jkt: [u8; 32], } pub struct Finished { @@ -37,11 +39,13 @@ pub async fn finish( let FinishLogin { login_id, credential_finalization, + binding, + jkt, } = input; let pending = login_states.take(&login_id).ok_or(FinishError::Expired)?; - // TODO: derive the session from the session key once sessions exist. - let _session_key = pending.state.finish(credential_finalization)?; + let session_key = pending.state.finish(credential_finalization)?; + session_key.verify_dpop_binding(&jkt, &binding)?; // The fake path cannot produce a valid finalization, and an account deleted since `start` has // no user left to log into; both answer exactly like a wrong password. @@ -62,6 +66,18 @@ mod tests { use keygo_opaque::server::ServerSetup; use std::time::Duration; + fn copy(input: &FinishLogin) -> FinishLogin { + FinishLogin { + login_id: input.login_id, + credential_finalization: CredentialFinalization::from_bytes( + &input.credential_finalization.to_bytes(), + ) + .unwrap(), + binding: DpopBinding::from_bytes(&input.binding.to_bytes()).unwrap(), + jkt: input.jkt, + } + } + #[sqlx::test] async fn right_password_logs_in(db: PgPool) { let login_states = LoginStates::new(); @@ -85,13 +101,7 @@ mod tests { register(&db, &setup, "ada").await; let (client, started) = start_login(&db, &login_states, &setup, "ada").await; let input = finish_login(client, started); - let replay = FinishLogin { - login_id: input.login_id, - credential_finalization: CredentialFinalization::from_bytes( - &input.credential_finalization.to_bytes(), - ) - .unwrap(), - }; + let replay = copy(&input); finish(&db, &login_states, input).await.unwrap(); let err = finish(&db, &login_states, replay).await.err().unwrap(); @@ -110,13 +120,7 @@ mod tests { login_id: target.login_id, ..finish_login(client, other) }; - let retry = FinishLogin { - login_id: forged.login_id, - credential_finalization: CredentialFinalization::from_bytes( - &forged.credential_finalization.to_bytes(), - ) - .unwrap(), - }; + let retry = copy(&forged); let err = finish(&db, &login_states, forged).await.err().unwrap(); let retried = finish(&db, &login_states, retry).await.err().unwrap(); @@ -128,6 +132,26 @@ mod tests { assert!(matches!(retried, FinishError::Expired), "{retried:?}"); } + #[sqlx::test] + async fn binding_for_another_key_is_invalid_and_consumes_the_login(db: PgPool) { + let login_states = LoginStates::new(); + let setup = ServerSetup::generate(); + register(&db, &setup, "ada").await; + let (client, started) = start_login(&db, &login_states, &setup, "ada").await; + let input = FinishLogin { + jkt: [0x41; 32], + ..finish_login(client, started) + }; + + let err = finish(&db, &login_states, input).await.err().unwrap(); + + assert!( + matches!(err, FinishError::Opaque(OpaqueError::InvalidLogin)), + "{err:?}" + ); + assert_eq!(login_states.count(), 0); + } + #[sqlx::test] async fn wrong_password_fails_at_the_client(db: PgPool) { let login_states = LoginStates::new(); diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index f6ca5bcee..bd573acfc 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -6,10 +6,11 @@ use crate::service::invite; use crate::service::login::{self, FinishLogin, StartLogin}; use crate::service::registration::{self, FinishRegistration, Signup, StartRegistration}; use axum::body::Body; -use axum::http::{Request, StatusCode}; +use axum::http::{HeaderMap, Request, StatusCode}; use http_body_util::BodyExt; -use keygo_dpop::NonceKey; +use keygo_dpop::testing::TestSigner; use keygo_dpop::verify::DpopVerifier; +use keygo_dpop::{DpopProver, Htm, NonceKey, ProofRequest}; use keygo_opaque::client::{ClientLogin, ClientRegistration}; use keygo_opaque::server::ServerSetup; use serde_json::Value; @@ -20,6 +21,7 @@ use tower::ServiceExt; use uuid::Uuid; pub const PASSWORD: &[u8] = b"correct horse battery staple"; +const JKT: [u8; 32] = [7; 32]; pub fn username(raw: &str) -> Username { Username::parse(raw).unwrap() @@ -72,6 +74,8 @@ pub fn finish_login(client: ClientLogin, started: login::Started) -> FinishLogin FinishLogin { login_id: started.login_id, credential_finalization: finish.finalization, + binding: finish.session_key.dpop_binding(&JKT), + jkt: JKT, } } @@ -138,12 +142,62 @@ pub async fn post(db: &PgPool, setup: &ServerSetup, uri: &str, body: Value) -> ( post_to(app_state(db, setup), uri, body).await } pub async fn post_to(state: AppState, uri: &str, body: Value) -> (StatusCode, Value) { - let request = Request::post(uri) - .header("content-type", "application/json") - .body(Body::from(body.to_string())) + let (status, _, body) = send(&state, json_post(uri, &body)).await; + (status, body) +} + +pub fn prover() -> DpopProver { + DpopProver::new(TestSigner::new()) +} + +/// Posts with a fresh proof and answers a nonce challenge once, the way a real client would. +pub async fn post_with_proof( + state: &AppState, + prover: &DpopProver, + uri: &str, + body: Value, +) -> (StatusCode, Value) { + let request = proof_post(state, prover, uri, &body, None); + let (status, headers, response) = send(state, request).await; + if response["code"] != "use_dpop_nonce" { + return (status, response); + } + + let nonce = headers["dpop-nonce"].to_str().unwrap(); + let request = proof_post(state, prover, uri, &body, Some(nonce)); + let (status, _, response) = send(state, request).await; + (status, response) +} +pub fn proof_post( + state: &AppState, + prover: &DpopProver, + uri: &str, + body: &Value, + nonce: Option<&str>, +) -> Request { + let htu = state.public_url.join(uri).unwrap(); + let proof = prover + .proof(&ProofRequest { + htm: Htm::Post, + htu: htu.as_str(), + access_token: None, + nonce, + }) .unwrap(); - let response = router(state).oneshot(request).await.unwrap(); + let mut request = json_post(uri, body); + request.headers_mut().insert("dpop", proof.parse().unwrap()); + request +} +pub async fn send(state: &AppState, request: Request) -> (StatusCode, HeaderMap, Value) { + let response = router(state.clone()).oneshot(request).await.unwrap(); let status = response.status(); + let headers = response.headers().clone(); let body = response.into_body().collect().await.unwrap().to_bytes(); - (status, serde_json::from_slice(&body).unwrap()) + (status, headers, serde_json::from_slice(&body).unwrap()) +} +fn json_post(uri: &str, body: &Value) -> Request { + Request::post(uri) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap() } From c1c0deba8ba1a94dfd4f632638c7c3c3481ba2b7 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 24 Oct 2026 21:48:58 +0200 Subject: [PATCH 09/26] refactor(api): derive error status from code and slim down ServerError --- rust/crates/keygo-dpop/src/wire.rs | 4 +- rust/crates/keygo-server/src/api/dpop.rs | 12 +- rust/crates/keygo-server/src/api/error.rs | 170 +++++++----------- rust/crates/keygo-server/src/api/mod.rs | 4 +- .../keygo-server/src/api/routes/auth/login.rs | 35 ++-- .../src/api/routes/auth/register.rs | 26 +-- .../keygo-server/src/db/registrations.rs | 2 +- .../keygo-server/src/service/invite/revoke.rs | 2 +- .../keygo-server/src/service/login/finish.rs | 32 ++-- .../keygo-server/src/service/login/mod.rs | 11 ++ .../keygo-server/src/service/login/start.rs | 15 +- .../src/service/registration/finish.rs | 2 +- .../src/service/registration/start.rs | 2 +- 13 files changed, 133 insertions(+), 184 deletions(-) diff --git a/rust/crates/keygo-dpop/src/wire.rs b/rust/crates/keygo-dpop/src/wire.rs index b4cb79cf3..56113f205 100644 --- a/rust/crates/keygo-dpop/src/wire.rs +++ b/rust/crates/keygo-dpop/src/wire.rs @@ -35,9 +35,9 @@ pub(crate) fn encode(value: &T) -> String { #[derive(Debug, Error)] pub enum DecodeError { - #[error("invalid base64: {0}")] + #[error("invalid base64")] Base64(#[from] base64::DecodeError), - #[error("invalid json: {0}")] + #[error("invalid json")] Json(#[from] serde_json::Error), } diff --git a/rust/crates/keygo-server/src/api/dpop.rs b/rust/crates/keygo-server/src/api/dpop.rs index 1bdeb11b4..d830643cf 100644 --- a/rust/crates/keygo-server/src/api/dpop.rs +++ b/rust/crates/keygo-server/src/api/dpop.rs @@ -1,7 +1,7 @@ use crate::api::{AppState, ErrorCode, HttpError, ServerError}; use axum::extract::{FromRequestParts, OriginalUri}; use axum::http::request::Parts; -use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method}; use keygo_dpop::Htm; use keygo_dpop::verify::{Expected, InvalidProof, VerifyError}; use url::Url; @@ -41,11 +41,11 @@ impl FromRequestParts for DpopProof { } impl HttpError for VerifyError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { + fn code(&self) -> ErrorCode { match self { - Self::Invalid(_) => (StatusCode::BAD_REQUEST, ErrorCode::InvalidDpopProof), - Self::UseNonce(_) => (StatusCode::BAD_REQUEST, ErrorCode::UseDpopNonce), - Self::Busy => (StatusCode::TOO_MANY_REQUESTS, ErrorCode::RateLimited), + Self::Invalid(_) => ErrorCode::InvalidDpopProof, + Self::UseNonce(_) => ErrorCode::UseDpopNonce, + Self::Busy => ErrorCode::RateLimited, } } @@ -96,7 +96,7 @@ mod tests { use crate::api::error::render; use axum::Router; use axum::body::Body; - use axum::http::Request; + use axum::http::{Request, StatusCode}; use axum::routing::post; use serde_json::json; use tower::ServiceExt; diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index fd5d2f569..5f7b7ceba 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -5,8 +5,7 @@ use axum::response::{IntoResponse, Response}; use keygo_opaque::OpaqueError; use serde::Serialize; use serde_json::json; - -const INTERNAL: (StatusCode, ErrorCode) = (StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::Internal); +use thiserror::Error; /// Every `code` the API answers with; clients match on the serialized name. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] @@ -31,138 +30,114 @@ pub enum ErrorCode { UseDpopNonce, } -pub trait HttpError: std::error::Error + Send + Sync + 'static { - fn status_and_code(&self) -> (StatusCode, ErrorCode); - - fn headers(&self) -> HeaderMap { - HeaderMap::new() +impl ErrorCode { + pub fn status(self) -> StatusCode { + match self { + Self::Internal => StatusCode::INTERNAL_SERVER_ERROR, + Self::InvalidRequest + | Self::InvalidUsername + | Self::RegistrationExpired + | Self::LoginExpired + | Self::InvalidDpopProof + | Self::UseDpopNonce => StatusCode::BAD_REQUEST, + Self::InvalidCredentials => StatusCode::UNAUTHORIZED, + Self::InviteRequired | Self::InviteInvalid => StatusCode::FORBIDDEN, + Self::NotFound => StatusCode::NOT_FOUND, + Self::UsernameTaken | Self::UserIdTaken => StatusCode::CONFLICT, + Self::RateLimited => StatusCode::TOO_MANY_REQUESTS, + } } } -pub struct ServerError(Box); - -struct Inner { - status: StatusCode, - code: ErrorCode, - message: String, - headers: HeaderMap, - source: Option, -} - -pub type ServerResult = Result; +pub trait HttpError: std::error::Error + Send + Sync + 'static { + fn code(&self) -> ErrorCode; -impl ServerError { - pub fn new(status: StatusCode, code: ErrorCode, message: impl Into) -> Self { - Self(Box::new(Inner { - status, - code, - message: message.into(), - headers: HeaderMap::new(), - source: None, - })) + fn status(&self) -> StatusCode { + self.code().status() } - pub fn not_found() -> Self { - Self::new( - StatusCode::NOT_FOUND, - ErrorCode::NotFound, - "resource not found", - ) + fn headers(&self) -> HeaderMap { + HeaderMap::new() } } -impl Inner { - fn internal(source: anyhow::Error) -> Self { - Self { - status: StatusCode::INTERNAL_SERVER_ERROR, - code: ErrorCode::Internal, - message: "internal server error".to_owned(), - headers: HeaderMap::new(), - source: Some(source), - } - } -} +pub struct ServerError(Box); + +pub type ServerResult = Result; impl From for ServerError { fn from(err: E) -> Self { - let (status, code) = err.status_and_code(); - let headers = err.headers(); - let inner = if status.is_server_error() { - Inner { - status, - code, - headers, - ..Inner::internal(err.into()) - } - } else { - Inner { - status, - code, - message: err.to_string(), - headers, - source: None, - } - }; - Self(Box::new(inner)) - } -} - -impl From for ServerError { - fn from(err: anyhow::Error) -> Self { - Self(Box::new(Inner::internal(err))) + Self(Box::new(err)) } } impl IntoResponse for ServerError { fn into_response(self) -> Response { - let err = *self.0; - if let Some(source) = &err.source { - tracing::error!(code = ?err.code, "request failed: {source:#}"); - } + let (code, status, headers) = (self.0.code(), self.0.status(), self.0.headers()); + let message = if status.is_server_error() { + let source = anyhow::Error::from_boxed(self.0); + tracing::error!(?code, "request failed: {source:#}"); + "internal server error".to_owned() + } else { + self.0.to_string() + }; ( - err.status, - err.headers, - axum::Json(json!({"code": err.code, "message": err.message})), + status, + headers, + axum::Json(json!({"code": code, "message": message})), ) .into_response() } } +#[derive(Debug, Error)] +#[error("resource not found")] +pub struct NotFound; + +impl HttpError for NotFound { + fn code(&self) -> ErrorCode { + ErrorCode::NotFound + } +} + impl HttpError for sqlx::Error { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { - INTERNAL + fn code(&self) -> ErrorCode { + ErrorCode::Internal } } impl HttpError for JsonRejection { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { - let status = match self { + fn code(&self) -> ErrorCode { + ErrorCode::InvalidRequest + } + + fn status(&self) -> StatusCode { + match self { // Malformed or mistyped JSON is a bad request like any other (§15); a missing content // type or an oversized body keeps its own HTTP status. Self::JsonDataError(_) | Self::JsonSyntaxError(_) => StatusCode::BAD_REQUEST, - _ => self.status(), - }; - (status, ErrorCode::InvalidRequest) + _ => JsonRejection::status(self), + } } } impl HttpError for UsernameError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { - (StatusCode::BAD_REQUEST, ErrorCode::InvalidUsername) + fn code(&self) -> ErrorCode { + ErrorCode::InvalidUsername } } impl HttpError for OpaqueError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { + fn code(&self) -> ErrorCode { match self { // One code for wrong password and unknown account, so a username's existence never // leaks. - Self::InvalidLogin => (StatusCode::UNAUTHORIZED, ErrorCode::InvalidCredentials), - Self::Malformed => (StatusCode::BAD_REQUEST, ErrorCode::InvalidRequest), + Self::InvalidLogin => ErrorCode::InvalidCredentials, + Self::Malformed => ErrorCode::InvalidRequest, // `ReflectedValue` and `EmptyPassword` are only raised by the client half of the // protocol; seeing one here means server code called a client function. - Self::ReflectedValue | Self::EmptyPassword | Self::Protocol(_) => INTERNAL, + Self::ReflectedValue | Self::EmptyPassword | Self::Protocol(_) => ErrorCode::Internal, } } } @@ -224,15 +199,6 @@ mod tests { ); } - #[tokio::test] - async fn anyhow_errors_are_internal() { - let (status, body) = render(anyhow::anyhow!("secret detail").context("loading")).await; - - assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); - assert_eq!(body["code"], "internal"); - assert_eq!(body["message"], "internal server error"); - } - #[tokio::test] async fn database_errors_are_internal() { let (status, body) = render(sqlx::Error::RowNotFound).await; @@ -242,8 +208,8 @@ mod tests { } #[tokio::test] - async fn ad_hoc_errors_keep_status_code_and_message() { - let (status, body) = render(ServerError::not_found()).await; + async fn not_found_keeps_its_message() { + let (status, body) = render(NotFound).await; assert_eq!(status, StatusCode::NOT_FOUND); assert_eq!( @@ -257,8 +223,8 @@ mod tests { struct Challenge; impl HttpError for Challenge { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { - (StatusCode::UNAUTHORIZED, ErrorCode::InvalidCredentials) + fn code(&self) -> ErrorCode { + ErrorCode::InvalidCredentials } fn headers(&self) -> HeaderMap { diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 36d843a8b..6369dab92 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -4,7 +4,7 @@ mod extract; mod routes; mod state; -pub use error::{ErrorCode, HttpError, ServerError, ServerResult}; +pub use error::{ErrorCode, HttpError, NotFound, ServerError, ServerResult}; pub use extract::Json; pub use state::AppState; @@ -27,7 +27,7 @@ fn v1() -> Router { } async fn not_found() -> ServerError { - ServerError::not_found() + NotFound.into() } #[cfg(test)] diff --git a/rust/crates/keygo-server/src/api/routes/auth/login.rs b/rust/crates/keygo-server/src/api/routes/auth/login.rs index b64476928..e1b41300f 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/login.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/login.rs @@ -4,7 +4,6 @@ use crate::domain::{LoginId, Username}; use crate::service::login::{self, FinishLogin, StartLogin}; use axum::Router; use axum::extract::State; -use axum::http::StatusCode; use axum::routing::post; use keygo_opaque::{CredentialFinalization, CredentialRequest, CredentialResponse, DpopBinding}; use serde::{Deserialize, Serialize}; @@ -16,6 +15,16 @@ pub fn router() -> Router { .route("/finish", post(finish)) } +impl HttpError for login::Error { + fn code(&self) -> ErrorCode { + match self { + Self::Expired => ErrorCode::LoginExpired, + Self::Opaque(err) => err.code(), + Self::Db(_) => ErrorCode::Internal, + } + } +} + #[derive(Deserialize)] struct StartRequest { /// Parsed in the handler so a bad name answers `invalid_username`, not `invalid_request`. @@ -30,15 +39,6 @@ struct StartResponse { expires_in: u64, } -impl HttpError for login::StartError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { - match self { - Self::Opaque(err) => err.status_and_code(), - Self::Db(err) => err.status_and_code(), - } - } -} - async fn start( State(state): State, Json(request): Json, @@ -70,16 +70,6 @@ struct FinishResponse { username: Username, } -impl HttpError for login::FinishError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { - match self { - Self::Expired => (StatusCode::BAD_REQUEST, ErrorCode::LoginExpired), - Self::Opaque(err) => err.status_and_code(), - Self::Db(err) => err.status_and_code(), - } - } -} - async fn finish( State(state): State, proof: DpopProof, @@ -107,6 +97,7 @@ mod tests { use crate::testing::{ PASSWORD, app_state, post_to, post_with_proof, proof_post, prover, register, send, }; + use axum::http::StatusCode; use keygo_opaque::OpaqueError; use keygo_opaque::client::ClientLogin; use keygo_opaque::server::ServerSetup; @@ -143,7 +134,7 @@ mod tests { #[tokio::test] async fn expired_logins_are_bad_requests() { - let (status, body) = render(login::FinishError::Expired).await; + let (status, body) = render(login::Error::Expired).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(body["code"], "login_expired"); @@ -151,7 +142,7 @@ mod tests { #[tokio::test] async fn failed_login_finish_matches_failed_start() { - let (status, body) = render(login::FinishError::Opaque(OpaqueError::InvalidLogin)).await; + let (status, body) = render(login::Error::Opaque(OpaqueError::InvalidLogin)).await; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!(body["code"], "invalid_credentials"); diff --git a/rust/crates/keygo-server/src/api/routes/auth/register.rs b/rust/crates/keygo-server/src/api/routes/auth/register.rs index 368f51fcc..f40ad67df 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/register.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/register.rs @@ -32,16 +32,16 @@ struct StartResponse { } impl HttpError for registration::StartError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { + fn code(&self) -> ErrorCode { match self { - Self::InvalidUserId => (StatusCode::BAD_REQUEST, ErrorCode::InvalidRequest), - Self::ReservedUsername => (StatusCode::BAD_REQUEST, ErrorCode::InvalidUsername), - Self::InviteRequired => (StatusCode::FORBIDDEN, ErrorCode::InviteRequired), - Self::InviteInvalid => (StatusCode::FORBIDDEN, ErrorCode::InviteInvalid), - Self::UsernameTaken => (StatusCode::CONFLICT, ErrorCode::UsernameTaken), - Self::UserIdTaken => (StatusCode::CONFLICT, ErrorCode::UserIdTaken), - Self::Opaque(err) => err.status_and_code(), - Self::Db(err) => err.status_and_code(), + Self::InvalidUserId => ErrorCode::InvalidRequest, + Self::ReservedUsername => ErrorCode::InvalidUsername, + Self::InviteRequired => ErrorCode::InviteRequired, + Self::InviteInvalid => ErrorCode::InviteInvalid, + Self::UsernameTaken => ErrorCode::UsernameTaken, + Self::UserIdTaken => ErrorCode::UserIdTaken, + Self::Opaque(err) => err.code(), + Self::Db(_) => ErrorCode::Internal, } } } @@ -78,11 +78,11 @@ struct FinishResponse { } impl HttpError for registration::FinishError { - fn status_and_code(&self) -> (StatusCode, ErrorCode) { + fn code(&self) -> ErrorCode { match self { - Self::Expired => (StatusCode::BAD_REQUEST, ErrorCode::RegistrationExpired), - Self::InviteInvalid => (StatusCode::FORBIDDEN, ErrorCode::InviteInvalid), - Self::Db(err) => err.status_and_code(), + Self::Expired => ErrorCode::RegistrationExpired, + Self::InviteInvalid => ErrorCode::InviteInvalid, + Self::Db(_) => ErrorCode::Internal, } } } diff --git a/rust/crates/keygo-server/src/db/registrations.rs b/rust/crates/keygo-server/src/db/registrations.rs index 4727864f5..4a9c356d1 100644 --- a/rust/crates/keygo-server/src/db/registrations.rs +++ b/rust/crates/keygo-server/src/db/registrations.rs @@ -11,7 +11,7 @@ pub enum ReserveError { UserIdTaken, #[error("username is already in use")] UsernameTaken, - #[error("database error: {0}")] + #[error("database error")] Db(#[source] sqlx::Error), } diff --git a/rust/crates/keygo-server/src/service/invite/revoke.rs b/rust/crates/keygo-server/src/service/invite/revoke.rs index 975615328..e1464f697 100644 --- a/rust/crates/keygo-server/src/service/invite/revoke.rs +++ b/rust/crates/keygo-server/src/service/invite/revoke.rs @@ -10,7 +10,7 @@ pub enum RevokeError { NotFound(InviteId), #[error("{id} matches {} open invites, nothing revoked", matches.len())] Ambiguous { id: InviteId, matches: Vec }, - #[error("database error: {0}")] + #[error("database error")] Db(#[from] sqlx::Error), } diff --git a/rust/crates/keygo-server/src/service/login/finish.rs b/rust/crates/keygo-server/src/service/login/finish.rs index 6c7401a11..3ced56dd4 100644 --- a/rust/crates/keygo-server/src/service/login/finish.rs +++ b/rust/crates/keygo-server/src/service/login/finish.rs @@ -1,21 +1,11 @@ use crate::cache::LoginStates; use crate::db::users; use crate::domain::{LoginId, Username}; +use crate::service::login::Error; use keygo_opaque::{CredentialFinalization, DpopBinding, OpaqueError}; use sqlx::PgPool; -use thiserror::Error; use uuid::Uuid; -#[derive(Debug, Error)] -pub enum FinishError { - #[error("login expired or unknown")] - Expired, - #[error(transparent)] - Opaque(#[from] OpaqueError), - #[error("database error: {0}")] - Db(#[from] sqlx::Error), -} - pub struct FinishLogin { pub login_id: LoginId, pub credential_finalization: CredentialFinalization, @@ -35,7 +25,7 @@ pub async fn finish( db: &PgPool, login_states: &LoginStates, input: FinishLogin, -) -> Result { +) -> Result { let FinishLogin { login_id, credential_finalization, @@ -43,7 +33,7 @@ pub async fn finish( jkt, } = input; - let pending = login_states.take(&login_id).ok_or(FinishError::Expired)?; + let pending = login_states.take(&login_id).ok_or(Error::Expired)?; let session_key = pending.state.finish(credential_finalization)?; session_key.verify_dpop_binding(&jkt, &binding)?; @@ -106,7 +96,7 @@ mod tests { let err = finish(&db, &login_states, replay).await.err().unwrap(); - assert!(matches!(err, FinishError::Expired), "{err:?}"); + assert!(matches!(err, Error::Expired), "{err:?}"); } #[sqlx::test] @@ -126,10 +116,10 @@ mod tests { let retried = finish(&db, &login_states, retry).await.err().unwrap(); assert!( - matches!(err, FinishError::Opaque(OpaqueError::InvalidLogin)), + matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), "{err:?}" ); - assert!(matches!(retried, FinishError::Expired), "{retried:?}"); + assert!(matches!(retried, Error::Expired), "{retried:?}"); } #[sqlx::test] @@ -146,7 +136,7 @@ mod tests { let err = finish(&db, &login_states, input).await.err().unwrap(); assert!( - matches!(err, FinishError::Opaque(OpaqueError::InvalidLogin)), + matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), "{err:?}" ); assert_eq!(login_states.count(), 0); @@ -197,7 +187,7 @@ mod tests { let err = finish(&db, &login_states, input).await.err().unwrap(); assert!( - matches!(err, FinishError::Opaque(OpaqueError::InvalidLogin)), + matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), "{err:?}" ); } @@ -220,7 +210,7 @@ mod tests { .unwrap(); assert!( - matches!(err, FinishError::Opaque(OpaqueError::InvalidLogin)), + matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), "{err:?}" ); } @@ -238,7 +228,7 @@ mod tests { let err = finish(&db, &login_states, input).await.err().unwrap(); - assert!(matches!(err, FinishError::Expired), "{err:?}"); + assert!(matches!(err, Error::Expired), "{err:?}"); assert_eq!(login_states.count(), 1); } @@ -255,6 +245,6 @@ mod tests { .err() .unwrap(); - assert!(matches!(err, FinishError::Expired), "{err:?}"); + assert!(matches!(err, Error::Expired), "{err:?}"); } } diff --git a/rust/crates/keygo-server/src/service/login/mod.rs b/rust/crates/keygo-server/src/service/login/mod.rs index 2ff91e503..0a3af0c21 100644 --- a/rust/crates/keygo-server/src/service/login/mod.rs +++ b/rust/crates/keygo-server/src/service/login/mod.rs @@ -4,6 +4,17 @@ mod start; pub use finish::*; pub use start::*; +use keygo_opaque::OpaqueError; use std::time::Duration; pub const TTL: Duration = Duration::from_mins(1); + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("login expired or unknown")] + Expired, + #[error(transparent)] + Opaque(#[from] OpaqueError), + #[error("database error")] + Db(#[from] sqlx::Error), +} diff --git a/rust/crates/keygo-server/src/service/login/start.rs b/rust/crates/keygo-server/src/service/login/start.rs index 5e5c20a17..b21489fa0 100644 --- a/rust/crates/keygo-server/src/service/login/start.rs +++ b/rust/crates/keygo-server/src/service/login/start.rs @@ -1,20 +1,11 @@ use crate::cache::{LoginStates, Pending}; use crate::db::opaque_records; use crate::domain::{LoginId, Username}; -use crate::service::login::TTL; +use crate::service::login::{Error, TTL}; use keygo_opaque::server::{ServerLogin, ServerSetup}; -use keygo_opaque::{CredentialRequest, CredentialResponse, OpaqueError}; +use keygo_opaque::{CredentialRequest, CredentialResponse}; use sqlx::PgPool; use std::time::Duration; -use thiserror::Error; - -#[derive(Debug, Error)] -pub enum StartError { - #[error(transparent)] - Opaque(#[from] OpaqueError), - #[error("database error: {0}")] - Db(#[from] sqlx::Error), -} pub struct StartLogin { pub username: Username, @@ -37,7 +28,7 @@ pub async fn start( login_states: &LoginStates, setup: &ServerSetup, input: StartLogin, -) -> Result { +) -> Result { let StartLogin { username, credential_request, diff --git a/rust/crates/keygo-server/src/service/registration/finish.rs b/rust/crates/keygo-server/src/service/registration/finish.rs index f0953c7e5..4c216e54d 100644 --- a/rust/crates/keygo-server/src/service/registration/finish.rs +++ b/rust/crates/keygo-server/src/service/registration/finish.rs @@ -10,7 +10,7 @@ pub enum FinishError { Expired, #[error("invite is not valid or has expired")] InviteInvalid, - #[error("database error: {0}")] + #[error("database error")] Db(#[from] sqlx::Error), } diff --git a/rust/crates/keygo-server/src/service/registration/start.rs b/rust/crates/keygo-server/src/service/registration/start.rs index 83c071648..cf4e931d9 100644 --- a/rust/crates/keygo-server/src/service/registration/start.rs +++ b/rust/crates/keygo-server/src/service/registration/start.rs @@ -25,7 +25,7 @@ pub enum StartError { UserIdTaken, #[error(transparent)] Opaque(#[from] OpaqueError), - #[error("database error: {0}")] + #[error("database error")] Db(#[from] sqlx::Error), } From 5d6eb87fdecd051dbf2843c84a747ea35252a914 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 24 Oct 2026 21:52:12 +0200 Subject: [PATCH 10/26] docs: drop internal spec section references from comments --- rust/crates/keygo-dpop/src/nonce.rs | 2 +- rust/crates/keygo-dpop/src/verify.rs | 6 +++--- rust/crates/keygo-server/src/api/error.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/rust/crates/keygo-dpop/src/nonce.rs b/rust/crates/keygo-dpop/src/nonce.rs index 765475fc9..a508cdbbf 100644 --- a/rust/crates/keygo-dpop/src/nonce.rs +++ b/rust/crates/keygo-dpop/src/nonce.rs @@ -9,7 +9,7 @@ use zeroize::Zeroizing; const NONCE_LIFETIME: Duration = Duration::from_mins(5); const TIMESTAMP_LEN: usize = size_of::(); -/// HMAC-SHA256 truncated to its leftmost 16 bytes (spec §10). +/// HMAC-SHA256 truncated to its leftmost 16 bytes. const TAG_LEN: usize = 16; const NONCE_LEN: usize = TIMESTAMP_LEN + TAG_LEN; diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index 53da513a4..4ca7a598e 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -18,9 +18,9 @@ pub struct Expected<'a> { pub jkt: Option<&'a [u8; 32]>, } -/// What went wrong, grouped by how the server answers (spec §10, §15). The 400/401 split is the -/// endpoint's, not the error's: token-issuing endpoints answer 400, everything else 401 with a -/// `WWW-Authenticate: DPoP` challenge. +/// What went wrong, grouped by how the server answers. The 400/401 split is the endpoint's, not the +/// error's: token-issuing endpoints answer 400, everything else 401 with a `WWW-Authenticate: DPoP` +/// challenge. #[derive(Debug, Error)] pub enum VerifyError { /// Answer `invalid_dpop_proof`. The reason is for logs only; the client reacts to every one diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index 5f7b7ceba..767500a3c 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -114,8 +114,8 @@ impl HttpError for JsonRejection { fn status(&self) -> StatusCode { match self { - // Malformed or mistyped JSON is a bad request like any other (§15); a missing content - // type or an oversized body keeps its own HTTP status. + // Malformed or mistyped JSON is a bad request like any other; a missing content type or + // an oversized body keeps its own HTTP status. Self::JsonDataError(_) | Self::JsonSyntaxError(_) => StatusCode::BAD_REQUEST, _ => JsonRejection::status(self), } From 4265767ba4d74fcd6f777fbb2ac6b1458198e3cc Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sun, 25 Oct 2026 11:51:25 +0100 Subject: [PATCH 11/26] feat(api): add device info --- rust/Cargo.lock | 1 + ...db2379782897daa733902917e64f3e811c940.json | 18 ++ rust/crates/keygo-server/Cargo.toml | 1 + .../migrations/20261014141017_init.sql | 11 + .../src/api/routes/auth/register.rs | 143 +++++++---- rust/crates/keygo-server/src/db/devices.rs | 24 ++ rust/crates/keygo-server/src/db/mod.rs | 1 + rust/crates/keygo-server/src/domain/device.rs | 233 ++++++++++++++++++ rust/crates/keygo-server/src/domain/mod.rs | 2 + .../src/service/registration/finish.rs | 44 +++- rust/crates/keygo-server/src/testing.rs | 11 +- 11 files changed, 428 insertions(+), 61 deletions(-) create mode 100644 rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json create mode 100644 rust/crates/keygo-server/src/db/devices.rs create mode 100644 rust/crates/keygo-server/src/domain/device.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 9e387e28d..ae5673066 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1687,6 +1687,7 @@ dependencies = [ "tracing", "tracing-subscriber", "unicode-normalization", + "unicode-properties", "url", "uuid", "zeroize", diff --git a/rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json b/rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json new file mode 100644 index 000000000..ca4a9166b --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "insert into devices (id, user_id, name, platform, app_version)\n values ($1, $2, $3, $4, $5)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940" +} diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 0f64da62f..5dab0d760 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -31,6 +31,7 @@ tower-http = { version = "0.7.1", features = ["trace"] } uuid = { workspace = true, features = ["v4"] } sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "postgres", "migrate", "macros", "uuid", "time"] } unicode-normalization = "0.1.25" +unicode-properties = { version = "0.1.4", default-features = false, features = ["general-category"] } humantime = "2.4.0" hmac = "0.13.0" sha2 = { version = "0.11.0", features = ["zeroize"] } diff --git a/rust/crates/keygo-server/migrations/20261014141017_init.sql b/rust/crates/keygo-server/migrations/20261014141017_init.sql index edebc33c8..b4e7aec32 100644 --- a/rust/crates/keygo-server/migrations/20261014141017_init.sql +++ b/rust/crates/keygo-server/migrations/20261014141017_init.sql @@ -5,6 +5,17 @@ create table users created_at timestamptz not null default now() ); +create table devices +( + id uuid primary key, + user_id uuid not null references users on delete cascade, + name text not null, + platform text not null, + app_version text not null, + created_at timestamptz not null default now(), + last_seen_at timestamptz not null default now() +); + create table invites ( code_hash bytea primary key, diff --git a/rust/crates/keygo-server/src/api/routes/auth/register.rs b/rust/crates/keygo-server/src/api/routes/auth/register.rs index f40ad67df..6f254be8f 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/register.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/register.rs @@ -1,5 +1,6 @@ +use crate::api::dpop::DpopProof; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; -use crate::domain::{RegistrationId, Username}; +use crate::domain::{DeviceInfo, RegistrationId, Username}; use crate::service::registration::{self, FinishRegistration, StartRegistration}; use axum::Router; use axum::extract::State; @@ -70,6 +71,7 @@ async fn start( struct FinishRequest { registration_id: RegistrationId, registration_upload: RegistrationUpload, + device: DeviceInfo, } #[derive(Serialize)] @@ -89,11 +91,14 @@ impl HttpError for registration::FinishError { async fn finish( State(state): State, + // TODO: bind the new session to `proof.jkt` + _proof: DpopProof, Json(request): Json, ) -> ServerResult<(StatusCode, Json)> { let input = FinishRegistration { registration_id: request.registration_id, registration_upload: request.registration_upload, + device_info: request.device, }; let finished = registration::finish(&state.db, input).await?; @@ -110,7 +115,10 @@ async fn finish( mod tests { use super::*; use crate::api::error::render; - use crate::testing::{app_state, count, create_invite, invite_only, post, post_to, register}; + use crate::testing::{ + app_state, count, create_invite, device_json, invite_only, post, post_to, post_with_proof, + proof_post, prover, register, send, + }; use keygo_opaque::client::ClientRegistration; use keygo_opaque::server::ServerSetup; use serde_json::{Value, json}; @@ -129,6 +137,21 @@ mod tests { (client, body) } + fn finish_body(client: ClientRegistration, started: &Value) -> Value { + let response = + RegistrationResponse::from_base64(started["registration_response"].as_str().unwrap()) + .unwrap(); + let upload = client + .finish(crate::testing::PASSWORD, response) + .unwrap() + .upload; + json!({ + "registration_id": started["registration_id"], + "registration_upload": upload.to_base64(), + "device": device_json(), + }) + } + #[tokio::test] async fn expired_registrations_are_bad_requests() { let (status, body) = render(registration::FinishError::Expired).await; @@ -147,31 +170,21 @@ mod tests { #[sqlx::test] async fn registers_over_http(db: PgPool) { - let setup = ServerSetup::generate(); - let user_id = Uuid::new_v4(); - let (client, body) = start_body("Ada", user_id); + let state = app_state(&db, &ServerSetup::generate()); + let (client, body) = start_body("Ada", Uuid::new_v4()); - let (status, started) = post(&db, &setup, START, body).await; + let (status, started) = post_to(state.clone(), START, body).await; assert_eq!(status, StatusCode::OK); assert_eq!(started["expires_in"], registration::TTL.as_secs()); - let response = - RegistrationResponse::from_base64(started["registration_response"].as_str().unwrap()) - .unwrap(); - let upload = client - .finish(crate::testing::PASSWORD, response) - .unwrap() - .upload; - let body = json!({ - "registration_id": started["registration_id"], - "registration_upload": upload.to_base64(), - }); + let body = finish_body(client, &started); - let (status, finished) = post(&db, &setup, FINISH, body).await; + let (status, finished) = post_with_proof(&state, &prover(), FINISH, body).await; assert_eq!(status, StatusCode::CREATED); assert_eq!(finished, json!({ "username": "ada" })); assert_eq!(count(&db, "users").await, 1); + assert_eq!(count(&db, "devices").await, 1); } fn invite_only_state(db: &PgPool, setup: &ServerSetup) -> AppState { @@ -183,26 +196,17 @@ mod tests { #[sqlx::test] async fn registers_with_an_invite_over_http(db: PgPool) { - let setup = ServerSetup::generate(); let (client, mut body) = start_body("ada", Uuid::new_v4()); body["invite"] = create_invite(&db).await.into(); - let (status, started) = post_to(invite_only_state(&db, &setup), START, body).await; + let state = invite_only_state(&db, &ServerSetup::generate()); + + let (status, started) = post_to(state.clone(), START, body).await; assert_eq!(status, StatusCode::OK); - let response = - RegistrationResponse::from_base64(started["registration_response"].as_str().unwrap()) - .unwrap(); - let upload = client - .finish(crate::testing::PASSWORD, response) - .unwrap() - .upload; - let body = json!({ - "registration_id": started["registration_id"], - "registration_upload": upload.to_base64(), - }); + let body = finish_body(client, &started); - let (status, _) = post_to(invite_only_state(&db, &setup), FINISH, body).await; + let (status, _) = post_with_proof(&state, &prover(), FINISH, body).await; assert_eq!(status, StatusCode::CREATED); assert_eq!(count(&db, "users").await, 1); @@ -330,25 +334,72 @@ mod tests { #[sqlx::test] async fn finish_rejects_an_unknown_registration(db: PgPool) { - let setup = ServerSetup::generate(); + let state = app_state(&db, &ServerSetup::generate()); let (client, body) = start_body("ada", Uuid::new_v4()); - let (_, started) = post(&db, &setup, START, body).await; - let response = - RegistrationResponse::from_base64(started["registration_response"].as_str().unwrap()) - .unwrap(); - let upload = client - .finish(crate::testing::PASSWORD, response) - .unwrap() - .upload; - let body = json!({ - "registration_id": RegistrationId::random(), - "registration_upload": upload.to_base64(), - }); + let (_, started) = post_to(state.clone(), START, body).await; + let mut body = finish_body(client, &started); + body["registration_id"] = json!(RegistrationId::random()); - let (status, body) = post(&db, &setup, FINISH, body).await; + let (status, body) = post_with_proof(&state, &prover(), FINISH, body).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(body["code"], "registration_expired"); assert_eq!(count(&db, "users").await, 0); } + + #[sqlx::test] + async fn finish_rejects_a_spoofing_device_name(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let (client, body) = start_body("ada", Uuid::new_v4()); + let (_, started) = post_to(state.clone(), START, body).await; + let mut body = finish_body(client, &started); + body["device"]["name"] = "Pixel\u{202E}9".into(); + + let (status, body) = post_with_proof(&state, &prover(), FINISH, body).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "invalid_request"); + assert_eq!(count(&db, "pending_registrations").await, 1); + } + + #[sqlx::test] + async fn finish_without_a_proof_keeps_the_registration(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let (client, body) = start_body("ada", Uuid::new_v4()); + let (_, started) = post_to(state.clone(), START, body).await; + let body = finish_body(client, &started); + + let (status, response) = post_to(state.clone(), FINISH, body.clone()).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(response["code"], "invalid_dpop_proof"); + assert_eq!(count(&db, "pending_registrations").await, 1); + + let (status, _) = post_with_proof(&state, &prover(), FINISH, body).await; + + assert_eq!(status, StatusCode::CREATED); + } + + #[sqlx::test] + async fn nonce_challenge_keeps_the_registration(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let (client, body) = start_body("ada", Uuid::new_v4()); + let (_, started) = post_to(state.clone(), START, body).await; + let body = finish_body(client, &started); + let prover = prover(); + + // A verifier that just started accepts no proof without one of its own nonces. + let request = proof_post(&state, &prover, FINISH, &body, None); + let (status, headers, challenge) = send(&state, request).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(challenge["code"], "use_dpop_nonce"); + assert!(headers.contains_key("dpop-nonce")); + assert_eq!(count(&db, "pending_registrations").await, 1); + + let (status, _) = post_with_proof(&state, &prover, FINISH, body).await; + + assert_eq!(status, StatusCode::CREATED); + assert_eq!(count(&db, "users").await, 1); + } } diff --git a/rust/crates/keygo-server/src/db/devices.rs b/rust/crates/keygo-server/src/db/devices.rs new file mode 100644 index 000000000..22094a58e --- /dev/null +++ b/rust/crates/keygo-server/src/db/devices.rs @@ -0,0 +1,24 @@ +use crate::domain::{DeviceId, DeviceInfo}; +use sqlx::PgConnection; +use uuid::Uuid; + +pub async fn insert( + conn: &mut PgConnection, + id: DeviceId, + user_id: Uuid, + device_info: &DeviceInfo, +) -> sqlx::Result<()> { + sqlx::query!( + "insert into devices (id, user_id, name, platform, app_version) + values ($1, $2, $3, $4, $5)", + id.as_uuid(), + user_id, + device_info.name.as_str(), + device_info.platform.as_str(), + device_info.app_version.as_str(), + ) + .execute(conn) + .await?; + + Ok(()) +} diff --git a/rust/crates/keygo-server/src/db/mod.rs b/rust/crates/keygo-server/src/db/mod.rs index 5e5d25879..b4ac5c784 100644 --- a/rust/crates/keygo-server/src/db/mod.rs +++ b/rust/crates/keygo-server/src/db/mod.rs @@ -1,3 +1,4 @@ +pub mod devices; pub mod invites; pub mod opaque_records; pub mod registrations; diff --git a/rust/crates/keygo-server/src/domain/device.rs b/rust/crates/keygo-server/src/domain/device.rs new file mode 100644 index 000000000..036ed7226 --- /dev/null +++ b/rust/crates/keygo-server/src/domain/device.rs @@ -0,0 +1,233 @@ +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; +use uuid::Uuid; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Platform { + Android, +} + +impl Platform { + pub const fn as_str(self) -> &'static str { + match self { + Self::Android => "android", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct DeviceId(Uuid); + +impl DeviceId { + pub fn random() -> Self { + Self(Uuid::new_v4()) + } + + pub const fn as_uuid(self) -> Uuid { + self.0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum DeviceNameError { + #[error("device name must not be blank")] + Blank, + #[error("device name must be at most {} characters", DeviceName::MAX_LEN)] + TooLong, + #[error("device name must not contain {0:?}")] + InvalidCharacter(char), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "String")] +pub struct DeviceName(String); + +impl DeviceName { + pub const MAX_LEN: usize = 64; + + pub fn parse(raw: impl AsRef) -> Result { + let name = raw.as_ref().trim(); + if name.is_empty() { + return Err(DeviceNameError::Blank); + } + if name.chars().count() > Self::MAX_LEN { + return Err(DeviceNameError::TooLong); + } + if let Some(c) = name.chars().find(|&c| is_hidden(c)) { + return Err(DeviceNameError::InvalidCharacter(c)); + } + Ok(Self(name.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Control characters and invisible formatting ones (bidi overrides, zero-width characters, line +/// separators): in the devices list they would let one name pose as another. +fn is_hidden(c: char) -> bool { + matches!( + c.general_category(), + GeneralCategory::Control + | GeneralCategory::Format + | GeneralCategory::LineSeparator + | GeneralCategory::ParagraphSeparator + ) +} + +impl TryFrom for DeviceName { + type Error = DeviceNameError; + fn try_from(value: String) -> Result { + Self::parse(value) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum AppVersionError { + #[error("app version must be 1 to {} characters", AppVersion::MAX_LEN)] + InvalidLength, + #[error("app version must not contain {0:?}")] + InvalidCharacter(char), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "String")] +pub struct AppVersion(String); + +impl AppVersion { + pub const MAX_LEN: usize = 32; + + pub fn parse(raw: impl AsRef) -> Result { + let version = raw.as_ref(); + if version.is_empty() || version.len() > Self::MAX_LEN { + return Err(AppVersionError::InvalidLength); + } + if let Some(c) = version + .chars() + .find(|&c| !c.is_ascii_alphanumeric() && !matches!(c, '.' | '+' | '-')) + { + return Err(AppVersionError::InvalidCharacter(c)); + } + Ok(Self(version.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl TryFrom for AppVersion { + type Error = AppVersionError; + fn try_from(value: String) -> Result { + Self::parse(value) + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DeviceInfo { + pub name: DeviceName, + pub platform: Platform, + pub app_version: AppVersion, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Device { + #[serde(rename = "device_id", skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(flatten)] + pub info: DeviceInfo, +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn device_name_is_trimmed() { + assert_eq!( + DeviceName::parse(" Pixel 9\t").unwrap().as_str(), + "Pixel 9" + ); + } + + #[test] + fn device_name_accepts_any_visible_text() { + for raw in ["Ada's Pixel", "Pixel 9 Pro (Arbeit)", "Телефон", "手机 📱"] { + assert_eq!(DeviceName::parse(raw).unwrap().as_str(), raw); + } + } + + #[test] + fn device_name_enforces_length_bounds() { + let max = DeviceName::MAX_LEN; + assert!(DeviceName::parse("é".repeat(max)).is_ok()); + assert_eq!(DeviceName::parse(""), Err(DeviceNameError::Blank)); + assert_eq!(DeviceName::parse(" \n "), Err(DeviceNameError::Blank)); + assert_eq!( + DeviceName::parse("a".repeat(max + 1)), + Err(DeviceNameError::TooLong), + ); + } + + #[test] + fn device_name_rejects_hidden_characters() { + for c in [ + '\n', + '\0', + '\u{7F}', + '\u{200B}', + '\u{202E}', + '\u{2066}', + '\u{FEFF}', + '\u{2029}', + '\u{E0041}', + ] { + assert_eq!( + DeviceName::parse(format!("Pixel{c}9")), + Err(DeviceNameError::InvalidCharacter(c)), + ); + } + } + + #[test] + fn app_version_accepts_semver() { + for raw in ["2.3.0", "2.3.0-beta.1+42", "v2"] { + assert_eq!(AppVersion::parse(raw).unwrap().as_str(), raw); + } + } + + #[test] + fn app_version_enforces_length_bounds() { + let max = AppVersion::MAX_LEN; + assert!(AppVersion::parse("1".repeat(max)).is_ok()); + assert_eq!(AppVersion::parse(""), Err(AppVersionError::InvalidLength)); + assert_eq!( + AppVersion::parse("1".repeat(max + 1)), + Err(AppVersionError::InvalidLength), + ); + } + + #[test] + fn app_version_rejects_other_characters() { + for c in [' ', '\n', '/', 'é'] { + assert_eq!( + AppVersion::parse(format!("2.3{c}0")), + Err(AppVersionError::InvalidCharacter(c)), + ); + } + } + + #[test] + fn device_info_validates_while_deserializing() { + let bad_name = + json!({ "name": "\u{202E}9 lexiP", "platform": "android", "app_version": "2.3.0" }); + let bad_platform = json!({ "name": "Pixel 9", "platform": "ios", "app_version": "2.3.0" }); + + assert!(serde_json::from_value::(bad_name).is_err()); + assert!(serde_json::from_value::(bad_platform).is_err()); + } +} diff --git a/rust/crates/keygo-server/src/domain/mod.rs b/rust/crates/keygo-server/src/domain/mod.rs index 833299199..932fc72c8 100644 --- a/rust/crates/keygo-server/src/domain/mod.rs +++ b/rust/crates/keygo-server/src/domain/mod.rs @@ -1,9 +1,11 @@ +mod device; mod invite_code; mod invite_hash; mod invite_id; mod random_id; mod username; +pub use device::{DeviceId, DeviceInfo}; pub use invite_code::{InviteCode, InvitePepper}; pub use invite_hash::InviteHash; pub use invite_id::InviteId; diff --git a/rust/crates/keygo-server/src/service/registration/finish.rs b/rust/crates/keygo-server/src/service/registration/finish.rs index 4c216e54d..47b338b41 100644 --- a/rust/crates/keygo-server/src/service/registration/finish.rs +++ b/rust/crates/keygo-server/src/service/registration/finish.rs @@ -1,5 +1,5 @@ -use crate::db::{invites, opaque_records, registrations, users}; -use crate::domain::{RegistrationId, Username}; +use crate::db::{devices, invites, opaque_records, registrations, users}; +use crate::domain::{DeviceId, DeviceInfo, RegistrationId, Username}; use keygo_opaque::{RegistrationUpload, server}; use sqlx::PgPool; use thiserror::Error; @@ -17,7 +17,8 @@ pub enum FinishError { pub struct FinishRegistration { pub registration_id: RegistrationId, pub registration_upload: RegistrationUpload, - // TODO: key bundle + device info + pub device_info: DeviceInfo, + // TODO: key bundle } pub struct Finished { @@ -29,6 +30,7 @@ pub async fn finish(db: &PgPool, input: FinishRegistration) -> Result Result Result (i64, i64, i64) { + async fn user_count(db: &PgPool) -> (i64, i64, i64, i64) { ( count(db, "users").await, count(db, "opaque_records").await, + count(db, "devices").await, count(db, "pending_registrations").await, ) } @@ -111,12 +120,20 @@ mod tests { let finished = finish(&db, input).await.unwrap(); assert_eq!(finished.username, username("ada")); - assert_eq!(user_count(&db).await, (1, 1, 0)); + assert_eq!(user_count(&db).await, (1, 1, 1, 0)); let stored: (Uuid, String) = sqlx::query_as("select id, username from users") .fetch_one(&db) .await .unwrap(); assert_eq!(stored, (user_id, "ada".to_owned())); + let device: (Uuid, String, String, String) = + sqlx::query_as("select user_id, name, platform, app_version from devices") + .fetch_one(&db) + .await + .unwrap(); + let expected = ["Pixel 9", "android", "2.3.0"].map(str::to_owned); + assert_eq!((device.1, device.2, device.3), expected.into()); + assert_eq!(device.0, user_id); } #[sqlx::test] @@ -128,13 +145,14 @@ mod tests { &input.registration_upload.to_bytes(), ) .unwrap(), + device_info: device_info(), }; finish(&db, input).await.unwrap(); let err = finish(&db, replay).await.err().unwrap(); assert!(matches!(err, FinishError::Expired), "{err:?}"); - assert_eq!(user_count(&db).await, (1, 1, 0)); + assert_eq!(user_count(&db).await, (1, 1, 1, 0)); } #[sqlx::test] @@ -148,7 +166,7 @@ mod tests { let err = finish(&db, unknown).await.err().unwrap(); assert!(matches!(err, FinishError::Expired), "{err:?}"); - assert_eq!(user_count(&db).await, (0, 0, 1)); + assert_eq!(user_count(&db).await, (0, 0, 0, 1)); } #[sqlx::test] @@ -159,7 +177,7 @@ mod tests { let err = finish(&db, input).await.err().unwrap(); assert!(matches!(err, FinishError::Expired), "{err:?}"); - assert_eq!(user_count(&db).await, (0, 0, 1)); + assert_eq!(user_count(&db).await, (0, 0, 0, 1)); } #[sqlx::test] @@ -175,7 +193,7 @@ mod tests { let err = finish(&db, input).await.err().unwrap(); assert!(matches!(err, FinishError::Db(_)), "{err:?}"); - assert_eq!(user_count(&db).await, (1, 0, 1)); + assert_eq!(user_count(&db).await, (1, 0, 0, 1)); } #[sqlx::test] @@ -185,7 +203,7 @@ mod tests { finish(&db, input).await.unwrap(); - assert_eq!(user_count(&db).await, (1, 1, 0)); + assert_eq!(user_count(&db).await, (1, 1, 1, 0)); assert_eq!(count(&db, "invites").await, 0); } @@ -199,7 +217,7 @@ mod tests { let err = finish(&db, bob).await.err().unwrap(); assert!(matches!(err, FinishError::InviteInvalid), "{err:?}"); - assert_eq!(user_count(&db).await, (1, 1, 1)); + assert_eq!(user_count(&db).await, (1, 1, 1, 1)); } #[sqlx::test] @@ -211,7 +229,7 @@ mod tests { let err = finish(&db, input).await.err().unwrap(); assert!(matches!(err, FinishError::InviteInvalid), "{err:?}"); - assert_eq!(user_count(&db).await, (0, 0, 1)); + assert_eq!(user_count(&db).await, (0, 0, 0, 1)); assert_eq!(count(&db, "invites").await, 1); } diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index bd573acfc..218033327 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -1,7 +1,7 @@ use crate::api::{AppState, router}; use crate::cache::LoginStates; use crate::db::invites; -use crate::domain::{InviteHash, InvitePepper, Username}; +use crate::domain::{DeviceInfo, InviteHash, InvitePepper, Username}; use crate::service::invite; use crate::service::login::{self, FinishLogin, StartLogin}; use crate::service::registration::{self, FinishRegistration, Signup, StartRegistration}; @@ -13,7 +13,7 @@ use keygo_dpop::verify::DpopVerifier; use keygo_dpop::{DpopProver, Htm, NonceKey, ProofRequest}; use keygo_opaque::client::{ClientLogin, ClientRegistration}; use keygo_opaque::server::ServerSetup; -use serde_json::Value; +use serde_json::{Value, json}; use sqlx::{AssertSqlSafe, PgPool}; use std::sync::Arc; use std::time::Duration; @@ -26,6 +26,12 @@ const JKT: [u8; 32] = [7; 32]; pub fn username(raw: &str) -> Username { Username::parse(raw).unwrap() } +pub fn device_json() -> Value { + json!({ "name": "Pixel 9", "platform": "android", "app_version": "2.3.0" }) +} +pub fn device_info() -> DeviceInfo { + serde_json::from_value(device_json()).unwrap() +} pub async fn register(db: &PgPool, setup: &ServerSetup, name: &str) -> Uuid { let user_id = Uuid::new_v4(); let (client, registration_request) = ClientRegistration::start(PASSWORD).unwrap(); @@ -46,6 +52,7 @@ pub async fn register(db: &PgPool, setup: &ServerSetup, name: &str) -> Uuid { let input = FinishRegistration { registration_id: started.registration_id, registration_upload: finish.upload, + device_info: device_info(), }; registration::finish(db, input).await.unwrap(); From 690439eda30ffa10fa561de53323d65a4e163eb4 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 27 Oct 2026 18:23:59 +0100 Subject: [PATCH 12/26] feat(tokens): add session tokens commit 0b6419d1f8fe3e2a9121afad3df76ec2035f8149 Author: Davis Date: Tue Oct 27 18:02:51 2026 +0100 feat(api): issue access token on login commit 388d24e8159b504f776e0c3d02d34541c887fcaf Author: Davis Date: Tue Oct 27 15:31:01 2026 +0100 fix(access_token): use parsed issuer commit d60ac9b22ea23ed1b7d3647d788d8ce80bbd1176 Author: Davis Date: Tue Oct 27 13:52:45 2026 +0100 feat(api): issue access token on register commit e2b371d1bb74848d7720484f3af2e1cf06bdfa57 Author: Davis Date: Tue Oct 27 12:33:47 2026 +0100 feat(api): add access token structure commit 29a1d4dda9ff150cdf9332dc9a2e0b5e08699471 Author: Davis Wolfermann Date: Sun Oct 25 16:52:32 2026 +0100 fix(tests): make tests pass and add new tests commit 4f6a9c985362aee858020bd35fc5ad03ee596980 Author: Davis Wolfermann Date: Sun Oct 25 16:42:06 2026 +0100 feat(api): wire-up session commit a6fd4f7aead4e1698872517834fd108f5311fe36 Author: Davis Wolfermann Date: Sun Oct 25 16:16:30 2026 +0100 feat(service): add session service commit 15c4e03f92631c14d0b6e4211db40d24422a42ef Author: Davis Wolfermann Date: Sun Oct 25 16:00:00 2026 +0100 feat(db): add session insert fn --- rust/Cargo.lock | 1 + rust/crates/keygo-dpop/src/nonce.rs | 8 +- rust/crates/keygo-dpop/src/verify.rs | 2 +- ...2e9d47ad15b0c02943c181293f3092c2483a7.json | 16 + ...5e8fac40faa2f8b6e019018f4f97b8b4cd352.json | 19 + ...7632489942012f1e4f3eb128ed078b6b66d70.json | 18 + ...293e2030d65d5afeda0a6c8784a4e184ced52.json | 15 + ...26f11cb76275d9fe14b92654d10dfa82d0f6.json} | 4 +- rust/crates/keygo-server/Cargo.toml | 1 + .../migrations/20261014141017_init.sql | 23 + rust/crates/keygo-server/src/api/mod.rs | 5 +- .../keygo-server/src/api/routes/auth/login.rs | 97 ++- .../keygo-server/src/api/routes/auth/mod.rs | 1 + .../src/api/routes/auth/register.rs | 52 +- .../src/api/routes/auth/session.rs | 24 + rust/crates/keygo-server/src/api/state.rs | 7 +- rust/crates/keygo-server/src/config.rs | 6 +- rust/crates/keygo-server/src/db/devices.rs | 22 + rust/crates/keygo-server/src/db/mod.rs | 2 + .../keygo-server/src/db/refresh_tokens.rs | 109 ++++ rust/crates/keygo-server/src/db/sessions.rs | 216 +++++++ .../keygo-server/src/domain/access_token.rs | 611 ++++++++++++++++++ .../keygo-server/src/domain/invite_code.rs | 6 +- rust/crates/keygo-server/src/domain/mod.rs | 6 +- .../crates/keygo-server/src/domain/session.rs | 111 ++++ rust/crates/keygo-server/src/secrets.rs | 26 +- .../crates/keygo-server/src/service/device.rs | 153 +++++ .../keygo-server/src/service/invite/create.rs | 2 +- .../keygo-server/src/service/login/finish.rs | 240 ++++++- rust/crates/keygo-server/src/service/mod.rs | 2 + .../src/service/registration/finish.rs | 72 ++- .../keygo-server/src/service/session.rs | 201 ++++++ rust/crates/keygo-server/src/testing.rs | 53 +- 33 files changed, 2051 insertions(+), 80 deletions(-) create mode 100644 rust/crates/keygo-server/.sqlx/query-7e72ddd24d19ed2e6e1b602f9302e9d47ad15b0c02943c181293f3092c2483a7.json create mode 100644 rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json create mode 100644 rust/crates/keygo-server/.sqlx/query-c4ee662f47c4aff1ebb955475f17632489942012f1e4f3eb128ed078b6b66d70.json create mode 100644 rust/crates/keygo-server/.sqlx/query-f4a6d574c44aedc437900062dba293e2030d65d5afeda0a6c8784a4e184ced52.json rename rust/crates/keygo-server/.sqlx/{query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json => query-fe7cc39f3f5ac35261f000ad298f26f11cb76275d9fe14b92654d10dfa82d0f6.json} (67%) create mode 100644 rust/crates/keygo-server/src/api/routes/auth/session.rs create mode 100644 rust/crates/keygo-server/src/db/refresh_tokens.rs create mode 100644 rust/crates/keygo-server/src/db/sessions.rs create mode 100644 rust/crates/keygo-server/src/domain/access_token.rs create mode 100644 rust/crates/keygo-server/src/domain/session.rs create mode 100644 rust/crates/keygo-server/src/service/device.rs create mode 100644 rust/crates/keygo-server/src/service/session.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index ae5673066..369bc094e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1665,6 +1665,7 @@ dependencies = [ "axum", "base64 0.23.1", "clap", + "ed25519-dalek", "getrandom 0.4.3", "hex", "hmac 0.13.0", diff --git a/rust/crates/keygo-dpop/src/nonce.rs b/rust/crates/keygo-dpop/src/nonce.rs index a508cdbbf..9fb3c4fd8 100644 --- a/rust/crates/keygo-dpop/src/nonce.rs +++ b/rust/crates/keygo-dpop/src/nonce.rs @@ -16,8 +16,8 @@ const NONCE_LEN: usize = TIMESTAMP_LEN + TAG_LEN; pub struct NonceKey(Zeroizing<[u8; 32]>); impl NonceKey { - pub fn new(bytes: [u8; 32]) -> Self { - Self(Zeroizing::new(bytes)) + pub fn new(bytes: &[u8; 32]) -> Self { + Self(Zeroizing::new(*bytes)) } fn mac(&self, created_at: u64) -> Hmac { @@ -93,7 +93,7 @@ mod tests { const NOW: u64 = 1_700_000_000; fn key() -> NonceKey { - NonceKey::new([1; 32]) + NonceKey::new(&[1; 32]) } #[test] @@ -123,7 +123,7 @@ mod tests { #[test] fn rejects_nonce_from_another_key() { - let foreign = NonceKey::new([2; 32]).issue(NOW).to_string(); + let foreign = NonceKey::new(&[2; 32]).issue(NOW).to_string(); assert_eq!(key().open(&foreign), None); } diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index 4ca7a598e..b83013161 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -176,7 +176,7 @@ mod tests { const NONCE_LIFETIME: u64 = 5 * 60; fn verifier_started_at(started_at: u64) -> DpopVerifier { - DpopVerifier::started_at(NonceKey::new([3; 32]), started_at) + DpopVerifier::started_at(NonceKey::new(&[3; 32]), started_at) } /// Verifies at `NOW` against a server that has been up long enough to accept nonce-less proofs. diff --git a/rust/crates/keygo-server/.sqlx/query-7e72ddd24d19ed2e6e1b602f9302e9d47ad15b0c02943c181293f3092c2483a7.json b/rust/crates/keygo-server/.sqlx/query-7e72ddd24d19ed2e6e1b602f9302e9d47ad15b0c02943c181293f3092c2483a7.json new file mode 100644 index 000000000..42ea281fc --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-7e72ddd24d19ed2e6e1b602f9302e9d47ad15b0c02943c181293f3092c2483a7.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "insert into refresh_tokens (token_hash, session_id, expires_at)\n values ($1, $2, now() + make_interval(secs => $3))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bytea", + "Uuid", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "7e72ddd24d19ed2e6e1b602f9302e9d47ad15b0c02943c181293f3092c2483a7" +} diff --git a/rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json b/rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json new file mode 100644 index 000000000..535d4b16b --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json @@ -0,0 +1,19 @@ +{ + "db_name": "PostgreSQL", + "query": "insert into sessions (id, device_id, user_id, dpop_jkt, auth_time, expires_at)\n values ($1, $2, $3, $4, to_timestamp($5::int8), now() + make_interval(secs => $6))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Uuid", + "Bytea", + "Int8", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352" +} diff --git a/rust/crates/keygo-server/.sqlx/query-c4ee662f47c4aff1ebb955475f17632489942012f1e4f3eb128ed078b6b66d70.json b/rust/crates/keygo-server/.sqlx/query-c4ee662f47c4aff1ebb955475f17632489942012f1e4f3eb128ed078b6b66d70.json new file mode 100644 index 000000000..8b37b60f8 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-c4ee662f47c4aff1ebb955475f17632489942012f1e4f3eb128ed078b6b66d70.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "update devices\n set name = $3, platform = $4, app_version = $5, last_seen_at = now()\n where id = $1 and user_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c4ee662f47c4aff1ebb955475f17632489942012f1e4f3eb128ed078b6b66d70" +} diff --git a/rust/crates/keygo-server/.sqlx/query-f4a6d574c44aedc437900062dba293e2030d65d5afeda0a6c8784a4e184ced52.json b/rust/crates/keygo-server/.sqlx/query-f4a6d574c44aedc437900062dba293e2030d65d5afeda0a6c8784a4e184ced52.json new file mode 100644 index 000000000..1e6171c27 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-f4a6d574c44aedc437900062dba293e2030d65d5afeda0a6c8784a4e184ced52.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "update sessions\n set revoked_at = now(), revoke_reason = $1\n where device_id = $2 and revoked_at is null", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "f4a6d574c44aedc437900062dba293e2030d65d5afeda0a6c8784a4e184ced52" +} diff --git a/rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json b/rust/crates/keygo-server/.sqlx/query-fe7cc39f3f5ac35261f000ad298f26f11cb76275d9fe14b92654d10dfa82d0f6.json similarity index 67% rename from rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json rename to rust/crates/keygo-server/.sqlx/query-fe7cc39f3f5ac35261f000ad298f26f11cb76275d9fe14b92654d10dfa82d0f6.json index ca4a9166b..2e0b913fa 100644 --- a/rust/crates/keygo-server/.sqlx/query-b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940.json +++ b/rust/crates/keygo-server/.sqlx/query-fe7cc39f3f5ac35261f000ad298f26f11cb76275d9fe14b92654d10dfa82d0f6.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "insert into devices (id, user_id, name, platform, app_version)\n values ($1, $2, $3, $4, $5)", + "query": "insert into devices (id, user_id, name, platform, app_version)\n values ($1, $2, $3, $4, $5)", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "b023eba0b2d892728dcf8e7e618db2379782897daa733902917e64f3e811c940" + "hash": "fe7cc39f3f5ac35261f000ad298f26f11cb76275d9fe14b92654d10dfa82d0f6" } diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 5dab0d760..7c13d6566 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -37,6 +37,7 @@ hmac = "0.13.0" sha2 = { version = "0.11.0", features = ["zeroize"] } time = { version = "0.3.55", features = ["formatting", "macros"] } moka = { version = "0.12.16", features = ["sync"] } +ed25519-dalek = "3.0.0" [dev-dependencies] keygo-dpop = { path = "../keygo-dpop", features = ["test-support"] } diff --git a/rust/crates/keygo-server/migrations/20261014141017_init.sql b/rust/crates/keygo-server/migrations/20261014141017_init.sql index b4e7aec32..0a2191154 100644 --- a/rust/crates/keygo-server/migrations/20261014141017_init.sql +++ b/rust/crates/keygo-server/migrations/20261014141017_init.sql @@ -16,6 +16,29 @@ create table devices last_seen_at timestamptz not null default now() ); +create table sessions +( + id uuid primary key, + device_id uuid not null references devices on delete cascade, + user_id uuid not null references users on delete cascade, + dpop_jkt bytea not null, + auth_time timestamptz not null, + created_at timestamptz not null default now(), + expires_at timestamptz not null, + revoked_at timestamptz, + revoke_reason text +); +create unique index sessions_one_live_per_device on sessions (device_id) where revoked_at is null; + +create table refresh_tokens +( + token_hash bytea primary key, + session_id uuid not null references sessions on delete cascade, + issued_at timestamptz not null default now(), + expires_at timestamptz not null, + used_at timestamptz +); + create table invites ( code_hash bytea primary key, diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 6369dab92..e2fb0a399 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -68,13 +68,14 @@ mod tests { pub(super) fn state() -> AppState { AppState { public_url: url::Url::parse("http://localhost").unwrap(), - signup: Signup::InviteOnly(Arc::new(InvitePepper::new([0; 32]))), + signup: Signup::InviteOnly(Arc::new(InvitePepper::new(&[0; 32]))), opaque_state: keygo_opaque::server::ServerSetup::generate(), // Lazy pools never connect until queried, so routes without a query need no database. db: sqlx::postgres::PgPoolOptions::new() .connect_lazy_with(sqlx::postgres::PgConnectOptions::new()), login_states: LoginStates::new(), - dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new([0; 32]))), + dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new(&[0; 32]))), + token_issuer: Arc::new(crate::testing::token_issuer()), } } diff --git a/rust/crates/keygo-server/src/api/routes/auth/login.rs b/rust/crates/keygo-server/src/api/routes/auth/login.rs index e1b41300f..af611a44b 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/login.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/login.rs @@ -1,6 +1,7 @@ use crate::api::dpop::DpopProof; +use crate::api::routes::auth::session::Session; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; -use crate::domain::{LoginId, Username}; +use crate::domain::{Device, LoginId, Username}; use crate::service::login::{self, FinishLogin, StartLogin}; use axum::Router; use axum::extract::State; @@ -61,6 +62,7 @@ async fn start( struct FinishRequest { login_id: LoginId, credential_finalization: CredentialFinalization, + device: Device, dpop_binding: DpopBinding, } @@ -68,6 +70,7 @@ struct FinishRequest { struct FinishResponse { user_id: Uuid, username: Username, + session: Session, } async fn finish( @@ -78,15 +81,18 @@ async fn finish( let input = FinishLogin { login_id: request.login_id, credential_finalization: request.credential_finalization, + device: request.device, binding: request.dpop_binding, jkt: proof.jkt, }; - let finished = login::finish(&state.db, &state.login_states, input).await?; + let finished = + login::finish(&state.db, &state.token_issuer, &state.login_states, input).await?; Ok(Json(FinishResponse { user_id: finished.user_id, username: finished.username, + session: finished.session.into(), })) } @@ -95,7 +101,8 @@ mod tests { use super::*; use crate::api::error::render; use crate::testing::{ - PASSWORD, app_state, post_to, post_with_proof, proof_post, prover, register, send, + PASSWORD, app_state, device_json, post_to, post_with_proof, proof_post, prover, register, + send, }; use axum::http::StatusCode; use keygo_opaque::OpaqueError; @@ -129,6 +136,7 @@ mod tests { "login_id": login_id, "credential_finalization": finish.finalization.to_base64(), "dpop_binding": finish.session_key.dpop_binding(jkt).to_base64(), + "device": device_json(), }) } @@ -162,10 +170,91 @@ mod tests { let (status, finished) = post_with_proof(&state, &prover, FINISH, body).await; assert_eq!(status, StatusCode::OK); - assert_eq!(finished, json!({ "user_id": user_id, "username": "ada" })); + assert_eq!(finished["user_id"], user_id.to_string()); + assert_eq!(finished["username"], "ada"); assert_eq!(state.login_states.count(), 0); } + #[sqlx::test] + async fn finish_returns_a_session_bound_to_the_proof_key(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + let user_id = register(&db, &setup, "ada").await; + let (client, started) = start_over_http(&state, "ada").await; + let prover = prover(); + let body = finish_body(&started["login_id"], client, &started, prover.jkt()); + + let (_, finished) = post_with_proof(&state, &prover, FINISH, body).await; + + let session = &finished["session"]; + assert!( + session["refresh_token"] + .as_str() + .unwrap() + .starts_with("kgr_") + ); + let claims = state + .token_issuer + .verify(session["access_token"].as_str().unwrap()) + .unwrap(); + assert_eq!(claims.user_id(), user_id); + assert_eq!(claims.jkt(), prover.jkt()); + let (device_id, jkt): (Uuid, Vec) = sqlx::query_as( + "select device_id, dpop_jkt from sessions where id = $1 and revoked_at is null", + ) + .bind(claims.session_id()) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(session["device_id"], device_id.to_string()); + assert_eq!(jkt, prover.jkt()); + } + + #[sqlx::test] + async fn returned_device_id_is_kept_across_sign_ins(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let prover = prover(); + let (client, started) = start_over_http(&state, "ada").await; + let body = finish_body(&started["login_id"], client, &started, prover.jkt()); + let (_, first) = post_with_proof(&state, &prover, FINISH, body).await; + let device_id = &first["session"]["device_id"]; + + let (client, started) = start_over_http(&state, "ada").await; + let mut body = finish_body(&started["login_id"], client, &started, prover.jkt()); + body["device"]["device_id"] = device_id.clone(); + let (status, second) = post_with_proof(&state, &prover, FINISH, body).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(&second["session"]["device_id"], device_id); + let reasons: Vec> = sqlx::query_scalar( + "select revoke_reason from sessions where device_id = $1 order by created_at", + ) + .bind(Uuid::parse_str(device_id.as_str().unwrap()).unwrap()) + .fetch_all(&db) + .await + .unwrap(); + assert_eq!(reasons, [Some("replaced".to_owned()), None]); + } + + #[sqlx::test] + async fn finish_requires_a_device(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let (client, started) = start_over_http(&state, "ada").await; + let prover = prover(); + let mut body = finish_body(&started["login_id"], client, &started, prover.jkt()); + body.as_object_mut().unwrap().remove("device"); + + let (status, body) = post_with_proof(&state, &prover, FINISH, body).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "invalid_request"); + assert_eq!(state.login_states.count(), 1); + } + #[sqlx::test] async fn finish_without_a_proof_keeps_the_login(db: PgPool) { let setup = ServerSetup::generate(); diff --git a/rust/crates/keygo-server/src/api/routes/auth/mod.rs b/rust/crates/keygo-server/src/api/routes/auth/mod.rs index a9a5e5abc..a3bd25205 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/mod.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/mod.rs @@ -4,6 +4,7 @@ use axum::extract::DefaultBodyLimit; mod login; mod register; +mod session; /// The largest legitimate body is a key bundle of a few hundred bytes. Every auth endpoint is /// reachable without a token, so anything larger is refused before it is buffered and parsed. diff --git a/rust/crates/keygo-server/src/api/routes/auth/register.rs b/rust/crates/keygo-server/src/api/routes/auth/register.rs index 6f254be8f..e843e6740 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/register.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/register.rs @@ -1,4 +1,5 @@ use crate::api::dpop::DpopProof; +use crate::api::routes::auth::session::Session; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; use crate::domain::{DeviceInfo, RegistrationId, Username}; use crate::service::registration::{self, FinishRegistration, StartRegistration}; @@ -77,6 +78,7 @@ struct FinishRequest { #[derive(Serialize)] struct FinishResponse { username: Username, + session: Session, } impl HttpError for registration::FinishError { @@ -91,22 +93,23 @@ impl HttpError for registration::FinishError { async fn finish( State(state): State, - // TODO: bind the new session to `proof.jkt` - _proof: DpopProof, + proof: DpopProof, Json(request): Json, ) -> ServerResult<(StatusCode, Json)> { let input = FinishRegistration { registration_id: request.registration_id, registration_upload: request.registration_upload, device_info: request.device, + jkt: proof.jkt, }; - let finished = registration::finish(&state.db, input).await?; + let finished = registration::finish(&state.db, &state.token_issuer, input).await?; Ok(( StatusCode::CREATED, Json(FinishResponse { username: finished.username, + session: finished.session.into(), }), )) } @@ -182,9 +185,50 @@ mod tests { let (status, finished) = post_with_proof(&state, &prover(), FINISH, body).await; assert_eq!(status, StatusCode::CREATED); - assert_eq!(finished, json!({ "username": "ada" })); + assert_eq!(finished["username"], "ada"); assert_eq!(count(&db, "users").await, 1); assert_eq!(count(&db, "devices").await, 1); + assert_eq!(count(&db, "sessions").await, 1); + } + + #[sqlx::test] + async fn finish_returns_a_session_bound_to_the_proof_key(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let (client, body) = start_body("ada", Uuid::new_v4()); + let (_, started) = post_to(state.clone(), START, body).await; + + let (status, finished) = + post_with_proof(&state, &prover, FINISH, finish_body(client, &started)).await; + + assert_eq!(status, StatusCode::CREATED); + let session = &finished["session"]; + let device_id: Uuid = sqlx::query_scalar("select id from devices") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(session["device_id"], device_id.to_string()); + assert_eq!( + session["refresh_expires_in"], + crate::service::session::REFRESH_TTL.as_secs(), + ); + let token = session["refresh_token"].as_str().unwrap(); + assert!(token.starts_with("kgr_"), "{token}"); + assert_eq!(token.len(), "kgr_".len() + 43); + let jkt: Vec = sqlx::query_scalar("select dpop_jkt from sessions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(jkt, prover.jkt()); + assert_eq!( + session["access_expires_in"], + crate::domain::ACCESS_TOKEN_LIFETIME.as_secs(), + ); + let claims = state + .token_issuer + .verify(session["access_token"].as_str().unwrap()) + .unwrap(); + assert_eq!(claims.jkt(), prover.jkt()); } fn invite_only_state(db: &PgPool, setup: &ServerSetup) -> AppState { diff --git a/rust/crates/keygo-server/src/api/routes/auth/session.rs b/rust/crates/keygo-server/src/api/routes/auth/session.rs new file mode 100644 index 000000000..317e6e3d7 --- /dev/null +++ b/rust/crates/keygo-server/src/api/routes/auth/session.rs @@ -0,0 +1,24 @@ +use crate::domain::{AccessToken, DeviceId, RefreshToken}; +use crate::service::session::Issued; +use serde::Serialize; + +#[derive(Serialize)] +pub struct Session { + device_id: DeviceId, + access_token: AccessToken, + access_expires_in: u64, + refresh_token: RefreshToken, + refresh_expires_in: u64, +} + +impl From for Session { + fn from(value: Issued) -> Self { + Self { + device_id: value.device_id, + access_token: value.access_token, + access_expires_in: value.access_expires_in.as_secs(), + refresh_token: value.refresh_token, + refresh_expires_in: value.refresh_expires_in.as_secs(), + } + } +} diff --git a/rust/crates/keygo-server/src/api/state.rs b/rust/crates/keygo-server/src/api/state.rs index 9d73389b3..ce8222ca7 100644 --- a/rust/crates/keygo-server/src/api/state.rs +++ b/rust/crates/keygo-server/src/api/state.rs @@ -1,5 +1,6 @@ use crate::cache::LoginStates; use crate::config::DeploymentConfig; +use crate::domain::TokenIssuer; use crate::service::registration::Signup; use anyhow::Context; use keygo_dpop::verify::DpopVerifier; @@ -15,13 +16,16 @@ pub struct AppState { pub db: PgPool, pub login_states: LoginStates, pub dpop_verifier: Arc, + pub token_issuer: Arc, } impl AppState { pub fn new(config: &DeploymentConfig, db: PgPool) -> anyhow::Result { let secrets = &config.secrets; + let public_url = Url::parse(&config.server.public_url).context("invalid public url")?; + let issuer = public_url.as_str().trim_end_matches('/').to_owned(); Ok(Self { - public_url: Url::parse(&config.server.public_url).context("invalid public url")?, + public_url, signup: if config.server.allow_signups { Signup::Open } else { @@ -31,6 +35,7 @@ impl AppState { db, login_states: LoginStates::new(), dpop_verifier: Arc::new(DpopVerifier::new(secrets.dpop_nonce_key()?)), + token_issuer: Arc::new(TokenIssuer::new(secrets.access_token_key()?, issuer)), }) } } diff --git a/rust/crates/keygo-server/src/config.rs b/rust/crates/keygo-server/src/config.rs index b9859b1ff..daa53a66a 100644 --- a/rust/crates/keygo-server/src/config.rs +++ b/rust/crates/keygo-server/src/config.rs @@ -1,4 +1,4 @@ -use crate::domain::InvitePepper; +use crate::domain::{AccessTokenKey, InvitePepper}; use crate::secrets::{DbPassword, DpopNonceKey, OpaqueSetup, SecretStore}; use clap::{Args, ValueEnum}; use keygo_dpop::NonceKey; @@ -111,4 +111,8 @@ impl SecretsConfig { pub(crate) fn dpop_nonce_key(&self) -> anyhow::Result { self.store().read::() } + + pub(crate) fn access_token_key(&self) -> anyhow::Result { + self.store().read::() + } } diff --git a/rust/crates/keygo-server/src/db/devices.rs b/rust/crates/keygo-server/src/db/devices.rs index 22094a58e..f1026ee93 100644 --- a/rust/crates/keygo-server/src/db/devices.rs +++ b/rust/crates/keygo-server/src/db/devices.rs @@ -22,3 +22,25 @@ pub async fn insert( Ok(()) } + +pub async fn attach( + conn: &mut PgConnection, + id: DeviceId, + user_id: Uuid, + device_info: &DeviceInfo, +) -> sqlx::Result { + let result = sqlx::query!( + "update devices + set name = $3, platform = $4, app_version = $5, last_seen_at = now() + where id = $1 and user_id = $2", + id.as_uuid(), + user_id, + device_info.name.as_str(), + device_info.platform.as_str(), + device_info.app_version.as_str(), + ) + .execute(conn) + .await?; + + Ok(result.rows_affected() == 1) +} diff --git a/rust/crates/keygo-server/src/db/mod.rs b/rust/crates/keygo-server/src/db/mod.rs index b4ac5c784..fc727ee2b 100644 --- a/rust/crates/keygo-server/src/db/mod.rs +++ b/rust/crates/keygo-server/src/db/mod.rs @@ -1,7 +1,9 @@ pub mod devices; pub mod invites; pub mod opaque_records; +pub mod refresh_tokens; pub mod registrations; +pub mod sessions; pub mod users; use crate::config::{DatabaseConfig, SecretsConfig}; diff --git a/rust/crates/keygo-server/src/db/refresh_tokens.rs b/rust/crates/keygo-server/src/db/refresh_tokens.rs new file mode 100644 index 000000000..feb5482cf --- /dev/null +++ b/rust/crates/keygo-server/src/db/refresh_tokens.rs @@ -0,0 +1,109 @@ +use crate::domain::SessionId; +use sqlx::PgConnection; +use std::time::Duration; + +pub async fn insert( + conn: &mut PgConnection, + session_id: SessionId, + token_hash: &[u8; 32], + ttl: Duration, +) -> sqlx::Result<()> { + sqlx::query!( + "insert into refresh_tokens (token_hash, session_id, expires_at) + values ($1, $2, now() + make_interval(secs => $3))", + token_hash, + session_id, + ttl.as_secs_f64(), + ) + .execute(conn) + .await?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::sessions; + use crate::testing::{JKT, count, expires_in_secs, insert_device}; + use sqlx::PgPool; + + const TTL: Duration = Duration::from_hours(24); + const HASH: [u8; 32] = [9; 32]; + + async fn insert_session(db: &PgPool) -> SessionId { + let (user_id, device_id) = insert_device(db).await; + let session_id = SessionId::new_v4(); + let mut conn = db.acquire().await.unwrap(); + sessions::insert(&mut conn, session_id, user_id, device_id, &JKT, 0, TTL) + .await + .unwrap(); + session_id + } + + #[sqlx::test] + async fn token_is_stored_unused_under_its_hash(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + + let stored: (Vec, SessionId, bool) = + sqlx::query_as("select token_hash, session_id, used_at is null from refresh_tokens") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, (HASH.to_vec(), session_id, true)); + } + + #[sqlx::test] + async fn token_expires_after_ttl(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + + let remaining = expires_in_secs(&db, "refresh_tokens").await; + assert!( + (TTL.as_secs_f64() - 5.0..=TTL.as_secs_f64()).contains(&remaining), + "{remaining}" + ); + } + + #[sqlx::test] + async fn duplicate_hash_is_rejected(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + + let err = insert(&mut conn, session_id, &HASH, TTL).await.unwrap_err(); + + assert!(err.as_database_error().unwrap().is_unique_violation()); + } + + #[sqlx::test] + async fn token_requires_a_session(db: PgPool) { + let mut conn = db.acquire().await.unwrap(); + + let err = insert(&mut conn, SessionId::new_v4(), &HASH, TTL) + .await + .unwrap_err(); + + assert!(err.as_database_error().unwrap().is_foreign_key_violation()); + } + + #[sqlx::test] + async fn token_is_deleted_with_its_session(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + + sqlx::query("delete from sessions where id = $1") + .bind(session_id) + .execute(&db) + .await + .unwrap(); + + assert_eq!(count(&db, "refresh_tokens").await, 0); + } +} diff --git a/rust/crates/keygo-server/src/db/sessions.rs b/rust/crates/keygo-server/src/db/sessions.rs new file mode 100644 index 000000000..e9eefded1 --- /dev/null +++ b/rust/crates/keygo-server/src/db/sessions.rs @@ -0,0 +1,216 @@ +use crate::domain::{DeviceId, RevokeReason, SessionId}; +use sqlx::PgConnection; +use std::time::Duration; +use uuid::Uuid; + +pub async fn insert( + conn: &mut PgConnection, + session_id: SessionId, + user_id: Uuid, + device_id: DeviceId, + jkt: &[u8; 32], + auth_time: u64, + ttl: Duration, +) -> sqlx::Result<()> { + sqlx::query!( + "insert into sessions (id, device_id, user_id, dpop_jkt, auth_time, expires_at) + values ($1, $2, $3, $4, to_timestamp($5::int8), now() + make_interval(secs => $6))", + session_id, + device_id.as_uuid(), + user_id, + jkt, + i64::try_from(auth_time).expect("auth_time fits a timestamptz"), + ttl.as_secs_f64(), + ) + .execute(conn) + .await?; + + Ok(()) +} + +pub async fn revoke( + conn: &mut PgConnection, + device_id: DeviceId, + reason: RevokeReason, +) -> sqlx::Result<()> { + sqlx::query!( + "update sessions + set revoked_at = now(), revoke_reason = $1 + where device_id = $2 and revoked_at is null", + reason.as_str(), + device_id.as_uuid(), + ) + .execute(conn) + .await?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{JKT, count, expires_in_secs, insert_device}; + use sqlx::PgPool; + + const TTL: Duration = Duration::from_hours(24); + + const AUTH_TIME: u64 = 1_791_504_000; + + #[sqlx::test] + async fn session_is_bound_to_device_user_and_key(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let session_id = SessionId::new_v4(); + let mut conn = db.acquire().await.unwrap(); + + insert( + &mut conn, session_id, user_id, device_id, &JKT, AUTH_TIME, TTL, + ) + .await + .unwrap(); + + let stored: (Uuid, Uuid, Uuid, Vec, i64) = sqlx::query_as( + "select id, device_id, user_id, dpop_jkt, extract(epoch from auth_time)::int8 + from sessions", + ) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!( + stored, + ( + session_id, + device_id.as_uuid(), + user_id, + JKT.to_vec(), + AUTH_TIME as i64, + ) + ); + } + + #[sqlx::test] + async fn session_expires_after_ttl(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + insert( + &mut conn, + SessionId::new_v4(), + user_id, + device_id, + &JKT, + AUTH_TIME, + TTL, + ) + .await + .unwrap(); + + let remaining = expires_in_secs(&db, "sessions").await; + assert!( + (TTL.as_secs_f64() - 5.0..=TTL.as_secs_f64()).contains(&remaining), + "{remaining}" + ); + } + + #[sqlx::test] + async fn session_requires_a_device(db: PgPool) { + let (user_id, _) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + let err = insert( + &mut conn, + SessionId::new_v4(), + user_id, + DeviceId::random(), + &JKT, + AUTH_TIME, + TTL, + ) + .await + .unwrap_err(); + + assert!(err.as_database_error().unwrap().is_foreign_key_violation()); + } + + #[sqlx::test] + async fn session_is_deleted_with_its_device(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert( + &mut conn, + SessionId::new_v4(), + user_id, + device_id, + &JKT, + AUTH_TIME, + TTL, + ) + .await + .unwrap(); + + sqlx::query("delete from devices where id = $1") + .bind(device_id.as_uuid()) + .execute(&db) + .await + .unwrap(); + + assert_eq!(count(&db, "sessions").await, 0); + } + + async fn insert_session(db: &PgPool) -> DeviceId { + let (user_id, device_id) = insert_device(db).await; + let mut conn = db.acquire().await.unwrap(); + insert( + &mut conn, + SessionId::new_v4(), + user_id, + device_id, + &JKT, + AUTH_TIME, + TTL, + ) + .await + .unwrap(); + device_id + } + + #[sqlx::test] + async fn revoke_records_the_reason(db: PgPool) { + let device_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + + revoke(&mut conn, device_id, RevokeReason::Replaced) + .await + .unwrap(); + + let (reason, revoked): (String, bool) = + sqlx::query_as("select revoke_reason, revoked_at is not null from sessions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!((reason.as_str(), revoked), ("replaced", true)); + } + + #[sqlx::test] + async fn revoke_leaves_revoked_sessions_alone(db: PgPool) { + let device_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + sqlx::query( + "update sessions set revoked_at = now() - interval '1 day', revoke_reason = 'logout'", + ) + .execute(&db) + .await + .unwrap(); + + revoke(&mut conn, device_id, RevokeReason::Replaced) + .await + .unwrap(); + + let (reason, old): (String, bool) = sqlx::query_as( + "select revoke_reason, revoked_at < now() - interval '1 hour' from sessions", + ) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!((reason.as_str(), old), ("logout", true)); + } +} diff --git a/rust/crates/keygo-server/src/domain/access_token.rs b/rust/crates/keygo-server/src/domain/access_token.rs new file mode 100644 index 000000000..210dde9d0 --- /dev/null +++ b/rust/crates/keygo-server/src/domain/access_token.rs @@ -0,0 +1,611 @@ +use crate::domain::SessionId; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ed25519_dalek::{Signature, Signer, SigningKey}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use thiserror::Error; +use uuid::Uuid; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +pub const ACCESS_TOKEN_LIFETIME: Duration = Duration::from_mins(10); +pub const FRESH_AUTH_WINDOW: Duration = Duration::from_mins(5); + +const JTI_BYTES: usize = 32; + +pub struct AccessTokenKey { + signing: SigningKey, + kid: String, +} + +pub struct TokenIssuer { + key: AccessTokenKey, + iss: String, +} + +impl TokenIssuer { + pub fn new(key: AccessTokenKey, iss: impl Into) -> Self { + Self { + key, + iss: iss.into(), + } + } + + pub fn issue( + &self, + user_id: Uuid, + session_id: SessionId, + auth_time: u64, + jkt: &[u8; 32], + ) -> AccessToken { + self.key.sign(&Claims::new( + self.iss.clone(), + user_id, + session_id, + auth_time, + jkt, + )) + } + + pub fn verify(&self, token: &str) -> Result { + self.key.verify(token, &self.iss) + } +} + +#[derive(Serialize, Deserialize)] +struct Cnf { + #[serde(with = "base64url")] + jkt: [u8; 32], +} + +#[derive(Serialize, Deserialize)] +enum Aud { + #[serde(rename = "keygo-api")] + KeyGoApi, +} + +// TODO: add `pwe` (password_epoch) once the epoch exists. +#[derive(Serialize, Deserialize)] +pub struct Claims { + iss: String, + aud: Aud, + #[serde(rename = "sub")] + user_id: Uuid, + #[serde(rename = "sid")] + session_id: SessionId, + iat: u64, + exp: u64, + auth_time: u64, + cnf: Cnf, + #[serde(with = "base64url")] + jti: [u8; JTI_BYTES], +} + +#[derive(Serialize, Deserialize)] +enum Alg { + EdDSA, +} + +#[derive(Serialize, Deserialize)] +enum Typ { + #[serde(rename = "at+jwt")] + AtJwt, +} + +#[derive(Serialize, Deserialize)] +struct Header { + alg: Alg, + typ: Typ, + kid: String, +} + +#[derive(Serialize, Zeroize, ZeroizeOnDrop)] +pub struct AccessToken(String); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum TokenError { + #[error("token is not a well-formed access token")] + Malformed, + #[error("token was signed by an unknown key")] + UnknownKey, + #[error("token signature does not verify")] + InvalidSignature, + #[error("token was issued by another server")] + WrongIssuer, + #[error("token has expired")] + Expired, +} + +impl Claims { + pub fn new( + iss: String, + user_id: Uuid, + session_id: SessionId, + auth_time: u64, + jkt: &[u8; 32], + ) -> Self { + Self::new_at(iss, user_id, session_id, auth_time, jkt, unix_now()) + } + + fn new_at( + iss: String, + user_id: Uuid, + session_id: SessionId, + auth_time: u64, + jkt: &[u8; 32], + now: u64, + ) -> Self { + let mut jti = [0u8; JTI_BYTES]; + getrandom::fill(jti.as_mut_slice()).expect("OS random number generator unavailable"); + + Self { + iss, + aud: Aud::KeyGoApi, + user_id, + session_id, + iat: now, + exp: now + ACCESS_TOKEN_LIFETIME.as_secs(), + auth_time, + cnf: Cnf { jkt: *jkt }, + jti, + } + } + + pub fn user_id(&self) -> Uuid { + self.user_id + } + + pub fn session_id(&self) -> SessionId { + self.session_id + } + + pub fn auth_time(&self) -> u64 { + self.auth_time + } + + pub fn jkt(&self) -> &[u8; 32] { + &self.cnf.jkt + } + + pub fn is_fresh(&self) -> bool { + self.is_fresh_at(unix_now()) + } + + fn is_fresh_at(&self, now: u64) -> bool { + now.saturating_sub(self.auth_time) <= FRESH_AUTH_WINDOW.as_secs() + } +} + +impl AccessToken { + pub(crate) fn expose(&self) -> &str { + &self.0 + } +} + +impl AccessTokenKey { + pub fn new(seed: &[u8; 32]) -> Self { + let signing = SigningKey::from_bytes(seed); + let digest = Sha256::digest(signing.verifying_key().as_bytes()); + let kid = hex::encode(&digest[..8]); + + Self { signing, kid } + } + + pub fn sign(&self, claims: &Claims) -> AccessToken { + let header = Header { + alg: Alg::EdDSA, + typ: Typ::AtJwt, + kid: self.kid.clone(), + }; + + let input = format!("{}.{}", encode(&header), encode(claims)); + let signature = self.signing.sign(input.as_bytes()); + + AccessToken(format!( + "{input}.{}", + URL_SAFE_NO_PAD.encode(signature.to_bytes()) + )) + } + + pub fn verify(&self, token: &str, iss: &str) -> Result { + self.verify_at(token, iss, unix_now()) + } + + fn verify_at(&self, token: &str, iss: &str, now: u64) -> Result { + let (input, signature) = token.rsplit_once('.').ok_or(TokenError::Malformed)?; + let (header, claims) = input.split_once('.').ok_or(TokenError::Malformed)?; + + let header: Header = decode(header)?; + if header.kid != self.kid { + return Err(TokenError::UnknownKey); + } + + let signature = URL_SAFE_NO_PAD + .decode(signature) + .ok() + .and_then(|bytes| Signature::from_slice(&bytes).ok()) + .ok_or(TokenError::Malformed)?; + self.signing + .verifying_key() + .verify_strict(input.as_bytes(), &signature) + .map_err(|_| TokenError::InvalidSignature)?; + + let claims: Claims = decode(claims)?; + if claims.iss != iss { + return Err(TokenError::WrongIssuer); + } + if now >= claims.exp { + return Err(TokenError::Expired); + } + Ok(claims) + } +} + +pub(crate) fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock is set before the Unix epoch") + .as_secs() +} + +fn encode(value: &T) -> String { + URL_SAFE_NO_PAD.encode(serde_json::to_vec(value).expect("types always serialize")) +} + +fn decode(segment: &str) -> Result { + let json = URL_SAFE_NO_PAD + .decode(segment) + .map_err(|_| TokenError::Malformed)?; + serde_json::from_slice(&json).map_err(|_| TokenError::Malformed) +} + +mod base64url { + use base64::Engine; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + use serde::de::Error; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize( + bytes: &[u8; N], + serializer: S, + ) -> Result { + serializer.serialize_str(&URL_SAFE_NO_PAD.encode(bytes)) + } + + pub fn deserialize<'de, D: Deserializer<'de>, const N: usize>( + deserializer: D, + ) -> Result<[u8; N], D::Error> { + let encoded = <&str>::deserialize(deserializer)?; + URL_SAFE_NO_PAD + .decode(encoded) + .ok() + .and_then(|bytes| bytes.try_into().ok()) + .ok_or_else(|| D::Error::custom(format!("expected {N} bytes of base64url"))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ed25519_dalek::Verifier; + use serde_json::{Value, json}; + + const SEED: [u8; 32] = [0x07; 32]; + const JKT: [u8; 32] = [0x41; 32]; + const ISS: &str = "https://keygo.example"; + const NOW: u64 = 1_791_504_000; + + fn fixed_claims() -> Claims { + Claims { + jti: [0x42; JTI_BYTES], + ..Claims::new_at( + ISS.into(), + Uuid::from_u128(1), + Uuid::from_u128(2), + 1_791_503_940, + &JKT, + NOW, + ) + } + } + + fn part(token: &str, index: usize) -> Value { + let segment = token.split('.').nth(index).unwrap(); + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).unwrap()).unwrap() + } + + fn with_part(token: &str, index: usize, value: Value) -> String { + let mut parts: Vec = token.split('.').map(String::from).collect(); + parts[index] = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&value).unwrap()); + parts.join(".") + } + + #[test] + fn signs_pinned_token() { + let token = AccessTokenKey::new(&SEED).sign(&fixed_claims()); + + assert_eq!( + token.expose(), + concat!( + "eyJhbGciOiJFZERTQSIsInR5cCI6ImF0K2p3dCIsImtpZCI6ImZlODEyYzEyZjNhYjRjZTYifQ.", + "eyJpc3MiOiJodHRwczovL2tleWdvLmV4YW1wbGUiLCJhdWQiOiJrZXlnby1hcGkiLCJzdWIiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEiLCJzaWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDIiLCJpYXQiOjE3OTE1MDQwMDAsImV4cCI6MTc5MTUwNDYwMCwiYXV0aF90aW1lIjoxNzkxNTAzOTQwLCJjbmYiOnsiamt0IjoiUVVGQlFVRkJRVUZCUVVGQlFVRkJRVUZCUVVGQlFVRkJRVUZCUVVGQlFVRSJ9LCJqdGkiOiJRa0pDUWtKQ1FrSkNRa0pDUWtKQ1FrSkNRa0pDUWtKQ1FrSkNRa0pDUWtJIn0.", + "3RCy0TvWwahXCYg7tQ4Wq34cgsuJMdI5ocC26HYRT-rQf8ayNnr5sSfgYxBVHdawh39Up55m8K2tgprgiXFHBg", + ), + ); + } + + #[test] + fn header_names_alg_typ_and_kid() { + let token = AccessTokenKey::new(&SEED).sign(&fixed_claims()); + + assert_eq!( + part(token.expose(), 0), + json!({ "alg": "EdDSA", "typ": "at+jwt", "kid": "fe812c12f3ab4ce6" }), + ); + } + + #[test] + fn claims_use_spec_names_and_string_encodings() { + let token = AccessTokenKey::new(&SEED).sign(&fixed_claims()); + + assert_eq!( + part(token.expose(), 1), + json!({ + "iss": "https://keygo.example", + "aud": "keygo-api", + "sub": "00000000-0000-0000-0000-000000000001", + "sid": "00000000-0000-0000-0000-000000000002", + "iat": 1_791_504_000, + "exp": 1_791_504_600, + "auth_time": 1_791_503_940, + "cnf": { "jkt": "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE" }, + "jti": "QkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI", + }), + ); + } + + #[test] + fn signature_verifies_under_the_public_key() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + + let (input, sig) = token.expose().rsplit_once('.').unwrap(); + let sig = Signature::from_slice(&URL_SAFE_NO_PAD.decode(sig).unwrap()).unwrap(); + + key.signing + .verifying_key() + .verify(input.as_bytes(), &sig) + .unwrap(); + } + + #[test] + fn expires_after_lifetime() { + let claims = Claims::new_at(String::new(), Uuid::nil(), Uuid::nil(), 0, &JKT, 1_000); + + assert_eq!(claims.iat, 1_000); + assert_eq!(claims.exp, 1_000 + ACCESS_TOKEN_LIFETIME.as_secs()); + } + + #[test] + fn generated_jtis_differ() { + let new = || Claims::new_at(String::new(), Uuid::nil(), Uuid::nil(), 0, &JKT, 0).jti; + + assert_ne!(new(), new()); + } + + #[test] + fn serializes_as_the_token() { + let token = AccessTokenKey::new(&SEED).sign(&fixed_claims()); + + assert_eq!(serde_json::to_value(&token).unwrap(), token.expose()); + } + + #[test] + fn verify_returns_the_signed_claims() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + + let claims = key.verify_at(token.expose(), ISS, NOW).unwrap(); + + assert_eq!(claims.user_id(), Uuid::from_u128(1)); + assert_eq!(claims.session_id(), Uuid::from_u128(2)); + assert_eq!(claims.auth_time(), 1_791_503_940); + assert_eq!(claims.jkt(), &JKT); + } + + #[test] + fn verify_rejects_tampered_claims() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + let mut claims = part(token.expose(), 1); + claims["sub"] = json!("00000000-0000-0000-0000-000000000009"); + + let tampered = with_part(token.expose(), 1, claims); + + assert_eq!( + key.verify_at(&tampered, ISS, NOW).err(), + Some(TokenError::InvalidSignature), + ); + } + + #[test] + fn verify_rejects_another_key() { + let token = AccessTokenKey::new(&[0x08; 32]).sign(&fixed_claims()); + + assert_eq!( + AccessTokenKey::new(&SEED) + .verify_at(token.expose(), ISS, NOW) + .err(), + Some(TokenError::UnknownKey), + ); + } + + #[test] + fn verify_rejects_a_foreign_signature_under_our_kid() { + let key = AccessTokenKey::new(&SEED); + let ours = key.sign(&fixed_claims()); + let theirs = AccessTokenKey::new(&[0x08; 32]).sign(&fixed_claims()); + let (input, _) = ours.expose().rsplit_once('.').unwrap(); + let (_, signature) = theirs.expose().rsplit_once('.').unwrap(); + + assert_eq!( + key.verify_at(&format!("{input}.{signature}"), ISS, NOW) + .err(), + Some(TokenError::InvalidSignature), + ); + } + + #[test] + fn verify_rejects_alg_none() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + let header = json!({ "alg": "none", "typ": "at+jwt", "kid": "fe812c12f3ab4ce6" }); + + let unsigned = with_part(token.expose(), 0, header); + + assert_eq!( + key.verify_at(&unsigned, ISS, NOW).err(), + Some(TokenError::Malformed), + ); + } + + #[test] + fn verify_rejects_another_typ() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + let header = json!({ "alg": "EdDSA", "typ": "dpop+jwt", "kid": "fe812c12f3ab4ce6" }); + + assert_eq!( + key.verify_at(&with_part(token.expose(), 0, header), ISS, NOW) + .err(), + Some(TokenError::Malformed), + ); + } + + #[test] + fn verify_rejects_another_issuer() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + + assert_eq!( + key.verify_at(token.expose(), "https://other.example", NOW) + .err(), + Some(TokenError::WrongIssuer), + ); + } + + #[test] + fn verify_rejects_another_audience() { + let key = AccessTokenKey::new(&SEED); + let mut claims = serde_json::to_value(fixed_claims()).unwrap(); + claims["aud"] = json!("other-api"); + let input = format!( + "{}.{}", + part_raw(key.sign(&fixed_claims()).expose(), 0), + URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap()), + ); + let signature = key.signing.sign(input.as_bytes()); + let token = format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature.to_bytes())); + + assert_eq!( + key.verify_at(&token, ISS, NOW).err(), + Some(TokenError::Malformed) + ); + } + + #[test] + fn verify_rejects_from_exp_on() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + let exp = NOW + ACCESS_TOKEN_LIFETIME.as_secs(); + + assert!(key.verify_at(token.expose(), ISS, exp - 1).is_ok()); + assert_eq!( + key.verify_at(token.expose(), ISS, exp).err(), + Some(TokenError::Expired), + ); + } + + #[test] + fn verify_rejects_malformed_input() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&fixed_claims()); + let (input, _) = token.expose().rsplit_once('.').unwrap(); + + for bad in ["", "a.b", "a.b.c", input, &format!("{input}.!!")] { + assert_eq!( + key.verify_at(bad, ISS, NOW).err(), + Some(TokenError::Malformed), + "{bad}" + ); + } + } + + #[test] + fn fresh_within_window_after_auth_time() { + let claims = Claims::new_at(String::new(), Uuid::nil(), Uuid::nil(), 1_000, &JKT, 1_000); + + assert!(claims.is_fresh_at(1_000)); + assert!(claims.is_fresh_at(1_000 + FRESH_AUTH_WINDOW.as_secs())); + assert!(!claims.is_fresh_at(1_000 + FRESH_AUTH_WINDOW.as_secs() + 1)); + } + + #[test] + fn token_issued_now_verifies_and_is_fresh() { + let key = AccessTokenKey::new(&SEED); + let token = key.sign(&Claims::new( + ISS.into(), + Uuid::nil(), + Uuid::nil(), + unix_now(), + &JKT, + )); + + assert!(key.verify(token.expose(), ISS).unwrap().is_fresh()); + } + + #[test] + fn issuer_round_trips_its_own_tokens() { + let issuer = TokenIssuer::new(AccessTokenKey::new(&SEED), ISS); + let token = issuer.issue(Uuid::from_u128(1), Uuid::from_u128(2), NOW, &JKT); + let claims = issuer.verify(token.expose()).unwrap(); + + assert_eq!(claims.user_id(), Uuid::from_u128(1)); + assert_eq!(claims.session_id(), Uuid::from_u128(2)); + assert_eq!(claims.auth_time(), NOW); + assert_eq!(claims.jkt(), &JKT); + } + + #[test] + fn issuer_rejects_tokens_for_another_issuer() { + let key = || AccessTokenKey::new(&SEED); + let token = TokenIssuer::new(key(), "https://other.example").issue( + Uuid::nil(), + Uuid::nil(), + unix_now(), + &JKT, + ); + + assert_eq!( + TokenIssuer::new(key(), ISS).verify(token.expose()).err(), + Some(TokenError::WrongIssuer), + ); + } + + #[test] + fn issuer_keeps_the_given_auth_time() { + let issuer = TokenIssuer::new(AccessTokenKey::new(&SEED), ISS); + let auth_time = unix_now() - FRESH_AUTH_WINDOW.as_secs() - 1; + + let token = issuer.issue(Uuid::nil(), Uuid::nil(), auth_time, &JKT); + let claims = issuer.verify(token.expose()).unwrap(); + + assert!(!claims.is_fresh()); + } + + fn part_raw(token: &str, index: usize) -> &str { + token.split('.').nth(index).unwrap() + } +} diff --git a/rust/crates/keygo-server/src/domain/invite_code.rs b/rust/crates/keygo-server/src/domain/invite_code.rs index b1805a53c..ad8078a03 100644 --- a/rust/crates/keygo-server/src/domain/invite_code.rs +++ b/rust/crates/keygo-server/src/domain/invite_code.rs @@ -11,8 +11,8 @@ const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // no I, L, O, pub struct InvitePepper(Zeroizing<[u8; 32]>); impl InvitePepper { - pub fn new(bytes: [u8; 32]) -> Self { - Self(Zeroizing::new(bytes)) + pub fn new(bytes: &[u8; 32]) -> Self { + Self(Zeroizing::new(*bytes)) } pub fn hash(&self, code: &InviteCode) -> InviteHash { @@ -94,7 +94,7 @@ mod tests { use super::*; fn pepper(byte: u8) -> InvitePepper { - InvitePepper::new([byte; 32]) + InvitePepper::new(&[byte; 32]) } #[test] diff --git a/rust/crates/keygo-server/src/domain/mod.rs b/rust/crates/keygo-server/src/domain/mod.rs index 932fc72c8..26cd6745d 100644 --- a/rust/crates/keygo-server/src/domain/mod.rs +++ b/rust/crates/keygo-server/src/domain/mod.rs @@ -1,13 +1,17 @@ +mod access_token; mod device; mod invite_code; mod invite_hash; mod invite_id; mod random_id; +mod session; mod username; -pub use device::{DeviceId, DeviceInfo}; +pub use access_token::*; +pub use device::{Device, DeviceId, DeviceInfo}; pub use invite_code::{InviteCode, InvitePepper}; pub use invite_hash::InviteHash; pub use invite_id::InviteId; pub use random_id::{LoginId, RegistrationId}; +pub use session::*; pub use username::{Username, UsernameError}; diff --git a/rust/crates/keygo-server/src/domain/session.rs b/rust/crates/keygo-server/src/domain/session.rs new file mode 100644 index 000000000..4ed756cf6 --- /dev/null +++ b/rust/crates/keygo-server/src/domain/session.rs @@ -0,0 +1,111 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::{Serialize, Serializer}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; + +pub type SessionId = Uuid; + +const PREFIX: &str = "kgr_"; +// 32 --> 43 if encoded using b64urlsafe +const ENCODED_LEN: usize = PREFIX.len() + 43; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RevokeReason { + Replaced, +} + +impl RevokeReason { + pub const fn as_str(&self) -> &'static str { + match self { + RevokeReason::Replaced => "replaced", + } + } +} + +#[derive(Zeroize, ZeroizeOnDrop)] +pub struct RefreshToken([u8; 32]); + +impl RefreshToken { + pub fn generate() -> Self { + let mut token = [0u8; 32]; + getrandom::fill(token.as_mut_slice()).expect("OS random number generator unavailable"); + Self(token) + } + + pub fn expose_encoded(&self) -> Zeroizing { + let mut out = Zeroizing::new(String::with_capacity(ENCODED_LEN)); + out.push_str(PREFIX); + URL_SAFE_NO_PAD.encode_string(self.0, &mut out); + out + } + + pub fn digest(&self) -> [u8; 32] { + Sha256::digest(self.0).into() + } +} + +impl Serialize for RefreshToken { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.expose_encoded()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generated_tokens_differ() { + assert_ne!( + RefreshToken::generate().digest(), + RefreshToken::generate().digest(), + ); + } + + #[test] + fn encodes_as_prefixed_unpadded_base64url() { + let encoded = RefreshToken([0xff; 32]).expose_encoded(); + + assert_eq!( + encoded.as_str(), + "kgr___________________________________________8" + ); + assert_eq!(encoded.len(), ENCODED_LEN); + } + + #[test] + fn encoding_round_trips_the_secret() { + let token = RefreshToken::generate(); + let encoded = token.expose_encoded(); + + let raw = URL_SAFE_NO_PAD + .decode(encoded.strip_prefix(PREFIX).unwrap()) + .unwrap(); + + assert_eq!(raw, token.0); + } + + #[test] + fn serializes_as_the_encoded_token() { + let token = RefreshToken::generate(); + + assert_eq!( + serde_json::to_value(&token).unwrap(), + token.expose_encoded().as_str(), + ); + } + + #[test] + fn digest_is_sha256_of_the_raw_secret() { + assert_eq!( + hex::encode(RefreshToken([0; 32]).digest()), + "66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925", + ); + } +} diff --git a/rust/crates/keygo-server/src/secrets.rs b/rust/crates/keygo-server/src/secrets.rs index 53fa4be39..c892cadf5 100644 --- a/rust/crates/keygo-server/src/secrets.rs +++ b/rust/crates/keygo-server/src/secrets.rs @@ -1,4 +1,4 @@ -use crate::domain::InvitePepper; +use crate::domain::{AccessTokenKey, InvitePepper}; use anyhow::{Context, anyhow, ensure}; use keygo_dpop::NonceKey; use keygo_opaque::server::ServerSetup; @@ -111,7 +111,7 @@ impl TypedSecret for InvitePepper { } fn decode(stored: &str) -> anyhow::Result { - Ok(Self::new(decode(stored)?)) + Ok(Self::new(&*decode(stored)?)) } } @@ -126,7 +126,20 @@ impl TypedSecret for DpopNonceKey { } fn decode(stored: &str) -> anyhow::Result { - Ok(NonceKey::new(decode(stored)?)) + Ok(NonceKey::new(&*decode(stored)?)) + } +} + +impl TypedSecret for AccessTokenKey { + const NAME: &'static str = "access_token_key"; + type Value = Self; + + fn generate() -> anyhow::Result { + random_key() + } + + fn decode(stored: &str) -> anyhow::Result { + Ok(AccessTokenKey::new(&*decode(stored)?)) } } @@ -136,9 +149,11 @@ fn random_key() -> anyhow::Result { Ok(hex::encode(raw.as_slice()).into()) } -fn decode(stored: &str) -> anyhow::Result<[u8; 32]> { +fn decode(stored: &str) -> anyhow::Result> { let raw = Zeroizing::new(hex::decode(stored).context("not hex")?); - let bytes = raw.as_slice().try_into().context("not 32 bytes")?; + ensure!(raw.len() == 32, "not 32 bytes"); + let mut bytes = Zeroizing::new([0u8; 32]); + bytes.copy_from_slice(&raw); Ok(bytes) } @@ -147,6 +162,7 @@ secrets! { OpaqueSetup, InvitePepper, DpopNonceKey, + AccessTokenKey, } #[derive(Debug, PartialEq, Eq)] diff --git a/rust/crates/keygo-server/src/service/device.rs b/rust/crates/keygo-server/src/service/device.rs new file mode 100644 index 000000000..3ceaa6d77 --- /dev/null +++ b/rust/crates/keygo-server/src/service/device.rs @@ -0,0 +1,153 @@ +use crate::db::{devices, sessions}; +use crate::domain::{Device, DeviceId, RevokeReason}; +use sqlx::PgTransaction; +use uuid::Uuid; + +pub async fn claim( + tx: &mut PgTransaction<'_>, + user_id: Uuid, + requested: Device, +) -> sqlx::Result { + let info = &requested.info; + if let Some(id) = requested.id + && devices::attach(tx, id, user_id, info).await? + { + sessions::revoke(tx, id, RevokeReason::Replaced).await?; + return Ok(id); + } + + let device_id = DeviceId::random(); + devices::insert(tx, device_id, user_id, info).await?; + + Ok(device_id) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::users; + use crate::domain::DeviceInfo; + use crate::service::session; + use crate::testing::{JKT, count, device, insert_device, token_issuer, username}; + use serde_json::json; + use sqlx::PgPool; + + async fn claim_once(db: &PgPool, user_id: Uuid, requested: Device) -> DeviceId { + let mut tx = db.begin().await.unwrap(); + let device_id = claim(&mut tx, user_id, requested).await.unwrap(); + tx.commit().await.unwrap(); + device_id + } + + async fn open_session(db: &PgPool, user_id: Uuid, device_id: DeviceId) { + let mut conn = db.acquire().await.unwrap(); + session::issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + } + + async fn revoke_reasons(db: &PgPool, device_id: DeviceId) -> Vec> { + sqlx::query_scalar("select revoke_reason from sessions where device_id = $1") + .bind(device_id.as_uuid()) + .fetch_all(db) + .await + .unwrap() + } + + #[sqlx::test] + async fn no_id_creates_a_device(db: PgPool) { + let (user_id, existing) = insert_device(&db).await; + + let device_id = claim_once(&db, user_id, device(None)).await; + + assert_ne!(device_id, existing); + assert_eq!(count(&db, "devices").await, 2); + } + + #[sqlx::test] + async fn own_device_is_attached_and_updated(db: PgPool) { + let (user_id, existing) = insert_device(&db).await; + let info: DeviceInfo = serde_json::from_value( + json!({ "name": "Pixel 10", "platform": "android", "app_version": "2.4.0" }), + ) + .unwrap(); + let requested = Device { + id: Some(existing), + info, + }; + + let device_id = claim_once(&db, user_id, requested).await; + + assert_eq!(device_id, existing); + assert_eq!(count(&db, "devices").await, 1); + let stored: (String, String) = sqlx::query_as("select name, app_version from devices") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, ("Pixel 10".into(), "2.4.0".into())); + } + + #[sqlx::test] + async fn attaching_revokes_the_live_session_as_replaced(db: PgPool) { + let (user_id, existing) = insert_device(&db).await; + open_session(&db, user_id, existing).await; + + claim_once(&db, user_id, device(Some(existing))).await; + + assert_eq!( + revoke_reasons(&db, existing).await, + [Some("replaced".to_owned())] + ); + } + + #[sqlx::test] + async fn revoked_sessions_keep_their_reason(db: PgPool) { + let (user_id, existing) = insert_device(&db).await; + open_session(&db, user_id, existing).await; + sqlx::query("update sessions set revoked_at = now(), revoke_reason = 'logout'") + .execute(&db) + .await + .unwrap(); + + claim_once(&db, user_id, device(Some(existing))).await; + + assert_eq!( + revoke_reasons(&db, existing).await, + [Some("logout".to_owned())] + ); + } + + #[sqlx::test] + async fn another_users_device_is_not_attached(db: PgPool) { + let (owner, foreign) = insert_device(&db).await; + open_session(&db, owner, foreign).await; + let user_id = Uuid::new_v4(); + let mut conn = db.acquire().await.unwrap(); + users::insert(&mut conn, user_id, &username("bob")) + .await + .unwrap(); + + let device_id = claim_once(&db, user_id, device(Some(foreign))).await; + + assert_ne!(device_id, foreign); + assert_eq!(revoke_reasons(&db, foreign).await, [None]); + let owners: Vec = + sqlx::query_scalar("select user_id from devices order by user_id = $1") + .bind(owner) + .fetch_all(&db) + .await + .unwrap(); + assert_eq!(owners, [user_id, owner]); + } + + #[sqlx::test] + async fn unknown_device_id_creates_a_device(db: PgPool) { + let (user_id, _) = insert_device(&db).await; + let unknown = DeviceId::random(); + + let device_id = claim_once(&db, user_id, device(Some(unknown))).await; + + assert_ne!(device_id, unknown); + assert_eq!(count(&db, "devices").await, 2); + } +} diff --git a/rust/crates/keygo-server/src/service/invite/create.rs b/rust/crates/keygo-server/src/service/invite/create.rs index 44a948167..776e7a1d3 100644 --- a/rust/crates/keygo-server/src/service/invite/create.rs +++ b/rust/crates/keygo-server/src/service/invite/create.rs @@ -34,7 +34,7 @@ mod tests { const TTL: Duration = Duration::from_hours(24); fn pepper() -> InvitePepper { - InvitePepper::new([1; 32]) + InvitePepper::new(&[1; 32]) } #[sqlx::test] diff --git a/rust/crates/keygo-server/src/service/login/finish.rs b/rust/crates/keygo-server/src/service/login/finish.rs index 3ced56dd4..a702643fb 100644 --- a/rust/crates/keygo-server/src/service/login/finish.rs +++ b/rust/crates/keygo-server/src/service/login/finish.rs @@ -1,7 +1,9 @@ use crate::cache::LoginStates; use crate::db::users; -use crate::domain::{LoginId, Username}; +use crate::domain::{Device, LoginId, TokenIssuer, Username}; +use crate::service; use crate::service::login::Error; +use crate::service::session::Issued; use keygo_opaque::{CredentialFinalization, DpopBinding, OpaqueError}; use sqlx::PgPool; use uuid::Uuid; @@ -9,6 +11,7 @@ use uuid::Uuid; pub struct FinishLogin { pub login_id: LoginId, pub credential_finalization: CredentialFinalization, + pub device: Device, pub binding: DpopBinding, pub jkt: [u8; 32], } @@ -16,19 +19,21 @@ pub struct FinishLogin { pub struct Finished { pub user_id: Uuid, pub username: Username, - // TODO: session + pub session: Issued, } /// The state is consumed before verifying, so a failed finish cannot be retried with the same /// `login_id`: every password guess costs a fresh `start`. pub async fn finish( db: &PgPool, + token_issuer: &TokenIssuer, login_states: &LoginStates, input: FinishLogin, ) -> Result { let FinishLogin { login_id, credential_finalization, + device, binding, jkt, } = input; @@ -41,18 +46,30 @@ pub async fn finish( // no user left to log into; both answer exactly like a wrong password. let user_id = pending.user_id.ok_or(OpaqueError::InvalidLogin)?; - let mut conn = db.acquire().await?; - let username = users::find_username(&mut conn, user_id) + let mut tx = db.begin().await?; + let username = users::find_username(&mut tx, user_id) .await? .ok_or(OpaqueError::InvalidLogin)?; - Ok(Finished { user_id, username }) + let device_id = service::device::claim(&mut tx, user_id, device).await?; + let issued = service::session::issue(&mut tx, token_issuer, user_id, device_id, &jkt).await?; + + tx.commit().await?; + + Ok(Finished { + user_id, + username, + session: issued, + }) } #[cfg(test)] mod tests { use super::*; - use crate::testing::{PASSWORD, finish_login, register, start_login, username}; + use crate::domain::DeviceId; + use crate::testing::{ + PASSWORD, device, finish_login, register, start_login, token_issuer, username, + }; use keygo_opaque::server::ServerSetup; use std::time::Duration; @@ -63,6 +80,7 @@ mod tests { &input.credential_finalization.to_bytes(), ) .unwrap(), + device: device(None), binding: DpopBinding::from_bytes(&input.binding.to_bytes()).unwrap(), jkt: input.jkt, } @@ -75,9 +93,14 @@ mod tests { let user_id = register(&db, &setup, "ada").await; let (client, started) = start_login(&db, &login_states, &setup, "ADA").await; - let finished = finish(&db, &login_states, finish_login(client, started)) - .await - .unwrap(); + let finished = finish( + &db, + &token_issuer(), + &login_states, + finish_login(client, started, None), + ) + .await + .unwrap(); assert_eq!(finished.user_id, user_id); assert_eq!(finished.username, username("ada")); @@ -90,11 +113,16 @@ mod tests { let setup = ServerSetup::generate(); register(&db, &setup, "ada").await; let (client, started) = start_login(&db, &login_states, &setup, "ada").await; - let input = finish_login(client, started); + let input = finish_login(client, started, None); let replay = copy(&input); - finish(&db, &login_states, input).await.unwrap(); + finish(&db, &token_issuer(), &login_states, input) + .await + .unwrap(); - let err = finish(&db, &login_states, replay).await.err().unwrap(); + let err = finish(&db, &token_issuer(), &login_states, replay) + .await + .err() + .unwrap(); assert!(matches!(err, Error::Expired), "{err:?}"); } @@ -108,12 +136,18 @@ mod tests { let (client, other) = start_login(&db, &login_states, &setup, "ada").await; let forged = FinishLogin { login_id: target.login_id, - ..finish_login(client, other) + ..finish_login(client, other, None) }; let retry = copy(&forged); - let err = finish(&db, &login_states, forged).await.err().unwrap(); - let retried = finish(&db, &login_states, retry).await.err().unwrap(); + let err = finish(&db, &token_issuer(), &login_states, forged) + .await + .err() + .unwrap(); + let retried = finish(&db, &token_issuer(), &login_states, retry) + .await + .err() + .unwrap(); assert!( matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), @@ -130,10 +164,13 @@ mod tests { let (client, started) = start_login(&db, &login_states, &setup, "ada").await; let input = FinishLogin { jkt: [0x41; 32], - ..finish_login(client, started) + ..finish_login(client, started, None) }; - let err = finish(&db, &login_states, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), &login_states, input) + .await + .err() + .unwrap(); assert!( matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), @@ -181,10 +218,13 @@ mod tests { let (client, real) = start_login(&db, &login_states, &setup, "ada").await; let input = FinishLogin { login_id: fake.login_id, - ..finish_login(client, real) + ..finish_login(client, real, None) }; - let err = finish(&db, &login_states, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), &login_states, input) + .await + .err() + .unwrap(); assert!( matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), @@ -204,10 +244,15 @@ mod tests { .await .unwrap(); - let err = finish(&db, &login_states, finish_login(client, started)) - .await - .err() - .unwrap(); + let err = finish( + &db, + &token_issuer(), + &login_states, + finish_login(client, started, None), + ) + .await + .err() + .unwrap(); assert!( matches!(err, Error::Opaque(OpaqueError::InvalidLogin)), @@ -223,10 +268,13 @@ mod tests { let (client, started) = start_login(&db, &login_states, &setup, "ada").await; let input = FinishLogin { login_id: LoginId::random(), - ..finish_login(client, started) + ..finish_login(client, started, None) }; - let err = finish(&db, &login_states, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), &login_states, input) + .await + .err() + .unwrap(); assert!(matches!(err, Error::Expired), "{err:?}"); assert_eq!(login_states.count(), 1); @@ -240,11 +288,149 @@ mod tests { let (client, started) = start_login(&db, &login_states, &setup, "ada").await; tokio::time::sleep(Duration::from_millis(50)).await; - let err = finish(&db, &login_states, finish_login(client, started)) + let err = finish( + &db, + &token_issuer(), + &login_states, + finish_login(client, started, None), + ) + .await + .err() + .unwrap(); + + assert!(matches!(err, Error::Expired), "{err:?}"); + } + + async fn registered_device(db: &PgPool) -> DeviceId { + let id: Uuid = sqlx::query_scalar("select id from devices") + .fetch_one(db) + .await + .unwrap(); + serde_json::from_value(serde_json::json!(id)).unwrap() + } + + async fn sessions_by_state(db: &PgPool) -> Vec> { + sqlx::query_scalar("select revoke_reason from sessions order by revoked_at nulls last") + .fetch_all(db) + .await + .unwrap() + } + + #[sqlx::test] + async fn sign_in_on_a_known_device_replaces_its_session(db: PgPool) { + let login_states = LoginStates::new(); + let setup = ServerSetup::generate(); + register(&db, &setup, "ada").await; + let device_id = registered_device(&db).await; + let (client, started) = start_login(&db, &login_states, &setup, "ada").await; + let input = finish_login(client, started, Some(device_id)); + + let finished = finish(&db, &token_issuer(), &login_states, input) + .await + .unwrap(); + + assert_eq!(finished.session.device_id, device_id); + assert_eq!( + sessions_by_state(&db).await, + [Some("replaced".to_owned()), None] + ); + let claims = token_issuer() + .verify(finished.session.access_token.expose()) + .unwrap(); + let live: Uuid = sqlx::query_scalar("select id from sessions where revoked_at is null") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(claims.session_id(), live); + } + + #[sqlx::test] + async fn sign_in_without_a_device_id_adds_a_device(db: PgPool) { + let login_states = LoginStates::new(); + let setup = ServerSetup::generate(); + register(&db, &setup, "ada").await; + let registered = registered_device(&db).await; + let (client, started) = start_login(&db, &login_states, &setup, "ada").await; + + let finished = finish( + &db, + &token_issuer(), + &login_states, + finish_login(client, started, None), + ) + .await + .unwrap(); + + assert_ne!(finished.session.device_id, registered); + assert_eq!(sessions_by_state(&db).await, [None, None]); + } + + #[sqlx::test] + async fn failed_sign_in_leaves_the_device_signed_in(db: PgPool) { + let login_states = LoginStates::new(); + let setup = ServerSetup::generate(); + register(&db, &setup, "ada").await; + let device_id = registered_device(&db).await; + let (client, started) = start_login(&db, &login_states, &setup, "ada").await; + let input = FinishLogin { + jkt: [0x41; 32], + ..finish_login(client, started, Some(device_id)) + }; + + finish(&db, &token_issuer(), &login_states, input) .await .err() .unwrap(); - assert!(matches!(err, Error::Expired), "{err:?}"); + assert_eq!(sessions_by_state(&db).await, [None]); + } + + #[sqlx::test] + async fn concurrent_sign_ins_on_one_device_replace_each_other(db: PgPool) { + let login_states = LoginStates::new(); + let setup = ServerSetup::generate(); + register(&db, &setup, "ada").await; + let device_id = registered_device(&db).await; + let (first, first_started) = start_login(&db, &login_states, &setup, "ada").await; + let (second, second_started) = start_login(&db, &login_states, &setup, "ada").await; + let issuer = token_issuer(); + + let results = tokio::join!( + finish( + &db, + &issuer, + &login_states, + finish_login(first, first_started, Some(device_id)), + ), + finish( + &db, + &issuer, + &login_states, + finish_login(second, second_started, Some(device_id)), + ), + ); + + // The device row lock in `attach` serializes the two, so the later one replaces the earlier + // instead of tripping `sessions_one_live_per_device`. + let sessions = [results.0.unwrap(), results.1.unwrap()] + .map(|finished| { + issuer + .verify(finished.session.access_token.expose()) + .unwrap() + }) + .map(|claims| claims.session_id()); + assert_eq!( + sessions_by_state(&db).await, + [ + Some("replaced".to_owned()), + Some("replaced".to_owned()), + None + ] + ); + let live: Uuid = sqlx::query_scalar("select id from sessions where revoked_at is null") + .fetch_one(&db) + .await + .unwrap(); + assert!(sessions.contains(&live), "{live} not in {sessions:?}"); } } diff --git a/rust/crates/keygo-server/src/service/mod.rs b/rust/crates/keygo-server/src/service/mod.rs index 4c204a554..03e35c62e 100644 --- a/rust/crates/keygo-server/src/service/mod.rs +++ b/rust/crates/keygo-server/src/service/mod.rs @@ -1,3 +1,5 @@ +pub mod device; pub mod invite; pub mod login; pub mod registration; +pub mod session; diff --git a/rust/crates/keygo-server/src/service/registration/finish.rs b/rust/crates/keygo-server/src/service/registration/finish.rs index 47b338b41..c085e2a3f 100644 --- a/rust/crates/keygo-server/src/service/registration/finish.rs +++ b/rust/crates/keygo-server/src/service/registration/finish.rs @@ -1,5 +1,7 @@ use crate::db::{devices, invites, opaque_records, registrations, users}; -use crate::domain::{DeviceId, DeviceInfo, RegistrationId, Username}; +use crate::domain::{DeviceId, DeviceInfo, RegistrationId, TokenIssuer, Username}; +use crate::service; +use crate::service::session::Issued; use keygo_opaque::{RegistrationUpload, server}; use sqlx::PgPool; use thiserror::Error; @@ -18,19 +20,25 @@ pub struct FinishRegistration { pub registration_id: RegistrationId, pub registration_upload: RegistrationUpload, pub device_info: DeviceInfo, + pub jkt: [u8; 32], // TODO: key bundle } pub struct Finished { pub username: Username, - // TODO: session + pub session: Issued, } -pub async fn finish(db: &PgPool, input: FinishRegistration) -> Result { +pub async fn finish( + db: &PgPool, + token_issuer: &TokenIssuer, + input: FinishRegistration, +) -> Result { let FinishRegistration { registration_id, registration_upload, device_info, + jkt, } = input; // Pure computation, so it runs before the transaction to keep the reservation's lock short. @@ -51,10 +59,14 @@ pub async fn finish(db: &PgPool, input: FinishRegistration) -> Result) = + sqlx::query_as("select device_id, user_id, dpop_jkt from sessions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(session, (device_id, user_id, JKT.to_vec())); + let token_hash: Vec = sqlx::query_scalar("select token_hash from refresh_tokens") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(token_hash, finished.session.refresh_token.digest()); + } + #[sqlx::test] async fn finish_consumes_the_registration(db: PgPool) { let input = started(&db, Uuid::new_v4(), "ada").await; @@ -146,13 +185,15 @@ mod tests { ) .unwrap(), device_info: device_info(), + jkt: JKT, }; - finish(&db, input).await.unwrap(); + finish(&db, &token_issuer(), input).await.unwrap(); - let err = finish(&db, replay).await.err().unwrap(); + let err = finish(&db, &token_issuer(), replay).await.err().unwrap(); assert!(matches!(err, FinishError::Expired), "{err:?}"); assert_eq!(user_count(&db).await, (1, 1, 1, 0)); + assert_eq!(count(&db, "sessions").await, 1); } #[sqlx::test] @@ -163,7 +204,7 @@ mod tests { ..input }; - let err = finish(&db, unknown).await.err().unwrap(); + let err = finish(&db, &token_issuer(), unknown).await.err().unwrap(); assert!(matches!(err, FinishError::Expired), "{err:?}"); assert_eq!(user_count(&db).await, (0, 0, 0, 1)); @@ -174,7 +215,7 @@ mod tests { let input = started(&db, Uuid::new_v4(), "ada").await; expire(&db, "pending_registrations").await; - let err = finish(&db, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), input).await.err().unwrap(); assert!(matches!(err, FinishError::Expired), "{err:?}"); assert_eq!(user_count(&db).await, (0, 0, 0, 1)); @@ -190,10 +231,11 @@ mod tests { .await .unwrap(); - let err = finish(&db, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), input).await.err().unwrap(); assert!(matches!(err, FinishError::Db(_)), "{err:?}"); assert_eq!(user_count(&db).await, (1, 0, 0, 1)); + assert_eq!(count(&db, "sessions").await, 0); } #[sqlx::test] @@ -201,7 +243,7 @@ mod tests { let code = create_invite(&db).await; let input = started_with(&db, &invite_only(), Some(&code), Uuid::new_v4(), "ada").await; - finish(&db, input).await.unwrap(); + finish(&db, &token_issuer(), input).await.unwrap(); assert_eq!(user_count(&db).await, (1, 1, 1, 0)); assert_eq!(count(&db, "invites").await, 0); @@ -212,9 +254,9 @@ mod tests { let code = create_invite(&db).await; let ada = started_with(&db, &invite_only(), Some(&code), Uuid::new_v4(), "ada").await; let bob = started_with(&db, &invite_only(), Some(&code), Uuid::new_v4(), "bob").await; - finish(&db, ada).await.unwrap(); + finish(&db, &token_issuer(), ada).await.unwrap(); - let err = finish(&db, bob).await.err().unwrap(); + let err = finish(&db, &token_issuer(), bob).await.err().unwrap(); assert!(matches!(err, FinishError::InviteInvalid), "{err:?}"); assert_eq!(user_count(&db).await, (1, 1, 1, 1)); @@ -226,7 +268,7 @@ mod tests { let input = started_with(&db, &invite_only(), Some(&code), Uuid::new_v4(), "ada").await; expire(&db, "invites").await; - let err = finish(&db, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), input).await.err().unwrap(); assert!(matches!(err, FinishError::InviteInvalid), "{err:?}"); assert_eq!(user_count(&db).await, (0, 0, 0, 1)); @@ -244,7 +286,7 @@ mod tests { .await .unwrap(); - let err = finish(&db, input).await.err().unwrap(); + let err = finish(&db, &token_issuer(), input).await.err().unwrap(); assert!(matches!(err, FinishError::Db(_)), "{err:?}"); assert_eq!(count(&db, "invites").await, 1); diff --git a/rust/crates/keygo-server/src/service/session.rs b/rust/crates/keygo-server/src/service/session.rs new file mode 100644 index 000000000..db55c7d53 --- /dev/null +++ b/rust/crates/keygo-server/src/service/session.rs @@ -0,0 +1,201 @@ +use crate::db::{refresh_tokens, sessions}; +use crate::domain::{ + ACCESS_TOKEN_LIFETIME, AccessToken, DeviceId, RefreshToken, SessionId, TokenIssuer, unix_now, +}; +use sqlx::{Connection, PgConnection}; +use std::time::Duration; +use uuid::Uuid; + +pub const SESSION_LIFETIME: Duration = Duration::from_hours(180 * 24); +pub const REFRESH_TTL: Duration = Duration::from_hours(30 * 24); + +pub struct Issued { + pub device_id: DeviceId, + pub access_token: AccessToken, + pub access_expires_in: Duration, + pub refresh_token: RefreshToken, + pub refresh_expires_in: Duration, +} + +pub async fn issue( + conn: &mut PgConnection, + token_issuer: &TokenIssuer, + user_id: Uuid, + device_id: DeviceId, + jkt: &[u8; 32], +) -> sqlx::Result { + let auth_time = unix_now(); + + let mut tx = conn.begin().await?; + let session_id = SessionId::new_v4(); + sessions::insert( + &mut tx, + session_id, + user_id, + device_id, + jkt, + auth_time, + SESSION_LIFETIME, + ) + .await?; + + let refresh_token = RefreshToken::generate(); + refresh_tokens::insert(&mut tx, session_id, &refresh_token.digest(), REFRESH_TTL).await?; + tx.commit().await?; + + Ok(Issued { + device_id, + access_token: token_issuer.issue(user_id, session_id, auth_time, jkt), + access_expires_in: ACCESS_TOKEN_LIFETIME, + refresh_token, + refresh_expires_in: REFRESH_TTL, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::RevokeReason; + use crate::testing::{JKT, count, expires_in_secs, insert_device, token_issuer}; + use sqlx::PgPool; + + fn assert_expires_after(remaining: f64, ttl: Duration) { + assert!( + (ttl.as_secs_f64() - 5.0..=ttl.as_secs_f64()).contains(&remaining), + "{remaining}" + ); + } + + #[sqlx::test] + async fn issue_binds_a_session_to_the_device_and_key(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + let issued = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + + assert_eq!(issued.device_id, device_id); + assert_eq!(issued.refresh_expires_in, REFRESH_TTL); + let stored: (Uuid, Uuid, Vec) = + sqlx::query_as("select device_id, user_id, dpop_jkt from sessions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, (device_id.as_uuid(), user_id, JKT.to_vec())); + assert_expires_after(expires_in_secs(&db, "sessions").await, SESSION_LIFETIME); + } + + #[sqlx::test] + async fn issue_signs_an_access_token_for_the_stored_session(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + let issued = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + + let claims = token_issuer().verify(issued.access_token.expose()).unwrap(); + let (session_id, auth_time): (Uuid, i64) = + sqlx::query_as("select id, extract(epoch from auth_time)::int8 from sessions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(claims.user_id(), user_id); + assert_eq!(claims.session_id(), session_id); + assert_eq!(claims.jkt(), &JKT); + assert_eq!(claims.auth_time(), auth_time as u64); + assert!(claims.is_fresh()); + assert_eq!(issued.access_expires_in, ACCESS_TOKEN_LIFETIME); + } + + #[sqlx::test] + async fn issue_stores_only_the_refresh_token_hash(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + let issued = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + + let stored: Vec = sqlx::query_scalar("select token_hash from refresh_tokens") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, issued.refresh_token.digest()); + assert_expires_after(expires_in_secs(&db, "refresh_tokens").await, REFRESH_TTL); + } + + #[sqlx::test] + async fn each_issue_opens_its_own_session(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + let first = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + sessions::revoke(&mut conn, device_id, RevokeReason::Replaced) + .await + .unwrap(); + let second = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + + assert_ne!(first.refresh_token.digest(), second.refresh_token.digest()); + assert_eq!(count(&db, "sessions").await, 2); + assert_eq!(count(&db, "refresh_tokens").await, 2); + } + + #[sqlx::test] + async fn a_device_has_at_most_one_live_session(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + + let err = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .err() + .unwrap(); + + assert!(err.as_database_error().unwrap().is_unique_violation()); + assert_eq!(count(&db, "sessions").await, 1); + assert_eq!(count(&db, "refresh_tokens").await, 1); + } + + #[sqlx::test] + async fn issue_rolls_back_with_the_outer_transaction(db: PgPool) { + let (user_id, device_id) = insert_device(&db).await; + let mut tx = db.begin().await.unwrap(); + + issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap(); + tx.rollback().await.unwrap(); + + assert_eq!(count(&db, "sessions").await, 0); + assert_eq!(count(&db, "refresh_tokens").await, 0); + } + + #[sqlx::test] + async fn issue_for_an_unknown_device_stores_nothing(db: PgPool) { + let (user_id, _) = insert_device(&db).await; + let mut conn = db.acquire().await.unwrap(); + + let err = issue( + &mut conn, + &token_issuer(), + user_id, + DeviceId::random(), + &JKT, + ) + .await + .err() + .unwrap(); + + assert!(err.as_database_error().unwrap().is_foreign_key_violation()); + assert_eq!(count(&db, "sessions").await, 0); + assert_eq!(count(&db, "refresh_tokens").await, 0); + } +} diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 218033327..0591e54d9 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -1,7 +1,9 @@ use crate::api::{AppState, router}; use crate::cache::LoginStates; -use crate::db::invites; -use crate::domain::{DeviceInfo, InviteHash, InvitePepper, Username}; +use crate::db::{devices, invites, users}; +use crate::domain::{ + AccessTokenKey, Device, DeviceId, DeviceInfo, InviteHash, InvitePepper, TokenIssuer, Username, +}; use crate::service::invite; use crate::service::login::{self, FinishLogin, StartLogin}; use crate::service::registration::{self, FinishRegistration, Signup, StartRegistration}; @@ -21,7 +23,12 @@ use tower::ServiceExt; use uuid::Uuid; pub const PASSWORD: &[u8] = b"correct horse battery staple"; -const JKT: [u8; 32] = [7; 32]; +pub const JKT: [u8; 32] = [7; 32]; +pub const ISS: &str = "http://localhost"; + +pub fn token_issuer() -> TokenIssuer { + TokenIssuer::new(AccessTokenKey::new(&[0; 32]), ISS) +} pub fn username(raw: &str) -> Username { Username::parse(raw).unwrap() @@ -32,6 +39,13 @@ pub fn device_json() -> Value { pub fn device_info() -> DeviceInfo { serde_json::from_value(device_json()).unwrap() } +pub fn device(id: Option) -> Device { + Device { + id, + info: device_info(), + } +} + pub async fn register(db: &PgPool, setup: &ServerSetup, name: &str) -> Uuid { let user_id = Uuid::new_v4(); let (client, registration_request) = ClientRegistration::start(PASSWORD).unwrap(); @@ -53,11 +67,26 @@ pub async fn register(db: &PgPool, setup: &ServerSetup, name: &str) -> Uuid { registration_id: started.registration_id, registration_upload: finish.upload, device_info: device_info(), + jkt: JKT, }; - registration::finish(db, input).await.unwrap(); + registration::finish(db, &token_issuer(), input) + .await + .unwrap(); user_id } +pub async fn insert_device(db: &PgPool) -> (Uuid, DeviceId) { + let user_id = Uuid::new_v4(); + let device_id = DeviceId::random(); + let mut conn = db.acquire().await.unwrap(); + users::insert(&mut conn, user_id, &username("ada")) + .await + .unwrap(); + devices::insert(&mut conn, device_id, user_id, &device_info()) + .await + .unwrap(); + (user_id, device_id) +} pub async fn start_login( db: &PgPool, login_states: &LoginStates, @@ -74,13 +103,18 @@ pub async fn start_login( login::start(db, login_states, setup, input).await.unwrap(), ) } -pub fn finish_login(client: ClientLogin, started: login::Started) -> FinishLogin { +pub fn finish_login( + client: ClientLogin, + started: login::Started, + device_id: Option, +) -> FinishLogin { let finish = client .finish(PASSWORD, started.credential_response) .unwrap(); FinishLogin { login_id: started.login_id, credential_finalization: finish.finalization, + device: device(device_id), binding: finish.session_key.dpop_binding(&JKT), jkt: JKT, } @@ -101,10 +135,10 @@ pub async fn insert_invite(db: &PgPool, hash: InviteHash) { const INVITE_PEPPER: [u8; 32] = [1; 32]; pub fn invite_only() -> Signup { - Signup::InviteOnly(Arc::new(InvitePepper::new(INVITE_PEPPER))) + Signup::InviteOnly(Arc::new(InvitePepper::new(&INVITE_PEPPER))) } pub async fn create_invite(db: &PgPool) -> String { - let pepper = InvitePepper::new(INVITE_PEPPER); + let pepper = InvitePepper::new(&INVITE_PEPPER); let created = invite::create(db, &pepper, Duration::from_hours(24)) .await .unwrap(); @@ -137,12 +171,13 @@ pub async fn expires_in_secs(db: &PgPool, table: &str) -> f64 { /// Requests that must see each other's login states share one `AppState` through `post_to`. pub fn app_state(db: &PgPool, setup: &ServerSetup) -> AppState { AppState { - public_url: url::Url::parse("http://localhost").unwrap(), + public_url: url::Url::parse(ISS).unwrap(), signup: Signup::Open, opaque_state: setup.clone(), db: db.clone(), login_states: LoginStates::new(), - dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new([0; 32]))), + dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new(&[0; 32]))), + token_issuer: Arc::new(token_issuer()), } } pub async fn post(db: &PgPool, setup: &ServerSetup, uri: &str, body: Value) -> (StatusCode, Value) { From 1ae1200d50746259f1e2465073fd8c42612bdc21 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 28 Oct 2026 18:53:36 +0100 Subject: [PATCH 13/26] feat(api): implement /auth/token endpoint --- ...a109eca7c1e975b737d3871e49f5a8ef2cd1c.json | 25 ++ ...315981759988f51c2f6dad1be5d4d58069705.json | 15 + ...a113b240dc6b8f43565d19ce7038b93dac605.json | 104 +++++++ ...f5fbe1f0a9edd0cfdf6494b1575a509379a11.json | 14 + ...5e8fac40faa2f8b6e019018f4f97b8b4cd352.json | 19 -- ...c0059c3a16c97b9d06a63bc3b1cb012614c30.json | 18 ++ .../migrations/20261014141017_init.sql | 3 +- rust/crates/keygo-server/src/api/error.rs | 56 +++- .../keygo-server/src/api/routes/auth/mod.rs | 4 + .../keygo-server/src/api/routes/auth/token.rs | 159 +++++++++++ .../keygo-server/src/db/refresh_tokens.rs | 270 +++++++++++++++++- rust/crates/keygo-server/src/db/sessions.rs | 121 ++++++-- rust/crates/keygo-server/src/domain/device.rs | 6 + .../crates/keygo-server/src/domain/session.rs | 170 ++++++++++- .../crates/keygo-server/src/server/sweeper.rs | 13 +- .../crates/keygo-server/src/service/device.rs | 2 +- .../src/service/registration/finish.rs | 12 +- .../keygo-server/src/service/session.rs | 255 ++++++++++++++++- 18 files changed, 1173 insertions(+), 93 deletions(-) create mode 100644 rust/crates/keygo-server/.sqlx/query-0e560be618cf6017e427c84dc19a109eca7c1e975b737d3871e49f5a8ef2cd1c.json create mode 100644 rust/crates/keygo-server/.sqlx/query-5a49901747fc1ae9e00b42b4f18315981759988f51c2f6dad1be5d4d58069705.json create mode 100644 rust/crates/keygo-server/.sqlx/query-6b3a7a0016dcbeedb3e83038396a113b240dc6b8f43565d19ce7038b93dac605.json create mode 100644 rust/crates/keygo-server/.sqlx/query-7cf296c93696be87e49ef7ef3e9f5fbe1f0a9edd0cfdf6494b1575a509379a11.json delete mode 100644 rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json create mode 100644 rust/crates/keygo-server/.sqlx/query-c8e5bdc795f215a1ae41e52e974c0059c3a16c97b9d06a63bc3b1cb012614c30.json create mode 100644 rust/crates/keygo-server/src/api/routes/auth/token.rs diff --git a/rust/crates/keygo-server/.sqlx/query-0e560be618cf6017e427c84dc19a109eca7c1e975b737d3871e49f5a8ef2cd1c.json b/rust/crates/keygo-server/.sqlx/query-0e560be618cf6017e427c84dc19a109eca7c1e975b737d3871e49f5a8ef2cd1c.json new file mode 100644 index 000000000..372aef0eb --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-0e560be618cf6017e427c84dc19a109eca7c1e975b737d3871e49f5a8ef2cd1c.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "with claimed as (\n update refresh_tokens set rotated_at = now()\n where token_hash = $1 and rotated_at is null\n returning session_id\n )\n insert into refresh_tokens (token_hash, session_id, expires_at)\n select $2, s.id, least(now() + make_interval(secs => $3), s.expires_at)\n from claimed c\n join sessions s on s.id = c.session_id\n returning extract(epoch from expires_at - now())::int8 as \"expires_in!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "expires_in!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Bytea", + "Bytea", + "Float8" + ] + }, + "nullable": [ + null + ] + }, + "hash": "0e560be618cf6017e427c84dc19a109eca7c1e975b737d3871e49f5a8ef2cd1c" +} diff --git a/rust/crates/keygo-server/.sqlx/query-5a49901747fc1ae9e00b42b4f18315981759988f51c2f6dad1be5d4d58069705.json b/rust/crates/keygo-server/.sqlx/query-5a49901747fc1ae9e00b42b4f18315981759988f51c2f6dad1be5d4d58069705.json new file mode 100644 index 000000000..a32eba71d --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-5a49901747fc1ae9e00b42b4f18315981759988f51c2f6dad1be5d4d58069705.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "update sessions\n set revoked_at = now(), revoke_reason = $1\n where id = $2 and revoked_at is null", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "5a49901747fc1ae9e00b42b4f18315981759988f51c2f6dad1be5d4d58069705" +} diff --git a/rust/crates/keygo-server/.sqlx/query-6b3a7a0016dcbeedb3e83038396a113b240dc6b8f43565d19ce7038b93dac605.json b/rust/crates/keygo-server/.sqlx/query-6b3a7a0016dcbeedb3e83038396a113b240dc6b8f43565d19ce7038b93dac605.json new file mode 100644 index 000000000..8419a12cb --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-6b3a7a0016dcbeedb3e83038396a113b240dc6b8f43565d19ce7038b93dac605.json @@ -0,0 +1,104 @@ +{ + "db_name": "PostgreSQL", + "query": "select rt.session_id,\n d.user_id,\n s.device_id,\n s.dpop_jkt,\n extract(epoch from s.auth_time)::int8 as \"auth_time!\",\n s.revoked_at is not null as \"revoked!\",\n s.revoke_reason,\n rt.rotated_at is not null as \"rotated!\",\n (rt.expires_at <= now() or s.expires_at <= now()) as \"expired!\"\n from refresh_tokens rt\n join sessions s on s.id = rt.session_id\n join devices d on d.id = s.device_id\n where rt.token_hash = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "session_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "refresh_tokens", + "name": "session_id" + } + } + }, + { + "ordinal": 1, + "name": "user_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "devices", + "name": "user_id" + } + } + }, + { + "ordinal": 2, + "name": "device_id", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "sessions", + "name": "device_id" + } + } + }, + { + "ordinal": 3, + "name": "dpop_jkt", + "type_info": "Bytea", + "origin": { + "Table": { + "table": "sessions", + "name": "dpop_jkt" + } + } + }, + { + "ordinal": 4, + "name": "auth_time!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 5, + "name": "revoked!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "revoke_reason", + "type_info": "Text", + "origin": { + "Table": { + "table": "sessions", + "name": "revoke_reason" + } + } + }, + { + "ordinal": 7, + "name": "rotated!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 8, + "name": "expired!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Bytea" + ] + }, + "nullable": [ + false, + false, + false, + false, + null, + null, + true, + null, + null + ] + }, + "hash": "6b3a7a0016dcbeedb3e83038396a113b240dc6b8f43565d19ce7038b93dac605" +} diff --git a/rust/crates/keygo-server/.sqlx/query-7cf296c93696be87e49ef7ef3e9f5fbe1f0a9edd0cfdf6494b1575a509379a11.json b/rust/crates/keygo-server/.sqlx/query-7cf296c93696be87e49ef7ef3e9f5fbe1f0a9edd0cfdf6494b1575a509379a11.json new file mode 100644 index 000000000..27dc8c29b --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-7cf296c93696be87e49ef7ef3e9f5fbe1f0a9edd0cfdf6494b1575a509379a11.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "delete from sessions\n where least(revoked_at, expires_at) <= now() - make_interval(secs => $1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Float8" + ] + }, + "nullable": [] + }, + "hash": "7cf296c93696be87e49ef7ef3e9f5fbe1f0a9edd0cfdf6494b1575a509379a11" +} diff --git a/rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json b/rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json deleted file mode 100644 index 535d4b16b..000000000 --- a/rust/crates/keygo-server/.sqlx/query-9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "insert into sessions (id, device_id, user_id, dpop_jkt, auth_time, expires_at)\n values ($1, $2, $3, $4, to_timestamp($5::int8), now() + make_interval(secs => $6))", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Uuid", - "Uuid", - "Bytea", - "Int8", - "Float8" - ] - }, - "nullable": [] - }, - "hash": "9307c45211a0383a318bc70dc315e8fac40faa2f8b6e019018f4f97b8b4cd352" -} diff --git a/rust/crates/keygo-server/.sqlx/query-c8e5bdc795f215a1ae41e52e974c0059c3a16c97b9d06a63bc3b1cb012614c30.json b/rust/crates/keygo-server/.sqlx/query-c8e5bdc795f215a1ae41e52e974c0059c3a16c97b9d06a63bc3b1cb012614c30.json new file mode 100644 index 000000000..4e21e5f32 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-c8e5bdc795f215a1ae41e52e974c0059c3a16c97b9d06a63bc3b1cb012614c30.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "insert into sessions (id, device_id, dpop_jkt, auth_time, expires_at)\n values ($1, $2, $3, to_timestamp($4::int8), now() + make_interval(secs => $5))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Uuid", + "Bytea", + "Int8", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "c8e5bdc795f215a1ae41e52e974c0059c3a16c97b9d06a63bc3b1cb012614c30" +} diff --git a/rust/crates/keygo-server/migrations/20261014141017_init.sql b/rust/crates/keygo-server/migrations/20261014141017_init.sql index 0a2191154..0b8f2f124 100644 --- a/rust/crates/keygo-server/migrations/20261014141017_init.sql +++ b/rust/crates/keygo-server/migrations/20261014141017_init.sql @@ -20,7 +20,6 @@ create table sessions ( id uuid primary key, device_id uuid not null references devices on delete cascade, - user_id uuid not null references users on delete cascade, dpop_jkt bytea not null, auth_time timestamptz not null, created_at timestamptz not null default now(), @@ -36,7 +35,7 @@ create table refresh_tokens session_id uuid not null references sessions on delete cascade, issued_at timestamptz not null default now(), expires_at timestamptz not null, - used_at timestamptz + rotated_at timestamptz ); create table invites diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index 767500a3c..85bdf5f39 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -25,6 +25,9 @@ pub enum ErrorCode { InviteInvalid, RegistrationExpired, LoginExpired, + // session + RefreshExpired, + SessionRevoked, // dpop InvalidDpopProof, UseDpopNonce, @@ -40,7 +43,9 @@ impl ErrorCode { | Self::LoginExpired | Self::InvalidDpopProof | Self::UseDpopNonce => StatusCode::BAD_REQUEST, - Self::InvalidCredentials => StatusCode::UNAUTHORIZED, + Self::InvalidCredentials | Self::RefreshExpired | Self::SessionRevoked => { + StatusCode::UNAUTHORIZED + } Self::InviteRequired | Self::InviteInvalid => StatusCode::FORBIDDEN, Self::NotFound => StatusCode::NOT_FOUND, Self::UsernameTaken | Self::UserIdTaken => StatusCode::CONFLICT, @@ -59,6 +64,10 @@ pub trait HttpError: std::error::Error + Send + Sync + 'static { fn headers(&self) -> HeaderMap { HeaderMap::new() } + + fn reason(&self) -> Option<&'static str> { + None + } } pub struct ServerError(Box); @@ -74,6 +83,7 @@ impl From for ServerError { impl IntoResponse for ServerError { fn into_response(self) -> Response { let (code, status, headers) = (self.0.code(), self.0.status(), self.0.headers()); + let reason = self.0.reason(); let message = if status.is_server_error() { let source = anyhow::Error::from_boxed(self.0); tracing::error!(?code, "request failed: {source:#}"); @@ -82,12 +92,12 @@ impl IntoResponse for ServerError { self.0.to_string() }; - ( - status, - headers, - axum::Json(json!({"code": code, "message": message})), - ) - .into_response() + let mut body = json!({"code": code, "message": message}); + if let Some(reason) = reason { + body["reason"] = reason.into(); + } + + (status, headers, axum::Json(body)).into_response() } } @@ -235,6 +245,38 @@ mod tests { } } + #[derive(Debug, thiserror::Error)] + #[error("revoked")] + struct Revoked; + + impl HttpError for Revoked { + fn code(&self) -> ErrorCode { + ErrorCode::SessionRevoked + } + + fn reason(&self) -> Option<&'static str> { + Some("replaced") + } + } + + #[tokio::test] + async fn error_reason_reaches_the_body() { + let (status, body) = render(Revoked).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!( + body, + json!({ "code": "session_revoked", "message": "revoked", "reason": "replaced" }), + ); + } + + #[tokio::test] + async fn errors_without_a_reason_omit_it() { + let (_, body) = render(NotFound).await; + + assert!(body.get("reason").is_none()); + } + #[tokio::test] async fn error_headers_reach_the_response() { let response = ServerError::from(Challenge).into_response(); diff --git a/rust/crates/keygo-server/src/api/routes/auth/mod.rs b/rust/crates/keygo-server/src/api/routes/auth/mod.rs index a3bd25205..0b1f2dedf 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/mod.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/mod.rs @@ -1,10 +1,13 @@ use crate::api::AppState; +use crate::api::routes::auth::token::token; use axum::Router; use axum::extract::DefaultBodyLimit; +use axum::routing::post; mod login; mod register; mod session; +mod token; /// The largest legitimate body is a key bundle of a few hundred bytes. Every auth endpoint is /// reachable without a token, so anything larger is refused before it is buffered and parsed. @@ -15,5 +18,6 @@ pub fn router() -> Router { Router::new() .nest("/register", register::router()) .nest("/login", login::router()) + .route("/token", post(token)) .layer(DefaultBodyLimit::max(MAX_BODY_BYTES)) } diff --git a/rust/crates/keygo-server/src/api/routes/auth/token.rs b/rust/crates/keygo-server/src/api/routes/auth/token.rs new file mode 100644 index 000000000..0c7720d4d --- /dev/null +++ b/rust/crates/keygo-server/src/api/routes/auth/token.rs @@ -0,0 +1,159 @@ +use crate::api::dpop::DpopProof; +use crate::api::routes::auth::session::Session; +use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; +use crate::domain::{RefreshToken, RevokeReason}; +use crate::service::session; +use crate::service::session::RefreshError; +use axum::extract::State; +use serde::Deserialize; + +#[derive(Deserialize)] +pub struct TokenRequest { + refresh_token: RefreshToken, +} + +impl HttpError for RefreshError { + fn code(&self) -> ErrorCode { + match self { + Self::Revoked(_) => ErrorCode::SessionRevoked, + Self::Expired => ErrorCode::RefreshExpired, + Self::WrongKey => ErrorCode::InvalidDpopProof, + Self::Db(_) => ErrorCode::Internal, + } + } + + fn reason(&self) -> Option<&'static str> { + match self { + Self::Revoked(reason) => reason.as_ref().map(RevokeReason::as_str), + _ => None, + } + } +} + +pub async fn token( + State(state): State, + proof: DpopProof, + Json(request): Json, +) -> ServerResult> { + let issued = session::refresh( + &state.db, + &state.token_issuer, + &request.refresh_token, + &proof.jkt, + ) + .await?; + + Ok(Json(issued.into())) +} + +#[cfg(test)] +mod tests { + use crate::testing::{ + PASSWORD, app_state, device_json, post_to, post_with_proof, prover, register, + }; + use axum::http::StatusCode; + use keygo_dpop::DpopProver; + use keygo_dpop::testing::TestSigner; + use keygo_opaque::CredentialResponse; + use keygo_opaque::client::ClientLogin; + use keygo_opaque::server::ServerSetup; + use serde_json::{Value, json}; + use sqlx::PgPool; + + const TOKEN: &str = "/api/v1/auth/token"; + + /// Signs in over HTTP and returns the session object. + async fn sign_in(state: &crate::api::AppState, prover: &DpopProver) -> Value { + let (client, request) = ClientLogin::start(PASSWORD).unwrap(); + let body = json!({ "username": "ada", "credential_request": request.to_base64() }); + let (_, started) = post_to(state.clone(), "/api/v1/auth/login/start", body).await; + let response = + CredentialResponse::from_base64(started["credential_response"].as_str().unwrap()) + .unwrap(); + let finish = client.finish(PASSWORD, response).unwrap(); + let body = json!({ + "login_id": started["login_id"], + "credential_finalization": finish.finalization.to_base64(), + "dpop_binding": finish.session_key.dpop_binding(prover.jkt()).to_base64(), + "device": device_json(), + }); + let (status, finished) = + post_with_proof(state, prover, "/api/v1/auth/login/finish", body).await; + assert_eq!(status, StatusCode::OK); + finished["session"].clone() + } + + fn token_body(session: &Value) -> Value { + json!({ "refresh_token": session["refresh_token"] }) + } + + #[sqlx::test] + async fn refreshes_over_http(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let prover = prover(); + let session = sign_in(&state, &prover).await; + + let (status, refreshed) = + post_with_proof(&state, &prover, TOKEN, token_body(&session)).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(refreshed["device_id"], session["device_id"]); + assert_ne!(refreshed["refresh_token"], session["refresh_token"]); + } + + #[sqlx::test] + async fn reuse_answers_session_revoked_with_its_reason(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let prover = prover(); + let session = sign_in(&state, &prover).await; + post_with_proof(&state, &prover, TOKEN, token_body(&session)).await; + + let (status, body) = post_with_proof(&state, &prover, TOKEN, token_body(&session)).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert_eq!(body["reason"], "reuse_detected"); + } + + #[sqlx::test] + async fn another_key_is_an_invalid_proof(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let session = sign_in(&state, &prover()).await; + let other = DpopProver::new(TestSigner::from_seed(8)); + + let (status, body) = post_with_proof(&state, &other, TOKEN, token_body(&session)).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "invalid_dpop_proof"); + } + + #[sqlx::test] + async fn unknown_token_is_revoked_without_a_reason(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let token = crate::domain::RefreshToken::generate(); + let body = json!({ "refresh_token": token.expose_encoded().as_str() }); + + let (status, body) = post_with_proof(&state, &prover(), TOKEN, body).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert!(body.get("reason").is_none()); + } + + #[sqlx::test] + async fn malformed_token_is_an_invalid_request(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let body = json!({ "refresh_token": "kgr_short" }); + + let (status, body) = post_with_proof(&state, &prover(), TOKEN, body).await; + + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "invalid_request"); + } +} diff --git a/rust/crates/keygo-server/src/db/refresh_tokens.rs b/rust/crates/keygo-server/src/db/refresh_tokens.rs index feb5482cf..3262f3e29 100644 --- a/rust/crates/keygo-server/src/db/refresh_tokens.rs +++ b/rust/crates/keygo-server/src/db/refresh_tokens.rs @@ -1,6 +1,8 @@ -use crate::domain::SessionId; +use crate::db::corrupt; +use crate::domain::{DeviceId, RevokeReason, SessionId}; use sqlx::PgConnection; use std::time::Duration; +use uuid::Uuid; pub async fn insert( conn: &mut PgConnection, @@ -21,6 +23,101 @@ pub async fn insert( Ok(()) } +#[derive(Debug, PartialEq, Eq)] +pub enum TokenStatus { + Revoked(Option), + Expired, + Rotated, + Live, +} + +pub struct Presented { + pub session_id: SessionId, + pub user_id: Uuid, + pub device_id: DeviceId, + pub dpop_jkt: [u8; 32], + pub auth_time: u64, + pub status: TokenStatus, +} + +pub async fn find(conn: &mut PgConnection, hash: &[u8; 32]) -> sqlx::Result> { + let Some(row) = sqlx::query!( + r#"select rt.session_id, + d.user_id, + s.device_id, + s.dpop_jkt, + extract(epoch from s.auth_time)::int8 as "auth_time!", + s.revoked_at is not null as "revoked!", + s.revoke_reason, + rt.rotated_at is not null as "rotated!", + (rt.expires_at <= now() or s.expires_at <= now()) as "expired!" + from refresh_tokens rt + join sessions s on s.id = rt.session_id + join devices d on d.id = s.device_id + where rt.token_hash = $1 + "#, + hash + ) + .fetch_optional(conn) + .await? + else { + return Ok(None); + }; + + let status = if row.revoked { + let reason = row.revoke_reason.as_deref().map(str::parse).transpose(); + TokenStatus::Revoked(reason.map_err(corrupt)?) + } else if row.rotated { + TokenStatus::Rotated + } else if row.expired { + TokenStatus::Expired + } else { + TokenStatus::Live + }; + + Ok(Some(Presented { + session_id: row.session_id, + user_id: row.user_id, + device_id: row.device_id.into(), + dpop_jkt: row.dpop_jkt.as_slice().try_into().map_err(corrupt)?, + auth_time: u64::try_from(row.auth_time).map_err(corrupt)?, + status, + })) +} + +pub async fn rotate( + conn: &mut PgConnection, + old_hash: &[u8; 32], + new_hash: &[u8; 32], + ttl: Duration, +) -> sqlx::Result> { + let record = sqlx::query!( + r#"with claimed as ( + update refresh_tokens set rotated_at = now() + where token_hash = $1 and rotated_at is null + returning session_id + ) + insert into refresh_tokens (token_hash, session_id, expires_at) + select $2, s.id, least(now() + make_interval(secs => $3), s.expires_at) + from claimed c + join sessions s on s.id = c.session_id + returning extract(epoch from expires_at - now())::int8 as "expires_in!""#, + old_hash, + new_hash, + ttl.as_secs_f64(), + ) + .fetch_optional(conn) + .await?; + + record + .map(|record| { + u64::try_from(record.expires_in) + .map(Duration::from_secs) + .map_err(corrupt) + }) + .transpose() +} + #[cfg(test)] mod tests { use super::*; @@ -30,26 +127,27 @@ mod tests { const TTL: Duration = Duration::from_hours(24); const HASH: [u8; 32] = [9; 32]; + const CHILD: [u8; 32] = [10; 32]; async fn insert_session(db: &PgPool) -> SessionId { - let (user_id, device_id) = insert_device(db).await; + let (_, device_id) = insert_device(db).await; let session_id = SessionId::new_v4(); let mut conn = db.acquire().await.unwrap(); - sessions::insert(&mut conn, session_id, user_id, device_id, &JKT, 0, TTL) + sessions::insert(&mut conn, session_id, device_id, &JKT, 0, TTL) .await .unwrap(); session_id } #[sqlx::test] - async fn token_is_stored_unused_under_its_hash(db: PgPool) { + async fn token_is_stored_unrotated_under_its_hash(db: PgPool) { let session_id = insert_session(&db).await; let mut conn = db.acquire().await.unwrap(); insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); let stored: (Vec, SessionId, bool) = - sqlx::query_as("select token_hash, session_id, used_at is null from refresh_tokens") + sqlx::query_as("select token_hash, session_id, rotated_at is null from refresh_tokens") .fetch_one(&db) .await .unwrap(); @@ -106,4 +204,166 @@ mod tests { assert_eq!(count(&db, "refresh_tokens").await, 0); } + + async fn status(db: &PgPool, hash: &[u8; 32]) -> TokenStatus { + let mut conn = db.acquire().await.unwrap(); + find(&mut conn, hash).await.unwrap().unwrap().status + } + + async fn set(db: &PgPool, sql: &str) { + sqlx::query(sqlx::AssertSqlSafe(sql.to_owned())) + .execute(db) + .await + .unwrap(); + } + + #[sqlx::test] + async fn find_returns_the_session_of_a_live_token(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + + let presented = find(&mut conn, &HASH).await.unwrap().unwrap(); + + let (user_id, device_id): (Uuid, Uuid) = sqlx::query_as("select user_id, id from devices") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(presented.session_id, session_id); + assert_eq!(presented.user_id, user_id); + assert_eq!(presented.device_id.as_uuid(), device_id); + assert_eq!(presented.dpop_jkt, JKT); + assert_eq!(presented.status, TokenStatus::Live); + } + + #[sqlx::test] + async fn find_of_an_unknown_token_is_none(db: PgPool) { + let mut conn = db.acquire().await.unwrap(); + + assert!(find(&mut conn, &HASH).await.unwrap().is_none()); + } + + #[sqlx::test] + async fn revocation_decides_before_anything_else(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + rotate(&mut conn, &HASH, &CHILD, TTL).await.unwrap(); + sessions::revoke(&mut conn, session_id, RevokeReason::Replaced) + .await + .unwrap(); + set( + &db, + "update sessions set expires_at = now() - interval '1 second'", + ) + .await; + + assert_eq!( + status(&db, &HASH).await, + TokenStatus::Revoked(Some(RevokeReason::Replaced)), + ); + } + + #[sqlx::test] + async fn an_expired_session_expires_its_live_token(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + rotate(&mut conn, &HASH, &CHILD, TTL).await.unwrap(); + set( + &db, + "update sessions set expires_at = now() - interval '1 second'", + ) + .await; + + assert_eq!(status(&db, &HASH).await, TokenStatus::Rotated); + assert_eq!(status(&db, &CHILD).await, TokenStatus::Expired); + } + + #[sqlx::test] + async fn a_rotated_token_stays_rotated_after_it_expires(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + rotate(&mut conn, &HASH, &CHILD, TTL).await.unwrap(); + set( + &db, + "update refresh_tokens set expires_at = now() - interval '1 second'", + ) + .await; + + assert_eq!(status(&db, &HASH).await, TokenStatus::Rotated); + assert_eq!(status(&db, &CHILD).await, TokenStatus::Expired); + } + + #[sqlx::test] + async fn stored_unknown_revoke_reason_is_corrupt(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + set( + &db, + "update sessions set revoked_at = now(), revoke_reason = 'nope'", + ) + .await; + + let err = find(&mut conn, &HASH).await.err().unwrap(); + + assert!(matches!(err, sqlx::Error::Decode(_))); + } + + #[sqlx::test] + async fn rotate_marks_the_token_and_stores_its_child(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + + let expires_in = rotate(&mut conn, &HASH, &CHILD, TTL) + .await + .unwrap() + .unwrap(); + + assert!(TTL - expires_in <= Duration::from_secs(5), "{expires_in:?}"); + assert_eq!(status(&db, &HASH).await, TokenStatus::Rotated); + assert_eq!(status(&db, &CHILD).await, TokenStatus::Live); + let child_session: SessionId = + sqlx::query_scalar("select session_id from refresh_tokens where token_hash = $1") + .bind(CHILD.as_slice()) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(child_session, session_id); + } + + #[sqlx::test] + async fn rotate_caps_the_child_at_the_session_expiry(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + set( + &db, + "update sessions set expires_at = now() + interval '1 hour'", + ) + .await; + + let expires_in = rotate(&mut conn, &HASH, &CHILD, TTL) + .await + .unwrap() + .unwrap(); + + assert_eq!(expires_in, Duration::from_hours(1)); + } + + #[sqlx::test] + async fn rotate_claims_a_token_only_once(db: PgPool) { + let session_id = insert_session(&db).await; + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, session_id, &HASH, TTL).await.unwrap(); + rotate(&mut conn, &HASH, &CHILD, TTL).await.unwrap(); + + let second = rotate(&mut conn, &HASH, &[11; 32], TTL).await.unwrap(); + + assert!(second.is_none()); + assert_eq!(count(&db, "refresh_tokens").await, 2); + } } diff --git a/rust/crates/keygo-server/src/db/sessions.rs b/rust/crates/keygo-server/src/db/sessions.rs index e9eefded1..21907aeea 100644 --- a/rust/crates/keygo-server/src/db/sessions.rs +++ b/rust/crates/keygo-server/src/db/sessions.rs @@ -1,23 +1,20 @@ use crate::domain::{DeviceId, RevokeReason, SessionId}; use sqlx::PgConnection; use std::time::Duration; -use uuid::Uuid; pub async fn insert( conn: &mut PgConnection, session_id: SessionId, - user_id: Uuid, device_id: DeviceId, jkt: &[u8; 32], auth_time: u64, ttl: Duration, ) -> sqlx::Result<()> { sqlx::query!( - "insert into sessions (id, device_id, user_id, dpop_jkt, auth_time, expires_at) - values ($1, $2, $3, $4, to_timestamp($5::int8), now() + make_interval(secs => $6))", + "insert into sessions (id, device_id, dpop_jkt, auth_time, expires_at) + values ($1, $2, $3, to_timestamp($4::int8), now() + make_interval(secs => $5))", session_id, device_id.as_uuid(), - user_id, jkt, i64::try_from(auth_time).expect("auth_time fits a timestamptz"), ttl.as_secs_f64(), @@ -28,7 +25,7 @@ pub async fn insert( Ok(()) } -pub async fn revoke( +pub async fn revoke_by_device( conn: &mut PgConnection, device_id: DeviceId, reason: RevokeReason, @@ -46,31 +43,59 @@ pub async fn revoke( Ok(()) } +pub async fn revoke( + conn: &mut PgConnection, + id: SessionId, + reason: RevokeReason, +) -> sqlx::Result<()> { + sqlx::query!( + "update sessions + set revoked_at = now(), revoke_reason = $1 + where id = $2 and revoked_at is null", + reason.as_str(), + id, + ) + .execute(conn) + .await?; + + Ok(()) +} + +pub async fn delete_ended(conn: &mut PgConnection, retention: Duration) -> sqlx::Result { + let result = sqlx::query!( + "delete from sessions + where least(revoked_at, expires_at) <= now() - make_interval(secs => $1)", + retention.as_secs_f64(), + ) + .execute(conn) + .await?; + + Ok(result.rows_affected()) +} + #[cfg(test)] mod tests { use super::*; use crate::testing::{JKT, count, expires_in_secs, insert_device}; use sqlx::PgPool; + use uuid::Uuid; const TTL: Duration = Duration::from_hours(24); const AUTH_TIME: u64 = 1_791_504_000; #[sqlx::test] - async fn session_is_bound_to_device_user_and_key(db: PgPool) { - let (user_id, device_id) = insert_device(&db).await; + async fn session_is_bound_to_device_and_key(db: PgPool) { + let (_, device_id) = insert_device(&db).await; let session_id = SessionId::new_v4(); let mut conn = db.acquire().await.unwrap(); - insert( - &mut conn, session_id, user_id, device_id, &JKT, AUTH_TIME, TTL, - ) - .await - .unwrap(); + insert(&mut conn, session_id, device_id, &JKT, AUTH_TIME, TTL) + .await + .unwrap(); - let stored: (Uuid, Uuid, Uuid, Vec, i64) = sqlx::query_as( - "select id, device_id, user_id, dpop_jkt, extract(epoch from auth_time)::int8 - from sessions", + let stored: (Uuid, Uuid, Vec, i64) = sqlx::query_as( + "select id, device_id, dpop_jkt, extract(epoch from auth_time)::int8 from sessions", ) .fetch_one(&db) .await @@ -80,7 +105,6 @@ mod tests { ( session_id, device_id.as_uuid(), - user_id, JKT.to_vec(), AUTH_TIME as i64, ) @@ -89,13 +113,12 @@ mod tests { #[sqlx::test] async fn session_expires_after_ttl(db: PgPool) { - let (user_id, device_id) = insert_device(&db).await; + let (_, device_id) = insert_device(&db).await; let mut conn = db.acquire().await.unwrap(); insert( &mut conn, SessionId::new_v4(), - user_id, device_id, &JKT, AUTH_TIME, @@ -113,13 +136,11 @@ mod tests { #[sqlx::test] async fn session_requires_a_device(db: PgPool) { - let (user_id, _) = insert_device(&db).await; let mut conn = db.acquire().await.unwrap(); let err = insert( &mut conn, SessionId::new_v4(), - user_id, DeviceId::random(), &JKT, AUTH_TIME, @@ -133,12 +154,11 @@ mod tests { #[sqlx::test] async fn session_is_deleted_with_its_device(db: PgPool) { - let (user_id, device_id) = insert_device(&db).await; + let (_, device_id) = insert_device(&db).await; let mut conn = db.acquire().await.unwrap(); insert( &mut conn, SessionId::new_v4(), - user_id, device_id, &JKT, AUTH_TIME, @@ -157,12 +177,11 @@ mod tests { } async fn insert_session(db: &PgPool) -> DeviceId { - let (user_id, device_id) = insert_device(db).await; + let (_, device_id) = insert_device(db).await; let mut conn = db.acquire().await.unwrap(); insert( &mut conn, SessionId::new_v4(), - user_id, device_id, &JKT, AUTH_TIME, @@ -178,7 +197,7 @@ mod tests { let device_id = insert_session(&db).await; let mut conn = db.acquire().await.unwrap(); - revoke(&mut conn, device_id, RevokeReason::Replaced) + revoke_by_device(&mut conn, device_id, RevokeReason::Replaced) .await .unwrap(); @@ -201,7 +220,7 @@ mod tests { .await .unwrap(); - revoke(&mut conn, device_id, RevokeReason::Replaced) + revoke_by_device(&mut conn, device_id, RevokeReason::Replaced) .await .unwrap(); @@ -213,4 +232,52 @@ mod tests { .unwrap(); assert_eq!((reason.as_str(), old), ("logout", true)); } + + const RETENTION: Duration = Duration::from_hours(30 * 24); + + async fn open_session(db: &PgPool, device_id: DeviceId) { + let mut conn = db.acquire().await.unwrap(); + insert( + &mut conn, + SessionId::new_v4(), + device_id, + &JKT, + AUTH_TIME, + TTL, + ) + .await + .unwrap(); + } + + async fn end_live_session(db: &PgPool, column: &str, ago: &str) { + sqlx::query(sqlx::AssertSqlSafe(format!( + "update sessions set {column} = now() - interval '{ago}' where revoked_at is null" + ))) + .execute(db) + .await + .unwrap(); + } + + #[sqlx::test] + async fn delete_ended_removes_sessions_past_retention(db: PgPool) { + let device_id = insert_session(&db).await; + end_live_session(&db, "revoked_at", "31 days").await; + open_session(&db, device_id).await; + end_live_session(&db, "expires_at", "31 days").await; + let mut conn = db.acquire().await.unwrap(); + + assert_eq!(delete_ended(&mut conn, RETENTION).await.unwrap(), 2); + assert_eq!(count(&db, "sessions").await, 0); + } + + #[sqlx::test] + async fn delete_ended_keeps_live_and_recently_ended_sessions(db: PgPool) { + let device_id = insert_session(&db).await; + end_live_session(&db, "revoked_at", "29 days").await; + open_session(&db, device_id).await; + let mut conn = db.acquire().await.unwrap(); + + assert_eq!(delete_ended(&mut conn, RETENTION).await.unwrap(), 0); + assert_eq!(count(&db, "sessions").await, 2); + } } diff --git a/rust/crates/keygo-server/src/domain/device.rs b/rust/crates/keygo-server/src/domain/device.rs index 036ed7226..3bdba8699 100644 --- a/rust/crates/keygo-server/src/domain/device.rs +++ b/rust/crates/keygo-server/src/domain/device.rs @@ -30,6 +30,12 @@ impl DeviceId { } } +impl From for DeviceId { + fn from(value: Uuid) -> Self { + Self(value) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] pub enum DeviceNameError { #[error("device name must not be blank")] diff --git a/rust/crates/keygo-server/src/domain/session.rs b/rust/crates/keygo-server/src/domain/session.rs index 4ed756cf6..1d32d36fd 100644 --- a/rust/crates/keygo-server/src/domain/session.rs +++ b/rust/crates/keygo-server/src/domain/session.rs @@ -1,7 +1,9 @@ use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use serde::{Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use sha2::{Digest, Sha256}; +use std::str::FromStr; +use thiserror::Error; use uuid::Uuid; use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; @@ -11,18 +13,44 @@ const PREFIX: &str = "kgr_"; // 32 --> 43 if encoded using b64urlsafe const ENCODED_LEN: usize = PREFIX.len() + 43; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum RevokeReason { - Replaced, -} +macro_rules! revoke_reasons { + ($($name:ident => $str:literal),+ $(,)?) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum RevokeReason { + $($name,)+ + } -impl RevokeReason { - pub const fn as_str(&self) -> &'static str { - match self { - RevokeReason::Replaced => "replaced", + impl RevokeReason { + #[cfg(test)] + pub const ALL: &[Self] = &[$(Self::$name,)+]; + + pub const fn as_str(&self) -> &'static str { + match self { + $(Self::$name => $str,)+ + } + } } - } + + #[derive(Debug, Error)] + #[error("unknown revoke reason {0:?}")] + pub struct UnknownRevokeReason(String); + + impl FromStr for RevokeReason { + type Err = UnknownRevokeReason; + + fn from_str(s: &str) -> Result { + match s { + $($str => Ok(Self::$name),)+ + _ => Err(UnknownRevokeReason(s.to_owned())), + } + } + } + }; +} + +revoke_reasons! { + Replaced => "replaced", + ReuseDetected => "reuse_detected", } #[derive(Zeroize, ZeroizeOnDrop)] @@ -56,6 +84,42 @@ impl Serialize for RefreshToken { } } +#[derive(Debug, Error)] +pub enum ParseRefreshTokenError { + #[error("invalid prefix")] + InvalidPrefix, + #[error("invalid token")] + InvalidToken, +} + +impl FromStr for RefreshToken { + type Err = ParseRefreshTokenError; + + fn from_str(s: &str) -> Result { + let Some(token) = s.strip_prefix(PREFIX) else { + return Err(ParseRefreshTokenError::InvalidPrefix); + }; + + if token.len() != ENCODED_LEN - PREFIX.len() { + return Err(ParseRefreshTokenError::InvalidToken); + } + + let mut out = RefreshToken([0; 32]); + URL_SAFE_NO_PAD + .decode_slice(token, &mut out.0) + .map_err(|_| ParseRefreshTokenError::InvalidToken)?; + + Ok(out) + } +} + +impl<'de> Deserialize<'de> for RefreshToken { + fn deserialize>(deserializer: D) -> Result { + let text = Zeroizing::new(String::deserialize(deserializer)?); + text.parse().map_err(serde::de::Error::custom) + } +} + #[cfg(test)] mod tests { use super::*; @@ -101,6 +165,90 @@ mod tests { ); } + #[test] + fn revoke_reason_round_trips_its_stored_name() { + for &reason in RevokeReason::ALL { + assert_eq!(reason.as_str().parse::().unwrap(), reason); + } + assert!("logout_typo".parse::().is_err()); + } + + #[test] + fn parse_round_trips_the_encoding() { + let token = RefreshToken::generate(); + + let parsed: RefreshToken = token.expose_encoded().parse().unwrap(); + + assert_eq!(parsed.0, token.0); + } + + #[test] + fn parse_rejects_a_missing_prefix() { + let encoded = RefreshToken::generate().expose_encoded(); + let unprefixed = encoded.strip_prefix(PREFIX).unwrap(); + + assert!(matches!( + unprefixed.parse::(), + Err(ParseRefreshTokenError::InvalidPrefix), + )); + assert!(matches!( + format!("kga_{unprefixed}").parse::(), + Err(ParseRefreshTokenError::InvalidPrefix), + )); + } + + #[test] + fn parse_rejects_the_wrong_length() { + let encoded = RefreshToken::generate().expose_encoded(); + + for text in [ + &encoded[..ENCODED_LEN - 1], + &format!("{}A", encoded.as_str()), + ] { + assert!(matches!( + text.parse::(), + Err(ParseRefreshTokenError::InvalidToken), + )); + } + } + + #[test] + fn parse_rejects_non_base64url() { + let text = format!("{PREFIX}{}", "+".repeat(ENCODED_LEN - PREFIX.len())); + + assert!(matches!( + text.parse::(), + Err(ParseRefreshTokenError::InvalidToken), + )); + } + + #[test] + fn parse_rejects_non_canonical_trailing_bits() { + // Same bytes as the canonical "…8", but the unused low bits of the last char are set. + let text = "kgr___________________________________________9"; + + assert!(matches!( + text.parse::(), + Err(ParseRefreshTokenError::InvalidToken), + )); + } + + #[test] + fn deserializes_from_the_encoded_token() { + let token = RefreshToken::generate(); + let json = serde_json::to_value(&token).unwrap(); + + let parsed: RefreshToken = serde_json::from_value(json).unwrap(); + + assert_eq!(parsed.0, token.0); + } + + #[test] + fn deserialize_rejects_a_malformed_token() { + assert!(serde_json::from_str::(r#""kgr_short""#).is_err()); + assert!(serde_json::from_value::(serde_json::json!(vec![0u8; 32])).is_err()); + } + #[test] fn digest_is_sha256_of_the_raw_secret() { assert_eq!( diff --git a/rust/crates/keygo-server/src/server/sweeper.rs b/rust/crates/keygo-server/src/server/sweeper.rs index e28863d9b..647195114 100644 --- a/rust/crates/keygo-server/src/server/sweeper.rs +++ b/rust/crates/keygo-server/src/server/sweeper.rs @@ -1,4 +1,5 @@ -use crate::db::{invites, registrations}; +use crate::db::{invites, registrations, sessions}; +use crate::service::session::SESSION_RETENTION; use sqlx::PgPool; use std::time::Duration; use tokio::time::MissedTickBehavior; @@ -7,9 +8,10 @@ use tokio::time::MissedTickBehavior; /// `expires_at`, so this bounds only how long they occupy the table, not how long they are valid. const INTERVAL: Duration = Duration::from_mins(1); -/// Deletes expired registrations, login states and invites until the task is aborted. A start that is -/// never finished (a wrong password fails at the client, which then never calls `finish`) leaves -/// its row behind, so without this the tables would only grow. +/// Deletes expired registrations and invites, and sessions past their retention, until the task is +/// aborted. A start that is never finished (a wrong password fails at the client, which then never +/// calls `finish`) leaves its row behind, and every refresh adds a token row, so without this the +/// tables would only grow. pub async fn run(db: PgPool) { let mut interval = tokio::time::interval(INTERVAL); interval.set_missed_tick_behavior(MissedTickBehavior::Delay); @@ -26,7 +28,8 @@ async fn sweep(db: &PgPool) -> sqlx::Result<()> { let mut conn = db.acquire().await?; let registrations = registrations::delete_expired(&mut conn).await?; let invites = invites::delete_expired(&mut conn).await?; - tracing::debug!(registrations, invites, "swept expired rows"); + let sessions = sessions::delete_ended(&mut conn, SESSION_RETENTION).await?; + tracing::debug!(registrations, invites, sessions, "swept expired rows"); Ok(()) } diff --git a/rust/crates/keygo-server/src/service/device.rs b/rust/crates/keygo-server/src/service/device.rs index 3ceaa6d77..91389ff9e 100644 --- a/rust/crates/keygo-server/src/service/device.rs +++ b/rust/crates/keygo-server/src/service/device.rs @@ -12,7 +12,7 @@ pub async fn claim( if let Some(id) = requested.id && devices::attach(tx, id, user_id, info).await? { - sessions::revoke(tx, id, RevokeReason::Replaced).await?; + sessions::revoke_by_device(tx, id, RevokeReason::Replaced).await?; return Ok(id); } diff --git a/rust/crates/keygo-server/src/service/registration/finish.rs b/rust/crates/keygo-server/src/service/registration/finish.rs index c085e2a3f..996ccdec8 100644 --- a/rust/crates/keygo-server/src/service/registration/finish.rs +++ b/rust/crates/keygo-server/src/service/registration/finish.rs @@ -162,11 +162,13 @@ mod tests { .await .unwrap(); assert_eq!(finished.session.device_id.as_uuid(), device_id); - let session: (Uuid, Uuid, Vec) = - sqlx::query_as("select device_id, user_id, dpop_jkt from sessions") - .fetch_one(&db) - .await - .unwrap(); + let session: (Uuid, Uuid, Vec) = sqlx::query_as( + "select s.device_id, d.user_id, s.dpop_jkt + from sessions s join devices d on d.id = s.device_id", + ) + .fetch_one(&db) + .await + .unwrap(); assert_eq!(session, (device_id, user_id, JKT.to_vec())); let token_hash: Vec = sqlx::query_scalar("select token_hash from refresh_tokens") .fetch_one(&db) diff --git a/rust/crates/keygo-server/src/service/session.rs b/rust/crates/keygo-server/src/service/session.rs index db55c7d53..2d0f222ff 100644 --- a/rust/crates/keygo-server/src/service/session.rs +++ b/rust/crates/keygo-server/src/service/session.rs @@ -1,13 +1,17 @@ +use crate::db::refresh_tokens::TokenStatus; use crate::db::{refresh_tokens, sessions}; use crate::domain::{ - ACCESS_TOKEN_LIFETIME, AccessToken, DeviceId, RefreshToken, SessionId, TokenIssuer, unix_now, + ACCESS_TOKEN_LIFETIME, AccessToken, DeviceId, RefreshToken, RevokeReason, SessionId, + TokenIssuer, unix_now, }; -use sqlx::{Connection, PgConnection}; +use sqlx::{Connection, PgConnection, PgPool, PgTransaction}; use std::time::Duration; +use thiserror::Error; use uuid::Uuid; pub const SESSION_LIFETIME: Duration = Duration::from_hours(180 * 24); pub const REFRESH_TTL: Duration = Duration::from_hours(30 * 24); +pub const SESSION_RETENTION: Duration = Duration::from_hours(30 * 24); pub struct Issued { pub device_id: DeviceId, @@ -31,7 +35,6 @@ pub async fn issue( sessions::insert( &mut tx, session_id, - user_id, device_id, jkt, auth_time, @@ -52,11 +55,78 @@ pub async fn issue( }) } +#[derive(Debug, Error)] +pub enum RefreshError { + #[error("session revoked")] + Revoked(Option), + #[error("refresh token expired")] + Expired, + #[error("proof key is not the session's key")] + WrongKey, + #[error("database error")] + Db(#[from] sqlx::Error), +} + +pub async fn refresh( + db: &PgPool, + token_issuer: &TokenIssuer, + refresh_token: &RefreshToken, + jkt: &[u8; 32], +) -> Result { + let mut tx = db.begin().await?; + let digest = refresh_token.digest(); + let Some(presented) = refresh_tokens::find(&mut tx, &digest).await? else { + return Err(RefreshError::Revoked(None)); + }; + + match presented.status { + TokenStatus::Revoked(reason) => return Err(RefreshError::Revoked(reason)), + TokenStatus::Expired => return Err(RefreshError::Expired), + TokenStatus::Rotated => return reuse_detected(tx, presented.session_id).await, + TokenStatus::Live => {} + } + + // Checked only for a live token: a rotated one revokes its session whichever key presents it. + if presented.dpop_jkt != *jkt { + return Err(RefreshError::WrongKey); + } + + let new_refresh_token = RefreshToken::generate(); + let rotated = + refresh_tokens::rotate(&mut tx, &digest, &new_refresh_token.digest(), REFRESH_TTL).await?; + let Some(refresh_expires_in) = rotated else { + return reuse_detected(tx, presented.session_id).await; + }; + tx.commit().await?; + + Ok(Issued { + device_id: presented.device_id, + access_token: token_issuer.issue( + presented.user_id, + presented.session_id, + presented.auth_time, + jkt, + ), + access_expires_in: ACCESS_TOKEN_LIFETIME, + refresh_token: new_refresh_token, + refresh_expires_in, + }) +} + +async fn reuse_detected( + mut tx: PgTransaction<'_>, + session_id: SessionId, +) -> Result { + sessions::revoke(&mut tx, session_id, RevokeReason::ReuseDetected).await?; + tx.commit().await?; + Err(RefreshError::Revoked(Some(RevokeReason::ReuseDetected))) +} + #[cfg(test)] mod tests { use super::*; use crate::domain::RevokeReason; - use crate::testing::{JKT, count, expires_in_secs, insert_device, token_issuer}; + use crate::testing::{JKT, count, expire, expires_in_secs, insert_device, token_issuer}; use sqlx::PgPool; fn assert_expires_after(remaining: f64, ttl: Duration) { @@ -77,12 +147,11 @@ mod tests { assert_eq!(issued.device_id, device_id); assert_eq!(issued.refresh_expires_in, REFRESH_TTL); - let stored: (Uuid, Uuid, Vec) = - sqlx::query_as("select device_id, user_id, dpop_jkt from sessions") - .fetch_one(&db) - .await - .unwrap(); - assert_eq!(stored, (device_id.as_uuid(), user_id, JKT.to_vec())); + let stored: (Uuid, Vec) = sqlx::query_as("select device_id, dpop_jkt from sessions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(stored, (device_id.as_uuid(), JKT.to_vec())); assert_expires_after(expires_in_secs(&db, "sessions").await, SESSION_LIFETIME); } @@ -134,7 +203,7 @@ mod tests { let first = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); - sessions::revoke(&mut conn, device_id, RevokeReason::Replaced) + sessions::revoke_by_device(&mut conn, device_id, RevokeReason::Replaced) .await .unwrap(); let second = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) @@ -198,4 +267,168 @@ mod tests { assert_eq!(count(&db, "sessions").await, 0); assert_eq!(count(&db, "refresh_tokens").await, 0); } + + async fn issued(db: &PgPool) -> Issued { + let (user_id, device_id) = insert_device(db).await; + let mut conn = db.acquire().await.unwrap(); + issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + .await + .unwrap() + } + + async fn revoke_reason(db: &PgPool) -> Option { + sqlx::query_scalar("select revoke_reason from sessions") + .fetch_one(db) + .await + .unwrap() + } + + #[sqlx::test] + async fn refresh_rotates_within_the_same_session(db: PgPool) { + let first = issued(&db).await; + sqlx::query("update sessions set auth_time = to_timestamp(1791504000)") + .execute(&db) + .await + .unwrap(); + + let refreshed = refresh(&db, &token_issuer(), &first.refresh_token, &JKT) + .await + .unwrap(); + + let before = token_issuer().verify(first.access_token.expose()).unwrap(); + let after = token_issuer() + .verify(refreshed.access_token.expose()) + .unwrap(); + assert_eq!(after.session_id(), before.session_id()); + assert_eq!(after.user_id(), before.user_id()); + assert_eq!(after.jkt(), &JKT); + assert_eq!(after.auth_time(), 1_791_504_000); + assert_eq!(refreshed.device_id, first.device_id); + assert_ne!( + refreshed.refresh_token.digest(), + first.refresh_token.digest() + ); + assert!(REFRESH_TTL - refreshed.refresh_expires_in <= Duration::from_secs(5)); + assert_eq!(count(&db, "refresh_tokens").await, 2); + } + + #[sqlx::test] + async fn refreshed_token_can_be_refreshed_again(db: PgPool) { + let first = issued(&db).await; + let second = refresh(&db, &token_issuer(), &first.refresh_token, &JKT) + .await + .unwrap(); + + let third = refresh(&db, &token_issuer(), &second.refresh_token, &JKT).await; + + assert!(third.is_ok()); + } + + #[sqlx::test] + async fn reusing_a_rotated_token_revokes_the_session(db: PgPool) { + let first = issued(&db).await; + let second = refresh(&db, &token_issuer(), &first.refresh_token, &JKT) + .await + .unwrap(); + + let reused = refresh(&db, &token_issuer(), &first.refresh_token, &JKT).await; + + assert!(matches!( + reused, + Err(RefreshError::Revoked(Some(RevokeReason::ReuseDetected))), + )); + assert_eq!(revoke_reason(&db).await.as_deref(), Some("reuse_detected")); + let child = refresh(&db, &token_issuer(), &second.refresh_token, &JKT).await; + assert!(matches!( + child, + Err(RefreshError::Revoked(Some(RevokeReason::ReuseDetected))), + )); + } + + #[sqlx::test] + async fn reuse_from_another_key_revokes_the_session_too(db: PgPool) { + let first = issued(&db).await; + refresh(&db, &token_issuer(), &first.refresh_token, &JKT) + .await + .unwrap(); + + let reused = refresh(&db, &token_issuer(), &first.refresh_token, &[0x41; 32]).await; + + assert!(matches!( + reused, + Err(RefreshError::Revoked(Some(RevokeReason::ReuseDetected))), + )); + assert_eq!(revoke_reason(&db).await.as_deref(), Some("reuse_detected")); + } + + #[sqlx::test] + async fn a_live_token_from_another_key_stays_live(db: PgPool) { + let first = issued(&db).await; + + let wrong = refresh(&db, &token_issuer(), &first.refresh_token, &[0x41; 32]).await; + + assert!(matches!(wrong, Err(RefreshError::WrongKey))); + assert_eq!(revoke_reason(&db).await, None); + assert!( + refresh(&db, &token_issuer(), &first.refresh_token, &JKT) + .await + .is_ok() + ); + } + + #[sqlx::test] + async fn concurrent_refreshes_with_one_token_revoke_the_session(db: PgPool) { + let first = issued(&db).await; + let issuer = token_issuer(); + + let (a, b) = tokio::join!( + refresh(&db, &issuer, &first.refresh_token, &JKT), + refresh(&db, &issuer, &first.refresh_token, &JKT), + ); + + let reused = |result: &Result| { + matches!( + result, + Err(RefreshError::Revoked(Some(RevokeReason::ReuseDetected))) + ) + }; + assert!(a.is_ok() != b.is_ok(), "exactly one refresh succeeds"); + assert!(reused(&a) || reused(&b)); + assert_eq!(count(&db, "refresh_tokens").await, 2); + assert_eq!(revoke_reason(&db).await.as_deref(), Some("reuse_detected")); + } + + #[sqlx::test] + async fn expired_token_is_refused_without_revoking(db: PgPool) { + let first = issued(&db).await; + expire(&db, "refresh_tokens").await; + + let result = refresh(&db, &token_issuer(), &first.refresh_token, &JKT).await; + + assert!(matches!(result, Err(RefreshError::Expired))); + assert_eq!(revoke_reason(&db).await, None); + } + + #[sqlx::test] + async fn token_of_a_revoked_session_answers_its_reason(db: PgPool) { + let first = issued(&db).await; + let mut conn = db.acquire().await.unwrap(); + sessions::revoke_by_device(&mut conn, first.device_id, RevokeReason::Replaced) + .await + .unwrap(); + + let result = refresh(&db, &token_issuer(), &first.refresh_token, &JKT).await; + + assert!(matches!( + result, + Err(RefreshError::Revoked(Some(RevokeReason::Replaced))), + )); + } + + #[sqlx::test] + async fn unknown_token_is_revoked_without_a_reason(db: PgPool) { + let result = refresh(&db, &token_issuer(), &RefreshToken::generate(), &JKT).await; + + assert!(matches!(result, Err(RefreshError::Revoked(None)))); + } } From 3584ce7dbbcd2dab10ab07f95bbf2200aeca6f94 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 28 Oct 2026 20:37:41 +0100 Subject: [PATCH 14/26] feat(api): implement authentication extractors --- ...9af6fe5218952df51f90f9c4a3647fde419a9.json | 42 ++ .../keygo-server/src/api/authenticated.rs | 508 ++++++++++++++++++ rust/crates/keygo-server/src/api/dpop.rs | 51 +- rust/crates/keygo-server/src/api/error.rs | 11 +- rust/crates/keygo-server/src/api/mod.rs | 11 + rust/crates/keygo-server/src/db/sessions.rs | 91 ++++ 6 files changed, 686 insertions(+), 28 deletions(-) create mode 100644 rust/crates/keygo-server/.sqlx/query-6217562d2c2b7a01d2dc8bb463c9af6fe5218952df51f90f9c4a3647fde419a9.json create mode 100644 rust/crates/keygo-server/src/api/authenticated.rs diff --git a/rust/crates/keygo-server/.sqlx/query-6217562d2c2b7a01d2dc8bb463c9af6fe5218952df51f90f9c4a3647fde419a9.json b/rust/crates/keygo-server/.sqlx/query-6217562d2c2b7a01d2dc8bb463c9af6fe5218952df51f90f9c4a3647fde419a9.json new file mode 100644 index 000000000..f6955c2c2 --- /dev/null +++ b/rust/crates/keygo-server/.sqlx/query-6217562d2c2b7a01d2dc8bb463c9af6fe5218952df51f90f9c4a3647fde419a9.json @@ -0,0 +1,42 @@ +{ + "db_name": "PostgreSQL", + "query": "select revoked_at is not null as \"revoked!\",\n revoke_reason,\n expires_at <= now() as \"expired!\"\n from sessions\n where id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "revoked!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "revoke_reason", + "type_info": "Text", + "origin": { + "Table": { + "table": "sessions", + "name": "revoke_reason" + } + } + }, + { + "ordinal": 2, + "name": "expired!", + "type_info": "Bool", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null, + true, + null + ] + }, + "hash": "6217562d2c2b7a01d2dc8bb463c9af6fe5218952df51f90f9c4a3647fde419a9" +} diff --git a/rust/crates/keygo-server/src/api/authenticated.rs b/rust/crates/keygo-server/src/api/authenticated.rs new file mode 100644 index 000000000..686ed74c3 --- /dev/null +++ b/rust/crates/keygo-server/src/api/authenticated.rs @@ -0,0 +1,508 @@ +use crate::api::dpop::verify_dpop; +use crate::api::{AppState, ErrorCode, HttpError, ServerError, single_header}; +use crate::db::sessions; +use crate::db::sessions::SessionState; +use crate::domain::{Claims, RevokeReason}; +use axum::extract::FromRequestParts; +use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; +use axum::http::request::Parts; +use axum::http::{HeaderMap, HeaderValue, StatusCode}; +use keygo_dpop::verify::VerifyError; +use thiserror::Error; + +/// Every rejection answers like a protected resource (RFC 9449 §7.1): `401` with a `DPoP` +/// challenge, whose `error` matches the body's `code` wherever the RFC has one. +#[derive(Debug, Error)] +pub enum AuthError { + #[error("authentication required")] + Missing, + #[error("invalid access token")] + Invalid, + #[error("session revoked")] + Revoked(Option), + #[error(transparent)] + Dpop(#[from] VerifyError), +} + +impl HttpError for AuthError { + fn code(&self) -> ErrorCode { + match self { + Self::Missing | Self::Invalid => ErrorCode::InvalidToken, + Self::Revoked(_) => ErrorCode::SessionRevoked, + Self::Dpop(err) => err.code(), + } + } + + fn status(&self) -> StatusCode { + match self { + // A full replay cache is not the client's fault, so it keeps its 429. + Self::Dpop(VerifyError::Busy) => StatusCode::TOO_MANY_REQUESTS, + _ => StatusCode::UNAUTHORIZED, + } + } + + fn headers(&self) -> HeaderMap { + let error = match self { + // A full replay cache is not an authentication failure: no challenge. + Self::Dpop(VerifyError::Busy) => return HeaderMap::new(), + // No credentials at all: the bare challenge (RFC 6750 §3.1). + Self::Missing => None, + // RFC 9449 has no code for a revoked session; to it the token is just invalid. + Self::Invalid | Self::Revoked(_) => Some("invalid_token"), + Self::Dpop(VerifyError::Invalid(_)) => Some("invalid_dpop_proof"), + Self::Dpop(VerifyError::UseNonce(_)) => Some("use_dpop_nonce"), + }; + + let mut headers = match self { + Self::Dpop(err) => err.headers(), // keeps DPoP-Nonce + _ => HeaderMap::new(), + }; + let challenge = match error { + Some(error) => format!(r#"DPoP algs="ES256", error="{error}""#), + None => r#"DPoP algs="ES256""#.to_owned(), + }; + headers.insert( + WWW_AUTHENTICATE, + HeaderValue::try_from(challenge).expect("the challenge is ASCII"), + ); + headers + } + + fn reason(&self) -> Option<&'static str> { + match self { + Self::Revoked(reason) => reason.as_ref().map(RevokeReason::as_str), + _ => None, + } + } +} + +pub struct Authenticated(Claims); + +impl Authenticated { + pub fn claims(&self) -> &Claims { + &self.0 + } +} + +impl FromRequestParts for Authenticated { + type Rejection = ServerError; + + async fn from_request_parts( + parts: &mut Parts, + state: &AppState, + ) -> Result { + let access_token = access_token(&parts.headers)?; + let claims = state + .token_issuer + .verify(access_token) + .map_err(|_| AuthError::Invalid)?; + + verify_dpop(parts, state, Some(access_token), Some(claims.jkt())) + .map_err(AuthError::from)?; + + let mut conn = state.db.acquire().await?; + match sessions::state(&mut conn, claims.session_id()).await? { + SessionState::Live => Ok(Self(claims)), + SessionState::Expired => Err(AuthError::Invalid.into()), + SessionState::Revoked(reason) => Err(AuthError::Revoked(reason).into()), + } + } +} + +#[derive(Debug, Error)] +#[error("recent sign-in required")] +pub struct FreshAuthRequired; + +impl HttpError for FreshAuthRequired { + fn code(&self) -> ErrorCode { + ErrorCode::FreshAuthRequired + } +} + +pub struct FreshAuthenticated(Authenticated); + +impl FreshAuthenticated { + pub fn claims(&self) -> &Claims { + self.0.claims() + } +} + +impl FromRequestParts for FreshAuthenticated { + type Rejection = ServerError; + + async fn from_request_parts( + parts: &mut Parts, + state: &AppState, + ) -> Result { + let authenticated = Authenticated::from_request_parts(parts, state).await?; + if !authenticated.claims().is_fresh() { + return Err(FreshAuthRequired.into()); + } + Ok(Self(authenticated)) + } +} + +fn access_token(headers: &HeaderMap) -> Result<&str, AuthError> { + if !headers.contains_key(AUTHORIZATION) { + return Err(AuthError::Missing); + } + + let authorization = single_header(headers, AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .ok_or(AuthError::Invalid)?; + + match authorization.split_once(' ') { + Some((scheme, token)) if scheme.eq_ignore_ascii_case("DPoP") => Ok(token), + _ => Err(AuthError::Invalid), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::FRESH_AUTH_WINDOW; + use crate::service::session; + use crate::testing::{app_state, insert_device, prover}; + use axum::Router; + use axum::body::Body; + use axum::http::Request; + use axum::routing::get; + use http_body_util::BodyExt; + use keygo_dpop::testing::TestSigner; + use keygo_dpop::{DpopProver, Htm, ProofRequest}; + use keygo_opaque::server::ServerSetup; + use serde_json::Value; + use sqlx::PgPool; + use tower::ServiceExt; + + const URI: &str = "/protected"; + const FRESH_URI: &str = "/sensitive"; + + async fn send(state: &AppState, request: Request) -> (StatusCode, HeaderMap, Value) { + let app = Router::new() + .route(URI, get(|_: Authenticated| async { "ok" })) + .route(FRESH_URI, get(|_: FreshAuthenticated| async { "ok" })) + .with_state(state.clone()); + let response = app.oneshot(request).await.unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + ( + status, + headers, + serde_json::from_slice(&body).unwrap_or(Value::Null), + ) + } + + fn request( + state: &AppState, + prover: &DpopProver, + authorization: &str, + access_token: &str, + nonce: Option<&str>, + ) -> Request { + request_to(state, URI, prover, authorization, access_token, nonce) + } + + fn request_to( + state: &AppState, + uri: &str, + prover: &DpopProver, + authorization: &str, + access_token: &str, + nonce: Option<&str>, + ) -> Request { + let htu = state.public_url.join(uri).unwrap(); + let proof = prover + .proof(&ProofRequest { + htm: Htm::Get, + htu: htu.as_str(), + access_token: Some(access_token), + nonce, + }) + .unwrap(); + Request::get(uri) + .header(AUTHORIZATION, authorization) + .header("dpop", proof) + .body(Body::empty()) + .unwrap() + } + + /// Sends with a fresh proof and answers a nonce challenge once, like a real client. + async fn call( + state: &AppState, + prover: &DpopProver, + access_token: &str, + ) -> (StatusCode, HeaderMap, Value) { + call_to(state, URI, prover, access_token).await + } + + async fn call_to( + state: &AppState, + uri: &str, + prover: &DpopProver, + access_token: &str, + ) -> (StatusCode, HeaderMap, Value) { + let authorization = format!("DPoP {access_token}"); + let first = request_to(state, uri, prover, &authorization, access_token, None); + let (status, headers, body) = send(state, first).await; + if body["code"] != "use_dpop_nonce" { + return (status, headers, body); + } + let nonce = headers["dpop-nonce"].to_str().unwrap(); + let retry = request_to( + state, + uri, + prover, + &authorization, + access_token, + Some(nonce), + ); + send(state, retry).await + } + + /// An access token for the same session whose sign-in lies past the freshness window. + fn stale_token(issued: &session::Issued, prover: &DpopProver) -> String { + let issuer = crate::testing::token_issuer(); + let claims = issuer.verify(issued.access_token.expose()).unwrap(); + let auth_time = crate::domain::unix_now() - FRESH_AUTH_WINDOW.as_secs() - 1; + issuer + .issue( + claims.user_id(), + claims.session_id(), + auth_time, + prover.jkt(), + ) + .expose() + .to_owned() + } + + async fn signed_in(db: &PgPool, prover: &DpopProver) -> session::Issued { + let (user_id, device_id) = insert_device(db).await; + let mut conn = db.acquire().await.unwrap(); + session::issue( + &mut conn, + &crate::testing::token_issuer(), + user_id, + device_id, + prover.jkt(), + ) + .await + .unwrap() + } + + fn challenge(headers: &HeaderMap) -> &str { + headers[WWW_AUTHENTICATE].to_str().unwrap() + } + + #[sqlx::test] + async fn live_session_is_authenticated(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + + let (status, _, _) = call(&state, &prover, issued.access_token.expose()).await; + + assert_eq!(status, StatusCode::OK); + } + + #[sqlx::test] + async fn missing_credentials_get_the_bare_challenge(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + + let request = Request::get(URI).body(Body::empty()).unwrap(); + let (status, headers, body) = send(&state, request).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_token"); + assert_eq!(challenge(&headers), r#"DPoP algs="ES256""#); + } + + #[sqlx::test] + async fn bearer_scheme_is_an_invalid_token(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let token = issued.access_token.expose(); + + let request = request(&state, &prover, &format!("Bearer {token}"), token, None); + let (status, headers, body) = send(&state, request).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_token"); + assert_eq!( + challenge(&headers), + r#"DPoP algs="ES256", error="invalid_token""# + ); + } + + #[sqlx::test] + async fn two_authorization_headers_are_an_invalid_token(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + + let request = Request::get(URI) + .header(AUTHORIZATION, "DPoP a") + .header(AUTHORIZATION, "DPoP b") + .body(Body::empty()) + .unwrap(); + let (status, _, body) = send(&state, request).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_token"); + } + + #[sqlx::test] + async fn proof_from_another_key_is_unauthorized(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let issued = signed_in(&db, &prover()).await; + let other = DpopProver::new(TestSigner::from_seed(8)); + + let (status, headers, body) = call(&state, &other, issued.access_token.expose()).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_dpop_proof"); + assert_eq!( + challenge(&headers), + r#"DPoP algs="ES256", error="invalid_dpop_proof""# + ); + } + + #[sqlx::test] + async fn nonce_challenge_is_unauthorized_with_a_nonce(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let token = issued.access_token.expose(); + + // A verifier that just started accepts no proof without one of its own nonces. + let request = request(&state, &prover, &format!("DPoP {token}"), token, None); + let (status, headers, body) = send(&state, request).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "use_dpop_nonce"); + assert!(headers.contains_key("dpop-nonce")); + assert_eq!( + challenge(&headers), + r#"DPoP algs="ES256", error="use_dpop_nonce""# + ); + } + + #[sqlx::test] + async fn revoked_session_answers_its_reason(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let mut conn = db.acquire().await.unwrap(); + sessions::revoke_by_device(&mut conn, issued.device_id, RevokeReason::Replaced) + .await + .unwrap(); + + let (status, headers, body) = call(&state, &prover, issued.access_token.expose()).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert_eq!(body["reason"], "replaced"); + assert_eq!( + challenge(&headers), + r#"DPoP algs="ES256", error="invalid_token""# + ); + } + + #[sqlx::test] + async fn deleted_session_is_revoked_without_a_reason(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + sqlx::query("delete from devices") + .execute(&db) + .await + .unwrap(); + + let (status, _, body) = call(&state, &prover, issued.access_token.expose()).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert!(body.get("reason").is_none()); + } + + #[tokio::test] + async fn full_replay_cache_keeps_its_429() { + let (status, body) = crate::api::error::render(AuthError::Dpop(VerifyError::Busy)).await; + + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); + assert_eq!(body["code"], "rate_limited"); + } + + #[sqlx::test] + async fn session_past_its_cap_is_an_invalid_token(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + crate::testing::expire(&db, "sessions").await; + + let (status, headers, body) = call(&state, &prover, issued.access_token.expose()).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_token"); + assert_eq!( + challenge(&headers), + r#"DPoP algs="ES256", error="invalid_token""# + ); + } + + #[sqlx::test] + async fn fresh_token_reaches_a_sensitive_endpoint(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + + let (status, _, _) = + call_to(&state, FRESH_URI, &prover, issued.access_token.expose()).await; + + assert_eq!(status, StatusCode::OK); + } + + #[sqlx::test] + async fn stale_token_is_forbidden_without_a_challenge(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let stale = stale_token(&issued, &prover); + + let (status, headers, body) = call_to(&state, FRESH_URI, &prover, &stale).await; + + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(body["code"], "fresh_auth_required"); + assert!(!headers.contains_key(WWW_AUTHENTICATE)); + } + + #[sqlx::test] + async fn stale_token_still_reaches_a_plain_endpoint(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let stale = stale_token(&issued, &prover); + + let (status, _, _) = call(&state, &prover, &stale).await; + + assert_eq!(status, StatusCode::OK); + } + + #[sqlx::test] + async fn revocation_is_checked_before_freshness(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let stale = stale_token(&issued, &prover); + let mut conn = db.acquire().await.unwrap(); + sessions::revoke_by_device(&mut conn, issued.device_id, RevokeReason::Replaced) + .await + .unwrap(); + + let (status, _, body) = call_to(&state, FRESH_URI, &prover, &stale).await; + + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert_eq!(body["reason"], "replaced"); + } +} diff --git a/rust/crates/keygo-server/src/api/dpop.rs b/rust/crates/keygo-server/src/api/dpop.rs index d830643cf..8f354c98f 100644 --- a/rust/crates/keygo-server/src/api/dpop.rs +++ b/rust/crates/keygo-server/src/api/dpop.rs @@ -1,4 +1,4 @@ -use crate::api::{AppState, ErrorCode, HttpError, ServerError}; +use crate::api::{AppState, ErrorCode, HttpError, ServerError, single_header}; use axum::extract::{FromRequestParts, OriginalUri}; use axum::http::request::Parts; use axum::http::{HeaderMap, HeaderName, HeaderValue, Method}; @@ -20,26 +20,35 @@ impl FromRequestParts for DpopProof { parts: &mut Parts, state: &AppState, ) -> Result { - let proof = single_header(&parts.headers, &DPOP) - .and_then(|value| value.to_str().ok()) - .ok_or(VerifyError::Invalid(InvalidProof::Malformed))?; - let htm = htm(&parts.method).ok_or(VerifyError::Invalid(InvalidProof::Request))?; - let htu = expected_htu(parts, &state.public_url); - - let expected = Expected { - htm, - htu: htu.as_str(), - access_token: None, - jkt: None, - }; - let jkt = state - .dpop_verifier - .verify(proof, expected) - .inspect_err(|err| tracing::debug!(?err, "dpop proof rejected"))?; + let jkt = verify_dpop(parts, state, None, None)?; Ok(DpopProof { jkt }) } } +pub(super) fn verify_dpop( + parts: &Parts, + state: &AppState, + access_token: Option<&str>, + jkt: Option<&[u8; 32]>, +) -> Result<[u8; 32], VerifyError> { + let proof = single_header(&parts.headers, DPOP) + .and_then(|value| value.to_str().ok()) + .ok_or(VerifyError::Invalid(InvalidProof::Malformed))?; + let htm = htm(&parts.method).ok_or(VerifyError::Invalid(InvalidProof::Request))?; + let htu = expected_htu(parts, &state.public_url); + + let expected = Expected { + htm, + htu: htu.as_str(), + access_token, + jkt, + }; + state + .dpop_verifier + .verify(proof, expected) + .inspect_err(|err| tracing::debug!(?err, "dpop proof rejected")) +} + impl HttpError for VerifyError { fn code(&self) -> ErrorCode { match self { @@ -60,14 +69,6 @@ impl HttpError for VerifyError { } } -fn single_header<'a>(headers: &'a HeaderMap, name: &HeaderName) -> Option<&'a HeaderValue> { - let mut values = headers.get_all(name).iter(); - match (values.next(), values.next()) { - (Some(value), None) => Some(value), - _ => None, - } -} - fn htm(method: &Method) -> Option { match *method { Method::GET => Some(Htm::Get), diff --git a/rust/crates/keygo-server/src/api/error.rs b/rust/crates/keygo-server/src/api/error.rs index 85bdf5f39..36a05ca7d 100644 --- a/rust/crates/keygo-server/src/api/error.rs +++ b/rust/crates/keygo-server/src/api/error.rs @@ -26,6 +26,8 @@ pub enum ErrorCode { RegistrationExpired, LoginExpired, // session + FreshAuthRequired, + InvalidToken, RefreshExpired, SessionRevoked, // dpop @@ -43,10 +45,13 @@ impl ErrorCode { | Self::LoginExpired | Self::InvalidDpopProof | Self::UseDpopNonce => StatusCode::BAD_REQUEST, - Self::InvalidCredentials | Self::RefreshExpired | Self::SessionRevoked => { - StatusCode::UNAUTHORIZED + Self::InvalidCredentials + | Self::InvalidToken + | Self::RefreshExpired + | Self::SessionRevoked => StatusCode::UNAUTHORIZED, + Self::InviteRequired | Self::InviteInvalid | Self::FreshAuthRequired => { + StatusCode::FORBIDDEN } - Self::InviteRequired | Self::InviteInvalid => StatusCode::FORBIDDEN, Self::NotFound => StatusCode::NOT_FOUND, Self::UsernameTaken | Self::UserIdTaken => StatusCode::CONFLICT, Self::RateLimited => StatusCode::TOO_MANY_REQUESTS, diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index e2fb0a399..8f1ad8fc3 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -1,9 +1,12 @@ +mod authenticated; mod dpop; mod error; mod extract; mod routes; mod state; +use axum::http::header::AsHeaderName; +use axum::http::{HeaderMap, HeaderValue}; pub use error::{ErrorCode, HttpError, NotFound, ServerError, ServerResult}; pub use extract::Json; pub use state::AppState; @@ -30,6 +33,14 @@ async fn not_found() -> ServerError { NotFound.into() } +fn single_header(headers: &HeaderMap, name: A) -> Option<&HeaderValue> { + let mut values = headers.get_all(name).iter(); + match (values.next(), values.next()) { + (Some(value), None) => Some(value), + _ => None, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/rust/crates/keygo-server/src/db/sessions.rs b/rust/crates/keygo-server/src/db/sessions.rs index 21907aeea..eb84ec6dc 100644 --- a/rust/crates/keygo-server/src/db/sessions.rs +++ b/rust/crates/keygo-server/src/db/sessions.rs @@ -1,3 +1,4 @@ +use crate::db::corrupt; use crate::domain::{DeviceId, RevokeReason, SessionId}; use sqlx::PgConnection; use std::time::Duration; @@ -61,6 +62,45 @@ pub async fn revoke( Ok(()) } +pub enum SessionState { + Live, + Expired, + Revoked(Option), +} + +pub async fn state(conn: &mut PgConnection, session_id: SessionId) -> sqlx::Result { + let Some(record) = sqlx::query!( + r#"select revoked_at is not null as "revoked!", + revoke_reason, + expires_at <= now() as "expired!" + from sessions + where id = $1"#, + session_id + ) + .fetch_optional(conn) + .await? + else { + return Ok(SessionState::Revoked(None)); + }; + + if !record.revoked { + return Ok(if record.expired { + SessionState::Expired + } else { + SessionState::Live + }); + } + + let reason = record + .revoke_reason + .as_deref() + .map(str::parse) + .transpose() + .map_err(corrupt)?; + + Ok(SessionState::Revoked(reason)) +} + pub async fn delete_ended(conn: &mut PgConnection, retention: Duration) -> sqlx::Result { let result = sqlx::query!( "delete from sessions @@ -280,4 +320,55 @@ mod tests { assert_eq!(delete_ended(&mut conn, RETENTION).await.unwrap(), 0); assert_eq!(count(&db, "sessions").await, 2); } + + async fn state_of(db: &PgPool, id: SessionId) -> SessionState { + let mut conn = db.acquire().await.unwrap(); + state(&mut conn, id).await.unwrap() + } + + async fn open_one(db: &PgPool) -> SessionId { + let (_, device_id) = insert_device(db).await; + let id = SessionId::new_v4(); + let mut conn = db.acquire().await.unwrap(); + insert(&mut conn, id, device_id, &JKT, AUTH_TIME, TTL) + .await + .unwrap(); + id + } + + #[sqlx::test] + async fn state_of_a_fresh_session_is_live(db: PgPool) { + let id = open_one(&db).await; + + assert!(matches!(state_of(&db, id).await, SessionState::Live)); + } + + #[sqlx::test] + async fn state_past_the_cap_is_expired(db: PgPool) { + let id = open_one(&db).await; + crate::testing::expire(&db, "sessions").await; + + assert!(matches!(state_of(&db, id).await, SessionState::Expired)); + } + + #[sqlx::test] + async fn revocation_wins_over_expiry(db: PgPool) { + let id = open_one(&db).await; + let mut conn = db.acquire().await.unwrap(); + revoke(&mut conn, id, RevokeReason::Replaced).await.unwrap(); + crate::testing::expire(&db, "sessions").await; + + assert!(matches!( + state_of(&db, id).await, + SessionState::Revoked(Some(RevokeReason::Replaced)) + )); + } + + #[sqlx::test] + async fn state_of_a_missing_session_is_revoked_without_a_reason(db: PgPool) { + assert!(matches!( + state_of(&db, SessionId::new_v4()).await, + SessionState::Revoked(None) + )); + } } From 9ba0364fc2c3259ca9d1086bd37ebeab6c0e5cb8 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 15:01:41 +0100 Subject: [PATCH 15/26] fix(dpop): keep unauthenticated proofs out of the replay store One unauthenticated client could fill the DPoP replay store with proofs signed by keys of its own, and every DPoP request then got 429. Verification is now split: `check` runs every stateless check, and the jti is recorded only where a replay could repeat an action. `Authenticated` records it after the access token verifies and the session is live. The token-issuing endpoints (`*/finish`, `/auth/token`) take `SingleUseDpopProof` and record nothing, because their own single-use state (login state, registration reservation, refresh rotation) already turns a replay away, and what they issue is bound to a key the replayer does not hold. Replay tests pin both paths. Co-Authored-By: Claude Opus 5.5 --- rust/crates/keygo-dpop/src/verify.rs | 121 +++++++++++++----- .../keygo-server/src/api/authenticated.rs | 48 ++++++- rust/crates/keygo-server/src/api/dpop.rs | 21 +-- .../keygo-server/src/api/routes/auth/login.rs | 29 ++++- .../src/api/routes/auth/register.rs | 25 +++- .../keygo-server/src/api/routes/auth/token.rs | 28 +++- rust/crates/keygo-server/src/testing.rs | 22 ++++ 7 files changed, 241 insertions(+), 53 deletions(-) diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index b83013161..a05d0441a 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -18,6 +18,17 @@ pub struct Expected<'a> { pub jkt: Option<&'a [u8; 32]>, } +/// A proof that passed every check that needs no state. A request whose replay could repeat its +/// action must [`record`](Self::record) it before acting. +#[must_use] +pub struct Checked<'a> { + verifier: &'a DpopVerifier, + jkt: [u8; 32], + jti: String, + deadline: u64, + now: u64, +} + /// What went wrong, grouped by how the server answers. The 400/401 split is the endpoint's, not the /// error's: token-issuing endpoints answer 400, everything else 401 with a `WWW-Authenticate: DPoP` /// challenge. @@ -92,11 +103,11 @@ impl DpopVerifier { } } - pub fn verify(&self, proof: &str, expected: Expected) -> VerifyResult<[u8; 32]> { - self.verify_at(proof, expected, unix_now()) + pub fn check(&self, proof: &str, expected: Expected) -> VerifyResult> { + self.check_at(proof, expected, unix_now()) } - fn verify_at(&self, proof: &str, expected: Expected, now: u64) -> VerifyResult<[u8; 32]> { + fn check_at(&self, proof: &str, expected: Expected, now: u64) -> VerifyResult> { let (input, sign) = proof.rsplit_once('.').ok_or(InvalidProof::Malformed)?; let (header, claims) = input.split_once('.').ok_or(InvalidProof::Malformed)?; @@ -145,12 +156,38 @@ impl DpopVerifier { return Err(VerifyError::UseNonce(self.nonce_key.issue(now))); }; - match self.seen_jtis.record(&jkt, &jti, deadline, now) { + Ok(Checked { + verifier: self, + jkt, + jti, + deadline, + now, + }) + } +} + +impl Checked<'_> { + /// Records the jti until the proof's deadline; a proof carrying it again is refused. + pub fn record(self) -> VerifyResult<[u8; 32]> { + let Self { + verifier, + jkt, + jti, + deadline, + now, + } = self; + match verifier.seen_jtis.record(&jkt, &jti, deadline, now) { Record::New => Ok(jkt), Record::Replay => Err(InvalidProof::Replay.into()), Record::Full => Err(VerifyError::Busy), } } + + /// Accepts the proof without storing its jti. Only for a request that consumes single-use + /// state, so a replayed proof can't do anything twice. + pub fn skip_replay_check(self) -> [u8; 32] { + self.jkt + } } fn verify_signature(input: &str, header: &Header, sign: &str) -> Result<(), InvalidProof> { @@ -181,7 +218,16 @@ mod tests { /// Verifies at `NOW` against a server that has been up long enough to accept nonce-less proofs. fn verify(proof: &str, expected: Expected) -> VerifyResult<[u8; 32]> { - verifier_started_at(NOW - WINDOW).verify_at(proof, expected, NOW) + verifier_started_at(NOW - WINDOW) + .check_at(proof, expected, NOW) + .and_then(Checked::record) + } + + /// Checks and records a proof carrying no access token on `verifier`, at `now`. + fn record_at(verifier: &DpopVerifier, proof: &str, now: u64) -> VerifyResult<[u8; 32]> { + verifier + .check_at(proof, expected(None), now) + .and_then(Checked::record) } fn proof(iat: u64, access_token: Option<&str>) -> String { @@ -200,7 +246,7 @@ mod tests { .unwrap() } - fn required_nonce(result: VerifyResult<[u8; 32]>) -> Nonce { + fn required_nonce(result: VerifyResult>) -> Nonce { match result { Err(VerifyError::UseNonce(nonce)) => nonce, Err(e) => panic!("expected a nonce challenge, got {e:?}"), @@ -383,15 +429,15 @@ mod tests { fn requires_nonce_until_a_window_after_start() { let verifier = verifier_started_at(NOW); - required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)); - required_nonce(verifier.verify_at( + required_nonce(verifier.check_at(&proof(NOW, None), expected(None), NOW)); + required_nonce(verifier.check_at( &proof(NOW + WINDOW - 1, None), expected(None), NOW + WINDOW - 1, )); assert!( verifier - .verify_at(&proof(NOW + WINDOW, None), expected(None), NOW + WINDOW) + .check_at(&proof(NOW + WINDOW, None), expected(None), NOW + WINDOW) .is_ok() ); } @@ -400,8 +446,8 @@ mod tests { fn requires_nonce_for_iat_outside_window() { let verifier = verifier_started_at(NOW - 10 * WINDOW); - required_nonce(verifier.verify_at(&proof(NOW - WINDOW - 1, None), expected(None), NOW)); - required_nonce(verifier.verify_at(&proof(NOW + WINDOW + 1, None), expected(None), NOW)); + required_nonce(verifier.check_at(&proof(NOW - WINDOW - 1, None), expected(None), NOW)); + required_nonce(verifier.check_at(&proof(NOW + WINDOW + 1, None), expected(None), NOW)); } #[test] @@ -412,7 +458,7 @@ mod tests { assert!( verifier - .verify_at(&proof(iat, None), expected(None), NOW) + .check_at(&proof(iat, None), expected(None), NOW) .is_ok() ); } @@ -421,36 +467,36 @@ mod tests { #[test] fn accepts_proof_carrying_issued_nonce() { let verifier = verifier_started_at(NOW); - let nonce = required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)); + let nonce = required_nonce(verifier.check_at(&proof(NOW, None), expected(None), NOW)); // The nonce replaces the iat check, so even a broken client clock passes. let proof = proof_with_nonce(0, None, Some(&nonce.to_string())); - assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + assert!(verifier.check_at(&proof, expected(None), NOW).is_ok()); } #[test] fn accepts_nonce_until_it_expires() { let verifier = verifier_started_at(NOW); let nonce = - required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)).to_string(); + required_nonce(verifier.check_at(&proof(NOW, None), expected(None), NOW)).to_string(); let proof = |iat| proof_with_nonce(iat, None, Some(&nonce)); let expires_at = NOW + NONCE_LIFETIME; assert!( verifier - .verify_at(&proof(1), expected(None), expires_at) + .check_at(&proof(1), expected(None), expires_at) .is_ok() ); - required_nonce(verifier.verify_at(&proof(2), expected(None), expires_at + 1)); + required_nonce(verifier.check_at(&proof(2), expected(None), expires_at + 1)); } #[test] fn rejects_nonce_from_previous_run() { let previous = verifier_started_at(NOW); - let nonce = required_nonce(previous.verify_at(&proof(NOW, None), expected(None), NOW)); + let nonce = required_nonce(previous.check_at(&proof(NOW, None), expected(None), NOW)); let restarted = verifier_started_at(NOW + 1); - required_nonce(restarted.verify_at( + required_nonce(restarted.check_at( &proof_with_nonce(NOW, None, Some(&nonce.to_string())), expected(None), NOW + 1, @@ -461,7 +507,7 @@ mod tests { fn rejects_forged_nonce() { let verifier = verifier_started_at(NOW); - required_nonce(verifier.verify_at( + required_nonce(verifier.check_at( &proof_with_nonce(NOW, None, Some("forged")), expected(None), NOW, @@ -493,9 +539,9 @@ mod tests { let verifier = verifier_started_at(NOW - WINDOW); let proof = proof(NOW, None); - assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + assert!(record_at(&verifier, &proof, NOW).is_ok()); assert!(matches!( - verifier.verify_at(&proof, expected(None), NOW), + record_at(&verifier, &proof, NOW), Err(VerifyError::Invalid(InvalidProof::Replay)) )); } @@ -503,12 +549,12 @@ mod tests { #[test] fn rejects_replayed_proof_carrying_nonce() { let verifier = verifier_started_at(NOW); - let nonce = required_nonce(verifier.verify_at(&proof(NOW, None), expected(None), NOW)); + let nonce = required_nonce(verifier.check_at(&proof(NOW, None), expected(None), NOW)); let proof = proof_with_nonce(NOW, None, Some(&nonce.to_string())); - assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + assert!(record_at(&verifier, &proof, NOW).is_ok()); assert!(matches!( - verifier.verify_at(&proof, expected(None), NOW), + record_at(&verifier, &proof, NOW), Err(VerifyError::Invalid(InvalidProof::Replay)) )); } @@ -517,13 +563,26 @@ mod tests { fn replay_is_refused_for_as_long_as_the_proof_is_acceptable() { let verifier = verifier_started_at(NOW - WINDOW); let proof = proof(NOW, None); - verifier.verify_at(&proof, expected(None), NOW).unwrap(); + record_at(&verifier, &proof, NOW).unwrap(); assert!(matches!( - verifier.verify_at(&proof, expected(None), NOW + WINDOW), + record_at(&verifier, &proof, NOW + WINDOW), Err(VerifyError::Invalid(InvalidProof::Replay)) )); - required_nonce(verifier.verify_at(&proof, expected(None), NOW + WINDOW + 1)); + required_nonce(verifier.check_at(&proof, expected(None), NOW + WINDOW + 1)); + } + + #[test] + fn single_use_proof_does_not_take_its_jti() { + let verifier = verifier_started_at(NOW - WINDOW); + let proof = proof(NOW, None); + + verifier + .check_at(&proof, expected(None), NOW) + .unwrap() + .skip_replay_check(); + + assert!(record_at(&verifier, &proof, NOW).is_ok()); } #[test] @@ -534,7 +593,7 @@ mod tests { }; assert!(matches!( - verifier.verify_at(&proof(NOW, None), expected(None), NOW), + record_at(&verifier, &proof(NOW, None), NOW), Err(VerifyError::Busy) )); } @@ -545,9 +604,9 @@ mod tests { let proof = proof(NOW, None); assert!(matches!( - verifier.verify_at(&proof, expected(Some("token")), NOW), + verifier.check_at(&proof, expected(Some("token")), NOW), Err(VerifyError::Invalid(InvalidProof::AccessTokenHash)) )); - assert!(verifier.verify_at(&proof, expected(None), NOW).is_ok()); + assert!(record_at(&verifier, &proof, NOW).is_ok()); } } diff --git a/rust/crates/keygo-server/src/api/authenticated.rs b/rust/crates/keygo-server/src/api/authenticated.rs index 686ed74c3..a93a9c43a 100644 --- a/rust/crates/keygo-server/src/api/authenticated.rs +++ b/rust/crates/keygo-server/src/api/authenticated.rs @@ -1,4 +1,4 @@ -use crate::api::dpop::verify_dpop; +use crate::api::dpop::check_dpop; use crate::api::{AppState, ErrorCode, HttpError, ServerError, single_header}; use crate::db::sessions; use crate::db::sessions::SessionState; @@ -97,12 +97,15 @@ impl FromRequestParts for Authenticated { .verify(access_token) .map_err(|_| AuthError::Invalid)?; - verify_dpop(parts, state, Some(access_token), Some(claims.jkt())) + let checked = check_dpop(parts, state, Some(access_token), Some(claims.jkt())) .map_err(AuthError::from)?; let mut conn = state.db.acquire().await?; match sessions::state(&mut conn, claims.session_id()).await? { - SessionState::Live => Ok(Self(claims)), + SessionState::Live => { + checked.record().map_err(AuthError::from)?; + Ok(Self(claims)) + } SessionState::Expired => Err(AuthError::Invalid.into()), SessionState::Revoked(reason) => Err(AuthError::Revoked(reason).into()), } @@ -367,6 +370,45 @@ mod tests { ); } + #[sqlx::test] + async fn replayed_proof_is_unauthorized(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let prover = prover(); + let issued = signed_in(&db, &prover).await; + let token = issued.access_token.expose(); + let authorization = format!("DPoP {token}"); + + let first = request(&state, &prover, &authorization, token, None); + let (_, headers, _) = send(&state, first).await; + let nonce = headers["dpop-nonce"].to_str().unwrap(); + let proof = prover + .proof(&ProofRequest { + htm: Htm::Get, + htu: state.public_url.join(URI).unwrap().as_str(), + access_token: Some(token), + nonce: Some(nonce), + }) + .unwrap(); + let replay = || { + Request::get(URI) + .header(AUTHORIZATION, &authorization) + .header("dpop", &proof) + .body(Body::empty()) + .unwrap() + }; + + let (accepted, _, _) = send(&state, replay()).await; + let (status, headers, body) = send(&state, replay()).await; + + assert_eq!(accepted, StatusCode::OK); + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "invalid_dpop_proof"); + assert_eq!( + challenge(&headers), + r#"DPoP algs="ES256", error="invalid_dpop_proof""# + ); + } + #[sqlx::test] async fn nonce_challenge_is_unauthorized_with_a_nonce(db: PgPool) { let state = app_state(&db, &ServerSetup::generate()); diff --git a/rust/crates/keygo-server/src/api/dpop.rs b/rust/crates/keygo-server/src/api/dpop.rs index 8f354c98f..b713e02f5 100644 --- a/rust/crates/keygo-server/src/api/dpop.rs +++ b/rust/crates/keygo-server/src/api/dpop.rs @@ -3,34 +3,34 @@ use axum::extract::{FromRequestParts, OriginalUri}; use axum::http::request::Parts; use axum::http::{HeaderMap, HeaderName, HeaderValue, Method}; use keygo_dpop::Htm; -use keygo_dpop::verify::{Expected, InvalidProof, VerifyError}; +use keygo_dpop::verify::{Checked, Expected, InvalidProof, VerifyError}; use url::Url; const DPOP: HeaderName = HeaderName::from_static("dpop"); const DPOP_NONCE: HeaderName = HeaderName::from_static("dpop-nonce"); -pub struct DpopProof { +pub struct SingleUseDpopProof { pub jkt: [u8; 32], } -impl FromRequestParts for DpopProof { +impl FromRequestParts for SingleUseDpopProof { type Rejection = ServerError; async fn from_request_parts( parts: &mut Parts, state: &AppState, ) -> Result { - let jkt = verify_dpop(parts, state, None, None)?; - Ok(DpopProof { jkt }) + let jkt = check_dpop(parts, state, None, None)?.skip_replay_check(); + Ok(SingleUseDpopProof { jkt }) } } -pub(super) fn verify_dpop( +pub(super) fn check_dpop<'a>( parts: &Parts, - state: &AppState, + state: &'a AppState, access_token: Option<&str>, jkt: Option<&[u8; 32]>, -) -> Result<[u8; 32], VerifyError> { +) -> Result, VerifyError> { let proof = single_header(&parts.headers, DPOP) .and_then(|value| value.to_str().ok()) .ok_or(VerifyError::Invalid(InvalidProof::Malformed))?; @@ -43,9 +43,10 @@ pub(super) fn verify_dpop( access_token, jkt, }; + state .dpop_verifier - .verify(proof, expected) + .check(proof, expected) .inspect_err(|err| tracing::debug!(?err, "dpop proof rejected")) } @@ -114,7 +115,7 @@ mod tests { let app = Router::new() .nest( "/auth", - Router::new().route("/finish", post(|_: DpopProof| async {})), + Router::new().route("/finish", post(|_: SingleUseDpopProof| async {})), ) .with_state(state); app.oneshot(request).await.unwrap().status() diff --git a/rust/crates/keygo-server/src/api/routes/auth/login.rs b/rust/crates/keygo-server/src/api/routes/auth/login.rs index af611a44b..5160131b5 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/login.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/login.rs @@ -1,4 +1,4 @@ -use crate::api::dpop::DpopProof; +use crate::api::dpop::SingleUseDpopProof; use crate::api::routes::auth::session::Session; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; use crate::domain::{Device, LoginId, Username}; @@ -75,7 +75,7 @@ struct FinishResponse { async fn finish( State(state): State, - proof: DpopProof, + proof: SingleUseDpopProof, Json(request): Json, ) -> ServerResult> { let input = FinishLogin { @@ -101,8 +101,8 @@ mod tests { use super::*; use crate::api::error::render; use crate::testing::{ - PASSWORD, app_state, device_json, post_to, post_with_proof, proof_post, prover, register, - send, + PASSWORD, app_state, count, device_json, post_to, post_with_proof, proof_post, prover, + register, replayable_post, send, }; use axum::http::StatusCode; use keygo_opaque::OpaqueError; @@ -293,6 +293,27 @@ mod tests { assert_eq!(status, StatusCode::OK); } + /// Finish skips the jti check: the taken login state already turns a replay away. + #[sqlx::test] + async fn replayed_finish_is_expired(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let (client, started) = start_over_http(&state, "ada").await; + let prover = prover(); + let body = finish_body(&started["login_id"], client, &started, prover.jkt()); + let replay = replayable_post(&state, &prover, FINISH, &body).await; + let sessions = count(&db, "sessions").await; + + let (accepted, _, _) = send(&state, replay()).await; + let (status, _, body) = send(&state, replay()).await; + + assert_eq!(accepted, StatusCode::OK); + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "login_expired"); + assert_eq!(count(&db, "sessions").await, sessions + 1); + } + #[sqlx::test] async fn binding_for_another_key_is_unauthorized(db: PgPool) { let setup = ServerSetup::generate(); diff --git a/rust/crates/keygo-server/src/api/routes/auth/register.rs b/rust/crates/keygo-server/src/api/routes/auth/register.rs index e843e6740..800eade88 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/register.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/register.rs @@ -1,4 +1,4 @@ -use crate::api::dpop::DpopProof; +use crate::api::dpop::SingleUseDpopProof; use crate::api::routes::auth::session::Session; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; use crate::domain::{DeviceInfo, RegistrationId, Username}; @@ -93,7 +93,7 @@ impl HttpError for registration::FinishError { async fn finish( State(state): State, - proof: DpopProof, + proof: SingleUseDpopProof, Json(request): Json, ) -> ServerResult<(StatusCode, Json)> { let input = FinishRegistration { @@ -120,7 +120,7 @@ mod tests { use crate::api::error::render; use crate::testing::{ app_state, count, create_invite, device_json, invite_only, post, post_to, post_with_proof, - proof_post, prover, register, send, + proof_post, prover, register, replayable_post, send, }; use keygo_opaque::client::ClientRegistration; use keygo_opaque::server::ServerSetup; @@ -424,6 +424,25 @@ mod tests { assert_eq!(status, StatusCode::CREATED); } + /// Finish skips the jti check: the taken reservation already turns a replay away. + #[sqlx::test] + async fn replayed_finish_is_expired(db: PgPool) { + let state = app_state(&db, &ServerSetup::generate()); + let (client, body) = start_body("ada", Uuid::new_v4()); + let (_, started) = post_to(state.clone(), START, body).await; + let body = finish_body(client, &started); + let replay = replayable_post(&state, &prover(), FINISH, &body).await; + + let (accepted, _, _) = send(&state, replay()).await; + let (status, _, body) = send(&state, replay()).await; + + assert_eq!(accepted, StatusCode::CREATED); + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(body["code"], "registration_expired"); + assert_eq!(count(&db, "users").await, 1); + assert_eq!(count(&db, "sessions").await, 1); + } + #[sqlx::test] async fn nonce_challenge_keeps_the_registration(db: PgPool) { let state = app_state(&db, &ServerSetup::generate()); diff --git a/rust/crates/keygo-server/src/api/routes/auth/token.rs b/rust/crates/keygo-server/src/api/routes/auth/token.rs index 0c7720d4d..ebf9c7db6 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/token.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/token.rs @@ -1,4 +1,4 @@ -use crate::api::dpop::DpopProof; +use crate::api::dpop::SingleUseDpopProof; use crate::api::routes::auth::session::Session; use crate::api::{AppState, ErrorCode, HttpError, Json, ServerResult}; use crate::domain::{RefreshToken, RevokeReason}; @@ -32,7 +32,7 @@ impl HttpError for RefreshError { pub async fn token( State(state): State, - proof: DpopProof, + proof: SingleUseDpopProof, Json(request): Json, ) -> ServerResult> { let issued = session::refresh( @@ -50,6 +50,7 @@ pub async fn token( mod tests { use crate::testing::{ PASSWORD, app_state, device_json, post_to, post_with_proof, prover, register, + replayable_post, send, }; use axum::http::StatusCode; use keygo_dpop::DpopProver; @@ -119,6 +120,29 @@ mod tests { assert_eq!(body["reason"], "reuse_detected"); } + /// The endpoint skips the jti check: the rotated token already turns a replay away, and as a + /// reuse it revokes the session. + #[sqlx::test] + async fn replayed_refresh_revokes_the_session(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let prover = prover(); + let session = sign_in(&state, &prover).await; + let replay = replayable_post(&state, &prover, TOKEN, &token_body(&session)).await; + + let (accepted, _, refreshed) = send(&state, replay()).await; + let (status, _, body) = send(&state, replay()).await; + + assert_eq!(accepted, StatusCode::OK); + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + assert_eq!(body["reason"], "reuse_detected"); + let (status, body) = post_with_proof(&state, &prover, TOKEN, token_body(&refreshed)).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(body["code"], "session_revoked"); + } + #[sqlx::test] async fn another_key_is_an_invalid_proof(db: PgPool) { let setup = ServerSetup::generate(); diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 0591e54d9..16cffbf84 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -230,6 +230,28 @@ pub fn proof_post( request.headers_mut().insert("dpop", proof.parse().unwrap()); request } + +/// Signs one proof carrying the verifier's nonce and builds identical requests around it, the way +/// an attacker replays a captured request. Fetching the nonce takes a challenge, which keeps state. +pub async fn replayable_post( + state: &AppState, + prover: &DpopProver, + uri: &str, + body: &Value, +) -> impl Fn() -> Request + use<> { + let (_, headers, challenge) = send(state, proof_post(state, prover, uri, body, None)).await; + assert_eq!(challenge["code"], "use_dpop_nonce"); + let nonce = headers["dpop-nonce"].to_str().unwrap(); + let proof = proof_post(state, prover, uri, body, Some(nonce)).headers()["dpop"].clone(); + let (uri, body) = (uri.to_owned(), body.clone()); + + move || { + let mut request = json_post(&uri, &body); + request.headers_mut().insert("dpop", proof.clone()); + request + } +} + pub async fn send(state: &AppState, request: Request) -> (StatusCode, HeaderMap, Value) { let response = router(state.clone()).oneshot(request).await.unwrap(); let status = response.status(); From d7512a4a6d1269adc3ca10a4d38293374edaa9e6 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 15:50:50 +0100 Subject: [PATCH 16/26] feat(api): add Cache-Control: no-store --- rust/crates/keygo-server/Cargo.toml | 2 +- rust/crates/keygo-server/src/api/mod.rs | 21 +++++++++++++++++++ .../keygo-server/src/api/routes/auth/token.rs | 16 ++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 7c13d6566..1cdcd45a8 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -27,7 +27,7 @@ serde_json = "1.0.154" tokio = { workspace = true, features = ["macros", "rt-multi-thread", "net", "signal", "time"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } -tower-http = { version = "0.7.1", features = ["trace"] } +tower-http = { version = "0.7.1", features = ["set-header", "trace"] } uuid = { workspace = true, features = ["v4"] } sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "postgres", "migrate", "macros", "uuid", "time"] } unicode-normalization = "0.1.25" diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index 8f1ad8fc3..da42056d3 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -12,6 +12,8 @@ pub use extract::Json; pub use state::AppState; use axum::Router; +use axum::http::header::CACHE_CONTROL; +use tower_http::set_header::SetResponseHeaderLayer; use tower_http::trace::TraceLayer; pub fn router(state: AppState) -> Router { @@ -19,6 +21,10 @@ pub fn router(state: AppState) -> Router { .nest("/health", routes::health::router()) .nest("/api/v1", v1()) .fallback(not_found) + .layer(SetResponseHeaderLayer::if_not_present( + CACHE_CONTROL, + HeaderValue::from_static("no-store"), + )) .layer(TraceLayer::new_for_http()) .with_state(state) } @@ -138,6 +144,21 @@ mod tests { assert!(body["message"].as_str().is_some_and(|m| !m.is_empty())); } + #[tokio::test] + async fn error_responses_are_not_stored() { + for request in [ + Request::get("/api/v1/nope").body(Body::empty()).unwrap(), + Request::post("/api/v1/auth/register/start") + .body(Body::from("{}")) + .unwrap(), + ] { + let response = router(state()).oneshot(request).await.unwrap(); + + assert!(response.status().is_client_error()); + assert_eq!(response.headers()[CACHE_CONTROL], "no-store"); + } + } + #[tokio::test] async fn oversized_body_is_rejected_as_json() { let padding = "a".repeat(MAX_BODY_BYTES); diff --git a/rust/crates/keygo-server/src/api/routes/auth/token.rs b/rust/crates/keygo-server/src/api/routes/auth/token.rs index ebf9c7db6..b862724f9 100644 --- a/rust/crates/keygo-server/src/api/routes/auth/token.rs +++ b/rust/crates/keygo-server/src/api/routes/auth/token.rs @@ -53,6 +53,7 @@ mod tests { replayable_post, send, }; use axum::http::StatusCode; + use axum::http::header::CACHE_CONTROL; use keygo_dpop::DpopProver; use keygo_dpop::testing::TestSigner; use keygo_opaque::CredentialResponse; @@ -104,6 +105,21 @@ mod tests { assert_ne!(refreshed["refresh_token"], session["refresh_token"]); } + #[sqlx::test] + async fn issued_tokens_are_not_stored(db: PgPool) { + let setup = ServerSetup::generate(); + let state = app_state(&db, &setup); + register(&db, &setup, "ada").await; + let prover = prover(); + let session = sign_in(&state, &prover).await; + let request = replayable_post(&state, &prover, TOKEN, &token_body(&session)).await; + + let (status, headers, _) = send(&state, request()).await; + + assert_eq!(status, StatusCode::OK); + assert_eq!(headers[CACHE_CONTROL], "no-store"); + } + #[sqlx::test] async fn reuse_answers_session_revoked_with_its_reason(db: PgPool) { let setup = ServerSetup::generate(); From 7b50da191035b665b2fd6510317c5262ec48caf7 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 15:59:14 +0100 Subject: [PATCH 17/26] feat(db): index foreign keys --- rust/crates/keygo-server/migrations/20261014141017_init.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rust/crates/keygo-server/migrations/20261014141017_init.sql b/rust/crates/keygo-server/migrations/20261014141017_init.sql index 0b8f2f124..c51ba50f8 100644 --- a/rust/crates/keygo-server/migrations/20261014141017_init.sql +++ b/rust/crates/keygo-server/migrations/20261014141017_init.sql @@ -15,6 +15,7 @@ create table devices created_at timestamptz not null default now(), last_seen_at timestamptz not null default now() ); +create index devices_user_id_idx on devices (user_id); create table sessions ( @@ -27,6 +28,7 @@ create table sessions revoked_at timestamptz, revoke_reason text ); +create index sessions_device_id_idx on sessions (device_id); create unique index sessions_one_live_per_device on sessions (device_id) where revoked_at is null; create table refresh_tokens @@ -37,6 +39,7 @@ create table refresh_tokens expires_at timestamptz not null, rotated_at timestamptz ); +create index refresh_tokens_session_id_idx on refresh_tokens (session_id); create table invites ( From 5d9bc3a39945fb0369f7f277b48514d1e473f240 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 17:33:28 +0100 Subject: [PATCH 18/26] refactor(token): make private --- rust/crates/keygo-server/src/domain/access_token.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/crates/keygo-server/src/domain/access_token.rs b/rust/crates/keygo-server/src/domain/access_token.rs index 210dde9d0..f7c869fe7 100644 --- a/rust/crates/keygo-server/src/domain/access_token.rs +++ b/rust/crates/keygo-server/src/domain/access_token.rs @@ -119,7 +119,7 @@ pub enum TokenError { } impl Claims { - pub fn new( + fn new( iss: String, user_id: Uuid, session_id: SessionId, @@ -193,7 +193,7 @@ impl AccessTokenKey { Self { signing, kid } } - pub fn sign(&self, claims: &Claims) -> AccessToken { + fn sign(&self, claims: &Claims) -> AccessToken { let header = Header { alg: Alg::EdDSA, typ: Typ::AtJwt, @@ -209,7 +209,7 @@ impl AccessTokenKey { )) } - pub fn verify(&self, token: &str, iss: &str) -> Result { + fn verify(&self, token: &str, iss: &str) -> Result { self.verify_at(token, iss, unix_now()) } From 7133b9f90c4cbc591c6f145f5cd71d34fb06d2d1 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 17:33:59 +0100 Subject: [PATCH 19/26] refactor(session): drop magic numbers --- .../crates/keygo-server/src/domain/session.rs | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/rust/crates/keygo-server/src/domain/session.rs b/rust/crates/keygo-server/src/domain/session.rs index 1d32d36fd..1448663eb 100644 --- a/rust/crates/keygo-server/src/domain/session.rs +++ b/rust/crates/keygo-server/src/domain/session.rs @@ -10,8 +10,9 @@ use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; pub type SessionId = Uuid; const PREFIX: &str = "kgr_"; -// 32 --> 43 if encoded using b64urlsafe -const ENCODED_LEN: usize = PREFIX.len() + 43; +const TOKEN_BYTES: usize = 32; +const ENCODED_LEN: usize = PREFIX.len() + + base64::encoded_len(TOKEN_BYTES, false).expect("encoded length can be represented by usize"); macro_rules! revoke_reasons { ($($name:ident => $str:literal),+ $(,)?) => { @@ -54,11 +55,11 @@ revoke_reasons! { } #[derive(Zeroize, ZeroizeOnDrop)] -pub struct RefreshToken([u8; 32]); +pub struct RefreshToken([u8; TOKEN_BYTES]); impl RefreshToken { pub fn generate() -> Self { - let mut token = [0u8; 32]; + let mut token = [0u8; TOKEN_BYTES]; getrandom::fill(token.as_mut_slice()).expect("OS random number generator unavailable"); Self(token) } @@ -70,7 +71,7 @@ impl RefreshToken { out } - pub fn digest(&self) -> [u8; 32] { + pub fn digest(&self) -> [u8; TOKEN_BYTES] { Sha256::digest(self.0).into() } } @@ -104,7 +105,7 @@ impl FromStr for RefreshToken { return Err(ParseRefreshTokenError::InvalidToken); } - let mut out = RefreshToken([0; 32]); + let mut out = RefreshToken([0; TOKEN_BYTES]); URL_SAFE_NO_PAD .decode_slice(token, &mut out.0) .map_err(|_| ParseRefreshTokenError::InvalidToken)?; @@ -134,7 +135,7 @@ mod tests { #[test] fn encodes_as_prefixed_unpadded_base64url() { - let encoded = RefreshToken([0xff; 32]).expose_encoded(); + let encoded = RefreshToken([0xff; TOKEN_BYTES]).expose_encoded(); assert_eq!( encoded.as_str(), @@ -246,13 +247,16 @@ mod tests { #[test] fn deserialize_rejects_a_malformed_token() { assert!(serde_json::from_str::(r#""kgr_short""#).is_err()); - assert!(serde_json::from_value::(serde_json::json!(vec![0u8; 32])).is_err()); + assert!( + serde_json::from_value::(serde_json::json!(vec![0u8; TOKEN_BYTES])) + .is_err() + ); } #[test] fn digest_is_sha256_of_the_raw_secret() { assert_eq!( - hex::encode(RefreshToken([0; 32]).digest()), + hex::encode(RefreshToken([0; TOKEN_BYTES]).digest()), "66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925", ); } From 53ce161ff1949afa57c6ef4b9945d41bee9f718a Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 17:54:49 +0100 Subject: [PATCH 20/26] feat(api): answer with Retry-After when jti store is full --- rust/crates/keygo-dpop/src/seen_jtis.rs | 16 ++++++++++++---- rust/crates/keygo-dpop/src/verify.rs | 9 ++++++--- .../crates/keygo-server/src/api/authenticated.rs | 13 ++++++++++--- rust/crates/keygo-server/src/api/dpop.rs | 15 ++++++++++++--- 4 files changed, 40 insertions(+), 13 deletions(-) diff --git a/rust/crates/keygo-dpop/src/seen_jtis.rs b/rust/crates/keygo-dpop/src/seen_jtis.rs index b8b73d834..717072781 100644 --- a/rust/crates/keygo-dpop/src/seen_jtis.rs +++ b/rust/crates/keygo-dpop/src/seen_jtis.rs @@ -8,7 +8,7 @@ const CAPACITY: usize = 100_000; pub(crate) enum Record { New, Replay, - Full, + Full { free_at: u64 }, } /// The `jti` of every accepted proof, kept until that proof could no longer be accepted. @@ -61,7 +61,9 @@ impl SeenJtis { if state.deadlines.len() >= self.capacity { state.remove_expired(now); if state.deadlines.len() >= self.capacity { - return Record::Full; + return Record::Full { + free_at: state.earliest_deadline.saturating_add(1), + }; } } @@ -145,7 +147,10 @@ mod tests { seen.record(&KEY, "a", NOW, NOW); seen.record(&KEY, "b", NOW, NOW); - assert_eq!(seen.record(&KEY, "c", NOW, NOW), Record::Full); + assert_eq!( + seen.record(&KEY, "c", NOW, NOW), + Record::Full { free_at: NOW + 1 } + ); assert_eq!(seen.record(&KEY, "a", NOW, NOW), Record::Replay); } @@ -154,7 +159,10 @@ mod tests { let seen = SeenJtis::with_capacity(1); seen.record(&KEY, "a", NOW, NOW); - assert_eq!(seen.record(&KEY, "b", NOW, NOW), Record::Full); + assert_eq!( + seen.record(&KEY, "b", NOW, NOW), + Record::Full { free_at: NOW + 1 } + ); assert_eq!(seen.record(&KEY, "b", NOW + 1, NOW + 1), Record::New); } diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index a05d0441a..a5565a280 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -7,6 +7,7 @@ use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::Signature; use p256::ecdsa::signature::Verifier; use sha2::{Digest, Sha256}; +use std::time::Duration; use thiserror::Error; pub struct Expected<'a> { @@ -43,7 +44,7 @@ pub enum VerifyError { UseNonce(Nonce), /// The replay cache is full. Answer `429 rate_limited`: the proof itself may be fine. #[error("too many recent proofs")] - Busy, + Busy { retry_after: Duration }, } #[derive(Debug, Error)] @@ -179,7 +180,9 @@ impl Checked<'_> { match verifier.seen_jtis.record(&jkt, &jti, deadline, now) { Record::New => Ok(jkt), Record::Replay => Err(InvalidProof::Replay.into()), - Record::Full => Err(VerifyError::Busy), + Record::Full { free_at } => Err(VerifyError::Busy { + retry_after: Duration::from_secs(free_at.saturating_sub(now)), + }), } } @@ -594,7 +597,7 @@ mod tests { assert!(matches!( record_at(&verifier, &proof(NOW, None), NOW), - Err(VerifyError::Busy) + Err(VerifyError::Busy { .. }) )); } diff --git a/rust/crates/keygo-server/src/api/authenticated.rs b/rust/crates/keygo-server/src/api/authenticated.rs index a93a9c43a..5ba5755b2 100644 --- a/rust/crates/keygo-server/src/api/authenticated.rs +++ b/rust/crates/keygo-server/src/api/authenticated.rs @@ -36,7 +36,7 @@ impl HttpError for AuthError { fn status(&self) -> StatusCode { match self { // A full replay cache is not the client's fault, so it keeps its 429. - Self::Dpop(VerifyError::Busy) => StatusCode::TOO_MANY_REQUESTS, + Self::Dpop(VerifyError::Busy { .. }) => StatusCode::TOO_MANY_REQUESTS, _ => StatusCode::UNAUTHORIZED, } } @@ -44,7 +44,7 @@ impl HttpError for AuthError { fn headers(&self) -> HeaderMap { let error = match self { // A full replay cache is not an authentication failure: no challenge. - Self::Dpop(VerifyError::Busy) => return HeaderMap::new(), + Self::Dpop(err @ VerifyError::Busy { .. }) => return err.headers(), // No credentials at all: the bare challenge (RFC 6750 §3.1). Self::Missing => None, // RFC 9449 has no code for a revoked session; to it the token is just invalid. @@ -176,6 +176,7 @@ mod tests { use keygo_opaque::server::ServerSetup; use serde_json::Value; use sqlx::PgPool; + use std::time::Duration; use tower::ServiceExt; const URI: &str = "/protected"; @@ -469,8 +470,14 @@ mod tests { #[tokio::test] async fn full_replay_cache_keeps_its_429() { - let (status, body) = crate::api::error::render(AuthError::Dpop(VerifyError::Busy)).await; + let busy = AuthError::Dpop(VerifyError::Busy { + retry_after: Duration::from_secs(7), + }); + let headers = busy.headers(); + assert_eq!(headers[axum::http::header::RETRY_AFTER], "7"); + assert!(!headers.contains_key(WWW_AUTHENTICATE)); + let (status, body) = crate::api::error::render(busy).await; assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); assert_eq!(body["code"], "rate_limited"); } diff --git a/rust/crates/keygo-server/src/api/dpop.rs b/rust/crates/keygo-server/src/api/dpop.rs index b713e02f5..dc36a9245 100644 --- a/rust/crates/keygo-server/src/api/dpop.rs +++ b/rust/crates/keygo-server/src/api/dpop.rs @@ -1,5 +1,6 @@ use crate::api::{AppState, ErrorCode, HttpError, ServerError, single_header}; use axum::extract::{FromRequestParts, OriginalUri}; +use axum::http::header::RETRY_AFTER; use axum::http::request::Parts; use axum::http::{HeaderMap, HeaderName, HeaderValue, Method}; use keygo_dpop::Htm; @@ -55,7 +56,7 @@ impl HttpError for VerifyError { match self { Self::Invalid(_) => ErrorCode::InvalidDpopProof, Self::UseNonce(_) => ErrorCode::UseDpopNonce, - Self::Busy => ErrorCode::RateLimited, + Self::Busy { .. } => ErrorCode::RateLimited, } } @@ -65,7 +66,10 @@ impl HttpError for VerifyError { let nonce = HeaderValue::try_from(nonce.to_string()).expect("nonces are base64url"); HeaderMap::from_iter([(DPOP_NONCE, nonce)]) } - Self::Invalid(_) | Self::Busy => HeaderMap::new(), + Self::Busy { retry_after } => { + HeaderMap::from_iter([(RETRY_AFTER, HeaderValue::from(retry_after.as_secs()))]) + } + Self::Invalid(_) => HeaderMap::new(), } } } @@ -101,6 +105,7 @@ mod tests { use axum::http::{Request, StatusCode}; use axum::routing::post; use serde_json::json; + use std::time::Duration; use tower::ServiceExt; fn public_url() -> Url { @@ -163,8 +168,12 @@ mod tests { #[tokio::test] async fn full_replay_cache_is_rate_limited() { - let (status, body) = render(VerifyError::Busy).await; + let busy = VerifyError::Busy { + retry_after: Duration::from_secs(7), + }; + assert_eq!(busy.headers()[RETRY_AFTER], "7"); + let (status, body) = render(busy).await; assert_eq!(status, StatusCode::TOO_MANY_REQUESTS); assert_eq!(body["code"], "rate_limited"); } From 19a933de1f688199efe1ef42fd77c299135a1b8c Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 18:13:54 +0100 Subject: [PATCH 21/26] refactor(dpop): drop nonce key secret --- rust/crates/keygo-dpop/src/nonce.rs | 19 +++++++++++-------- rust/crates/keygo-dpop/src/verify.rs | 10 +++++----- rust/crates/keygo-server/src/api/mod.rs | 3 +-- rust/crates/keygo-server/src/api/state.rs | 2 +- rust/crates/keygo-server/src/config.rs | 7 +------ rust/crates/keygo-server/src/secrets.rs | 17 ----------------- rust/crates/keygo-server/src/testing.rs | 4 ++-- 7 files changed, 21 insertions(+), 41 deletions(-) diff --git a/rust/crates/keygo-dpop/src/nonce.rs b/rust/crates/keygo-dpop/src/nonce.rs index 9fb3c4fd8..d6b606a81 100644 --- a/rust/crates/keygo-dpop/src/nonce.rs +++ b/rust/crates/keygo-dpop/src/nonce.rs @@ -16,8 +16,15 @@ const NONCE_LEN: usize = TIMESTAMP_LEN + TAG_LEN; pub struct NonceKey(Zeroizing<[u8; 32]>); impl NonceKey { - pub fn new(bytes: &[u8; 32]) -> Self { - Self(Zeroizing::new(*bytes)) + pub fn random() -> Self { + let mut key = Zeroizing::new([0u8; 32]); + getrandom::fill(key.as_mut_slice()).expect("OS random number generator unavailable"); + Self(key) + } + + #[cfg(test)] + pub(crate) fn new(bytes: [u8; 32]) -> Self { + Self(Zeroizing::new(bytes)) } fn mac(&self, created_at: u64) -> Hmac { @@ -67,10 +74,6 @@ pub struct Nonce { } impl Nonce { - pub(crate) fn created_at(&self) -> u64 { - self.created_at - } - pub(crate) fn expires_at(&self) -> u64 { self.created_at + NONCE_LIFETIME.as_secs() } @@ -93,7 +96,7 @@ mod tests { const NOW: u64 = 1_700_000_000; fn key() -> NonceKey { - NonceKey::new(&[1; 32]) + NonceKey::new([1; 32]) } #[test] @@ -123,7 +126,7 @@ mod tests { #[test] fn rejects_nonce_from_another_key() { - let foreign = NonceKey::new(&[2; 32]).issue(NOW).to_string(); + let foreign = NonceKey::new([2; 32]).issue(NOW).to_string(); assert_eq!(key().open(&foreign), None); } diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index a5565a280..81a9c3864 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -92,8 +92,8 @@ pub struct DpopVerifier { } impl DpopVerifier { - pub fn new(nonce_key: NonceKey) -> Self { - Self::started_at(nonce_key, unix_now()) + pub fn new() -> Self { + Self::started_at(NonceKey::random(), unix_now()) } pub(crate) fn started_at(nonce_key: NonceKey, started_at: u64) -> Self { @@ -148,7 +148,7 @@ impl DpopVerifier { Some(nonce) => self .nonce_key .open(&nonce) - .filter(|nonce| nonce.created_at() >= self.started_at && now <= nonce.expires_at()) + .filter(|nonce| now <= nonce.expires_at()) .map(|nonce| nonce.expires_at()), None => (now.abs_diff(iat) <= IAT_WINDOW && iat >= self.started_at + IAT_WINDOW) .then(|| iat + IAT_WINDOW), @@ -216,7 +216,7 @@ mod tests { const NONCE_LIFETIME: u64 = 5 * 60; fn verifier_started_at(started_at: u64) -> DpopVerifier { - DpopVerifier::started_at(NonceKey::new(&[3; 32]), started_at) + DpopVerifier::started_at(NonceKey::new([3; 32]), started_at) } /// Verifies at `NOW` against a server that has been up long enough to accept nonce-less proofs. @@ -497,7 +497,7 @@ mod tests { fn rejects_nonce_from_previous_run() { let previous = verifier_started_at(NOW); let nonce = required_nonce(previous.check_at(&proof(NOW, None), expected(None), NOW)); - let restarted = verifier_started_at(NOW + 1); + let restarted = DpopVerifier::started_at(NonceKey::random(), NOW + 1); required_nonce(restarted.check_at( &proof_with_nonce(NOW, None, Some(&nonce.to_string())), diff --git a/rust/crates/keygo-server/src/api/mod.rs b/rust/crates/keygo-server/src/api/mod.rs index da42056d3..4649aa781 100644 --- a/rust/crates/keygo-server/src/api/mod.rs +++ b/rust/crates/keygo-server/src/api/mod.rs @@ -56,7 +56,6 @@ mod tests { use axum::body::Body; use axum::http::{Request, StatusCode}; use http_body_util::BodyExt; - use keygo_dpop::NonceKey; use keygo_dpop::verify::DpopVerifier; use routes::auth::MAX_BODY_BYTES; use serde_json::{Value, json}; @@ -91,7 +90,7 @@ mod tests { db: sqlx::postgres::PgPoolOptions::new() .connect_lazy_with(sqlx::postgres::PgConnectOptions::new()), login_states: LoginStates::new(), - dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new(&[0; 32]))), + dpop_verifier: Arc::new(DpopVerifier::new()), token_issuer: Arc::new(crate::testing::token_issuer()), } } diff --git a/rust/crates/keygo-server/src/api/state.rs b/rust/crates/keygo-server/src/api/state.rs index ce8222ca7..59b5e2f3f 100644 --- a/rust/crates/keygo-server/src/api/state.rs +++ b/rust/crates/keygo-server/src/api/state.rs @@ -34,7 +34,7 @@ impl AppState { opaque_state: secrets.opaque_setup()?, db, login_states: LoginStates::new(), - dpop_verifier: Arc::new(DpopVerifier::new(secrets.dpop_nonce_key()?)), + dpop_verifier: Arc::new(DpopVerifier::new()), token_issuer: Arc::new(TokenIssuer::new(secrets.access_token_key()?, issuer)), }) } diff --git a/rust/crates/keygo-server/src/config.rs b/rust/crates/keygo-server/src/config.rs index daa53a66a..935ef5720 100644 --- a/rust/crates/keygo-server/src/config.rs +++ b/rust/crates/keygo-server/src/config.rs @@ -1,7 +1,6 @@ use crate::domain::{AccessTokenKey, InvitePepper}; -use crate::secrets::{DbPassword, DpopNonceKey, OpaqueSetup, SecretStore}; +use crate::secrets::{DbPassword, OpaqueSetup, SecretStore}; use clap::{Args, ValueEnum}; -use keygo_dpop::NonceKey; use keygo_opaque::server::ServerSetup; use secrecy::SecretString; use std::path::PathBuf; @@ -108,10 +107,6 @@ impl SecretsConfig { self.store().read::() } - pub(crate) fn dpop_nonce_key(&self) -> anyhow::Result { - self.store().read::() - } - pub(crate) fn access_token_key(&self) -> anyhow::Result { self.store().read::() } diff --git a/rust/crates/keygo-server/src/secrets.rs b/rust/crates/keygo-server/src/secrets.rs index c892cadf5..4e7e5500c 100644 --- a/rust/crates/keygo-server/src/secrets.rs +++ b/rust/crates/keygo-server/src/secrets.rs @@ -1,6 +1,5 @@ use crate::domain::{AccessTokenKey, InvitePepper}; use anyhow::{Context, anyhow, ensure}; -use keygo_dpop::NonceKey; use keygo_opaque::server::ServerSetup; use secrecy::{ExposeSecret, SecretString}; use std::fs::{self, DirBuilder, File, Permissions}; @@ -115,21 +114,6 @@ impl TypedSecret for InvitePepper { } } -pub struct DpopNonceKey; - -impl TypedSecret for DpopNonceKey { - const NAME: &'static str = "dpop_nonce_key"; - type Value = NonceKey; - - fn generate() -> anyhow::Result { - random_key() - } - - fn decode(stored: &str) -> anyhow::Result { - Ok(NonceKey::new(&*decode(stored)?)) - } -} - impl TypedSecret for AccessTokenKey { const NAME: &'static str = "access_token_key"; type Value = Self; @@ -161,7 +145,6 @@ secrets! { DbPassword, OpaqueSetup, InvitePepper, - DpopNonceKey, AccessTokenKey, } diff --git a/rust/crates/keygo-server/src/testing.rs b/rust/crates/keygo-server/src/testing.rs index 16cffbf84..5f9ab5efb 100644 --- a/rust/crates/keygo-server/src/testing.rs +++ b/rust/crates/keygo-server/src/testing.rs @@ -12,7 +12,7 @@ use axum::http::{HeaderMap, Request, StatusCode}; use http_body_util::BodyExt; use keygo_dpop::testing::TestSigner; use keygo_dpop::verify::DpopVerifier; -use keygo_dpop::{DpopProver, Htm, NonceKey, ProofRequest}; +use keygo_dpop::{DpopProver, Htm, ProofRequest}; use keygo_opaque::client::{ClientLogin, ClientRegistration}; use keygo_opaque::server::ServerSetup; use serde_json::{Value, json}; @@ -176,7 +176,7 @@ pub fn app_state(db: &PgPool, setup: &ServerSetup) -> AppState { opaque_state: setup.clone(), db: db.clone(), login_states: LoginStates::new(), - dpop_verifier: Arc::new(DpopVerifier::new(NonceKey::new(&[0; 32]))), + dpop_verifier: Arc::new(DpopVerifier::new()), token_issuer: Arc::new(token_issuer()), } } From bc8551c673c2cf5735aec14d39b6e5d2af9def3d Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 18:34:25 +0100 Subject: [PATCH 22/26] refactor(service): drop checkpoint in session issuing --- .../keygo-server/src/api/authenticated.rs | 10 ++- .../crates/keygo-server/src/service/device.rs | 5 +- .../keygo-server/src/service/session.rs | 74 +++++++++---------- 3 files changed, 42 insertions(+), 47 deletions(-) diff --git a/rust/crates/keygo-server/src/api/authenticated.rs b/rust/crates/keygo-server/src/api/authenticated.rs index 5ba5755b2..c40cac773 100644 --- a/rust/crates/keygo-server/src/api/authenticated.rs +++ b/rust/crates/keygo-server/src/api/authenticated.rs @@ -283,16 +283,18 @@ mod tests { async fn signed_in(db: &PgPool, prover: &DpopProver) -> session::Issued { let (user_id, device_id) = insert_device(db).await; - let mut conn = db.acquire().await.unwrap(); - session::issue( - &mut conn, + let mut tx = db.begin().await.unwrap(); + let issued = session::issue( + &mut tx, &crate::testing::token_issuer(), user_id, device_id, prover.jkt(), ) .await - .unwrap() + .unwrap(); + tx.commit().await.unwrap(); + issued } fn challenge(headers: &HeaderMap) -> &str { diff --git a/rust/crates/keygo-server/src/service/device.rs b/rust/crates/keygo-server/src/service/device.rs index 91389ff9e..7563c44cf 100644 --- a/rust/crates/keygo-server/src/service/device.rs +++ b/rust/crates/keygo-server/src/service/device.rs @@ -40,10 +40,11 @@ mod tests { } async fn open_session(db: &PgPool, user_id: Uuid, device_id: DeviceId) { - let mut conn = db.acquire().await.unwrap(); - session::issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let mut tx = db.begin().await.unwrap(); + session::issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); + tx.commit().await.unwrap(); } async fn revoke_reasons(db: &PgPool, device_id: DeviceId) -> Vec> { diff --git a/rust/crates/keygo-server/src/service/session.rs b/rust/crates/keygo-server/src/service/session.rs index 2d0f222ff..38f28035d 100644 --- a/rust/crates/keygo-server/src/service/session.rs +++ b/rust/crates/keygo-server/src/service/session.rs @@ -4,7 +4,7 @@ use crate::domain::{ ACCESS_TOKEN_LIFETIME, AccessToken, DeviceId, RefreshToken, RevokeReason, SessionId, TokenIssuer, unix_now, }; -use sqlx::{Connection, PgConnection, PgPool, PgTransaction}; +use sqlx::{PgPool, PgTransaction}; use std::time::Duration; use thiserror::Error; use uuid::Uuid; @@ -22,7 +22,7 @@ pub struct Issued { } pub async fn issue( - conn: &mut PgConnection, + tx: &mut PgTransaction<'_>, token_issuer: &TokenIssuer, user_id: Uuid, device_id: DeviceId, @@ -30,21 +30,11 @@ pub async fn issue( ) -> sqlx::Result { let auth_time = unix_now(); - let mut tx = conn.begin().await?; let session_id = SessionId::new_v4(); - sessions::insert( - &mut tx, - session_id, - device_id, - jkt, - auth_time, - SESSION_LIFETIME, - ) - .await?; + sessions::insert(tx, session_id, device_id, jkt, auth_time, SESSION_LIFETIME).await?; let refresh_token = RefreshToken::generate(); - refresh_tokens::insert(&mut tx, session_id, &refresh_token.digest(), REFRESH_TTL).await?; - tx.commit().await?; + refresh_tokens::insert(tx, session_id, &refresh_token.digest(), REFRESH_TTL).await?; Ok(Issued { device_id, @@ -139,11 +129,12 @@ mod tests { #[sqlx::test] async fn issue_binds_a_session_to_the_device_and_key(db: PgPool) { let (user_id, device_id) = insert_device(&db).await; - let mut conn = db.acquire().await.unwrap(); + let mut tx = db.begin().await.unwrap(); - let issued = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let issued = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); + tx.commit().await.unwrap(); assert_eq!(issued.device_id, device_id); assert_eq!(issued.refresh_expires_in, REFRESH_TTL); @@ -158,11 +149,12 @@ mod tests { #[sqlx::test] async fn issue_signs_an_access_token_for_the_stored_session(db: PgPool) { let (user_id, device_id) = insert_device(&db).await; - let mut conn = db.acquire().await.unwrap(); + let mut tx = db.begin().await.unwrap(); - let issued = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let issued = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); + tx.commit().await.unwrap(); let claims = token_issuer().verify(issued.access_token.expose()).unwrap(); let (session_id, auth_time): (Uuid, i64) = @@ -181,11 +173,12 @@ mod tests { #[sqlx::test] async fn issue_stores_only_the_refresh_token_hash(db: PgPool) { let (user_id, device_id) = insert_device(&db).await; - let mut conn = db.acquire().await.unwrap(); + let mut tx = db.begin().await.unwrap(); - let issued = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let issued = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); + tx.commit().await.unwrap(); let stored: Vec = sqlx::query_scalar("select token_hash from refresh_tokens") .fetch_one(&db) @@ -198,17 +191,18 @@ mod tests { #[sqlx::test] async fn each_issue_opens_its_own_session(db: PgPool) { let (user_id, device_id) = insert_device(&db).await; - let mut conn = db.acquire().await.unwrap(); + let mut tx = db.begin().await.unwrap(); - let first = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let first = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); - sessions::revoke_by_device(&mut conn, device_id, RevokeReason::Replaced) + sessions::revoke_by_device(&mut tx, device_id, RevokeReason::Replaced) .await .unwrap(); - let second = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let second = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); + tx.commit().await.unwrap(); assert_ne!(first.refresh_token.digest(), second.refresh_token.digest()); assert_eq!(count(&db, "sessions").await, 2); @@ -218,12 +212,14 @@ mod tests { #[sqlx::test] async fn a_device_has_at_most_one_live_session(db: PgPool) { let (user_id, device_id) = insert_device(&db).await; - let mut conn = db.acquire().await.unwrap(); - issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let mut tx = db.begin().await.unwrap(); + issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .unwrap(); + tx.commit().await.unwrap(); - let err = issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let mut tx = db.begin().await.unwrap(); + let err = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await .err() .unwrap(); @@ -250,18 +246,12 @@ mod tests { #[sqlx::test] async fn issue_for_an_unknown_device_stores_nothing(db: PgPool) { let (user_id, _) = insert_device(&db).await; - let mut conn = db.acquire().await.unwrap(); + let mut tx = db.begin().await.unwrap(); - let err = issue( - &mut conn, - &token_issuer(), - user_id, - DeviceId::random(), - &JKT, - ) - .await - .err() - .unwrap(); + let err = issue(&mut tx, &token_issuer(), user_id, DeviceId::random(), &JKT) + .await + .err() + .unwrap(); assert!(err.as_database_error().unwrap().is_foreign_key_violation()); assert_eq!(count(&db, "sessions").await, 0); @@ -270,10 +260,12 @@ mod tests { async fn issued(db: &PgPool) -> Issued { let (user_id, device_id) = insert_device(db).await; - let mut conn = db.acquire().await.unwrap(); - issue(&mut conn, &token_issuer(), user_id, device_id, &JKT) + let mut tx = db.begin().await.unwrap(); + let issued = issue(&mut tx, &token_issuer(), user_id, device_id, &JKT) .await - .unwrap() + .unwrap(); + tx.commit().await.unwrap(); + issued } async fn revoke_reason(db: &PgPool) -> Option { From 3a101b0a8fe5196f611eeff90e7ca33cc46223e8 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 18:34:47 +0100 Subject: [PATCH 23/26] refactor(db): dedup revoke reason extraction --- rust/crates/keygo-server/src/db/refresh_tokens.rs | 5 +++-- rust/crates/keygo-server/src/db/sessions.rs | 13 ++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/rust/crates/keygo-server/src/db/refresh_tokens.rs b/rust/crates/keygo-server/src/db/refresh_tokens.rs index 3262f3e29..821c5e5a6 100644 --- a/rust/crates/keygo-server/src/db/refresh_tokens.rs +++ b/rust/crates/keygo-server/src/db/refresh_tokens.rs @@ -1,4 +1,5 @@ use crate::db::corrupt; +use crate::db::sessions::revoke_reason; use crate::domain::{DeviceId, RevokeReason, SessionId}; use sqlx::PgConnection; use std::time::Duration; @@ -65,8 +66,8 @@ pub async fn find(conn: &mut PgConnection, hash: &[u8; 32]) -> sqlx::Result sqlx::Resu }); } - let reason = record - .revoke_reason + let reason = revoke_reason(record.revoke_reason)?; + + Ok(SessionState::Revoked(reason)) +} + +pub(super) fn revoke_reason(stored: Option) -> sqlx::Result> { + stored .as_deref() .map(str::parse) .transpose() - .map_err(corrupt)?; - - Ok(SessionState::Revoked(reason)) + .map_err(corrupt) } pub async fn delete_ended(conn: &mut PgConnection, retention: Duration) -> sqlx::Result { From 2af6edf6462cac954a78fedaa81feb7fdb5ece8a Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 18:38:30 +0100 Subject: [PATCH 24/26] refactor(db): reuse device service for registration finish --- rust/crates/keygo-server/src/service/device.rs | 4 ++-- .../keygo-server/src/service/login/finish.rs | 2 +- .../src/service/registration/finish.rs | 16 ++++++++++++---- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/rust/crates/keygo-server/src/service/device.rs b/rust/crates/keygo-server/src/service/device.rs index 7563c44cf..36418cc4d 100644 --- a/rust/crates/keygo-server/src/service/device.rs +++ b/rust/crates/keygo-server/src/service/device.rs @@ -3,7 +3,7 @@ use crate::domain::{Device, DeviceId, RevokeReason}; use sqlx::PgTransaction; use uuid::Uuid; -pub async fn claim( +pub async fn attach_or_create( tx: &mut PgTransaction<'_>, user_id: Uuid, requested: Device, @@ -34,7 +34,7 @@ mod tests { async fn claim_once(db: &PgPool, user_id: Uuid, requested: Device) -> DeviceId { let mut tx = db.begin().await.unwrap(); - let device_id = claim(&mut tx, user_id, requested).await.unwrap(); + let device_id = attach_or_create(&mut tx, user_id, requested).await.unwrap(); tx.commit().await.unwrap(); device_id } diff --git a/rust/crates/keygo-server/src/service/login/finish.rs b/rust/crates/keygo-server/src/service/login/finish.rs index a702643fb..36019c704 100644 --- a/rust/crates/keygo-server/src/service/login/finish.rs +++ b/rust/crates/keygo-server/src/service/login/finish.rs @@ -51,7 +51,7 @@ pub async fn finish( .await? .ok_or(OpaqueError::InvalidLogin)?; - let device_id = service::device::claim(&mut tx, user_id, device).await?; + let device_id = service::device::attach_or_create(&mut tx, user_id, device).await?; let issued = service::session::issue(&mut tx, token_issuer, user_id, device_id, &jkt).await?; tx.commit().await?; diff --git a/rust/crates/keygo-server/src/service/registration/finish.rs b/rust/crates/keygo-server/src/service/registration/finish.rs index 996ccdec8..a321dcbdb 100644 --- a/rust/crates/keygo-server/src/service/registration/finish.rs +++ b/rust/crates/keygo-server/src/service/registration/finish.rs @@ -1,6 +1,7 @@ -use crate::db::{devices, invites, opaque_records, registrations, users}; -use crate::domain::{DeviceId, DeviceInfo, RegistrationId, TokenIssuer, Username}; +use crate::db::{invites, opaque_records, registrations, users}; +use crate::domain::{Device, DeviceInfo, RegistrationId, TokenIssuer, Username}; use crate::service; +use crate::service::device; use crate::service::session::Issued; use keygo_opaque::{RegistrationUpload, server}; use sqlx::PgPool; @@ -57,8 +58,15 @@ pub async fn finish( users::insert(&mut tx, pending.user_id, &pending.username).await?; opaque_records::insert(&mut tx, pending.user_id, &password_file).await?; - let device_id = DeviceId::random(); - devices::insert(&mut tx, device_id, pending.user_id, &device_info).await?; + let device_id = device::attach_or_create( + &mut tx, + pending.user_id, + Device { + id: None, + info: device_info, + }, + ) + .await?; let session = service::session::issue(&mut tx, token_issuer, pending.user_id, device_id, &jkt).await?; From 05a606c44865cb67ab470c5fd5adc0d23a46a444 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 20:16:53 +0100 Subject: [PATCH 25/26] chore(dpop): expect new_without_default on verifier --- rust/crates/keygo-dpop/src/verify.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/crates/keygo-dpop/src/verify.rs b/rust/crates/keygo-dpop/src/verify.rs index 81a9c3864..a1c58dd87 100644 --- a/rust/crates/keygo-dpop/src/verify.rs +++ b/rust/crates/keygo-dpop/src/verify.rs @@ -92,6 +92,10 @@ pub struct DpopVerifier { } impl DpopVerifier { + #[expect( + clippy::new_without_default, + reason = "a verifier owns a random nonce key and a start time, not a neutral default" + )] pub fn new() -> Self { Self::started_at(NonceKey::random(), unix_now()) } From dbb952b86eeadf2b8f902584915f5a693a874ea2 Mon Sep 17 00:00:00 2001 From: Davis Date: Thu, 29 Oct 2026 20:16:53 +0100 Subject: [PATCH 26/26] refactor(token): gate expose behind cfg(test) --- rust/crates/keygo-server/src/domain/access_token.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/crates/keygo-server/src/domain/access_token.rs b/rust/crates/keygo-server/src/domain/access_token.rs index f7c869fe7..c92583dae 100644 --- a/rust/crates/keygo-server/src/domain/access_token.rs +++ b/rust/crates/keygo-server/src/domain/access_token.rs @@ -179,6 +179,7 @@ impl Claims { } impl AccessToken { + #[cfg(test)] pub(crate) fn expose(&self) -> &str { &self.0 }