chadtmiller.com/monolith
An atproto PDS
0
0
//! DPoP proofs (RFC 9449), checked as `spec/OAUTH.md` says under "DPoP":
//! a JWT signed by the public key in its header, naming the request it is
//! for, with a nonce the server gave, spent once.
use super::OAuth;
use crate::Service;
use axum::http::HeaderMap;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use serde_json::{Map, Value as Json, json};
use sha2::{Digest, Sha256};
/// The JWS algorithms the server verifies.
pub(crate) const ALGS: &[&str] = &["ES256", "ES256K"];
/// How long a proof's `jti` is held: longer than any `iat` it may carry is taken.
const JTI_LIFE: u64 = 200;
/// The namespace of the single-use values proofs' `jti`s are kept in.
const NS: &str = "dpop";
/// The most proofs held in memory alone; past that the oldest are forgotten.
pub(crate) const MEMORY_MAX: usize = 1_000_000;
/// How far before the server's clock a proof's `iat` may be, and after.
const IAT_BEFORE: f64 = 190.0;
const IAT_AFTER: f64 = 180.0;
/// How far past a proof's `exp` may be.
const EXP_PAST: f64 = 180.0;
/// Nonces rotate every this many seconds.
const NONCE_PERIOD: u64 = 60;
/// Why a proof is refused: `invalid_dpop_proof`, or `use_dpop_nonce`.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Refusal {
Invalid(String),
Nonce(String),
}
impl Refusal {
pub fn error(&self) -> &'static str {
match self {
Refusal::Invalid(_) => "invalid_dpop_proof",
Refusal::Nonce(_) => "use_dpop_nonce",
}
}
pub fn description(&self) -> &str {
match self {
Refusal::Invalid(d) | Refusal::Nonce(d) => d,
}
}
}
/// A proof that passed: its key's thumbprint, and its `jti`, spent in
/// memory and to be kept (`keep`) once its request passes its token or grant.
pub(crate) struct Proof {
pub jkt: String,
jti: String,
until: u64,
}
/// The entry that keeps a proof's `jti` durably, once its request passed the
/// check of its token or grant; None if it is kept already, by a request
/// that carried the same proof while it was forgotten in memory: then it is
/// replayed.
pub(crate) fn keep(svc: &Service, proof: &Proof, now: u64) -> Option<Json> {
svc.replay.claim(NS, &proof.jti, now, proof.until)
}
/// Proofs spent, held in memory: every proof that passes checks 1 to 4, from
/// when it is spent until its time passes, at most `max` of them, the oldest
/// forgotten first. Those whose requests passed are kept durably too
/// (`keep`); the others are held here alone, and not across a restart.
/// A `jti` is held by the first 16 bytes of its SHA-256.
pub(crate) struct Spent {
until: std::collections::HashMap<[u8; 16], u64>,
/// The same, in the order they were spent; an entry whose time is not
/// the one `until` holds for it is stale, and passed over.
order: std::collections::VecDeque<([u8; 16], u64)>,
max: usize,
}
impl Default for Spent {
fn default() -> Spent {
Spent::new(MEMORY_MAX)
}
}
impl Spent {
pub fn new(max: usize) -> Spent {
Spent {
until: Default::default(),
order: Default::default(),
max,
}
}
fn key(jti: &str) -> [u8; 16] {
let d = Sha256::digest(jti.as_bytes());
let mut k = [0; 16];
k.copy_from_slice(&d[..16]);
k
}
/// Spend `jti` at `now` until `until`: false if it is held already.
pub fn spend(&mut self, jti: &str, now: u64, until: u64) -> bool {
let k = Spent::key(jti);
while let Some(&(old, t)) = self.order.front()
&& t <= now
{
self.order.pop_front();
if self.until.get(&old) == Some(&t) {
self.until.remove(&old);
}
}
if self.until.get(&k).is_some_and(|t| *t > now) {
return false;
}
while self.until.len() >= self.max {
let Some((old, t)) = self.order.pop_front() else {
break;
};
if self.until.get(&old) == Some(&t) {
self.until.remove(&old);
}
}
self.until.insert(k, until);
self.order.push_back((k, until));
true
}
/// How many proofs are held.
#[cfg(test)]
pub fn len(&self) -> usize {
self.until.len()
}
}
/// A public key a proof, or a client assertion, is signed with.
pub(super) enum Key {
P256(p256::ecdsa::VerifyingKey),
K256(k256::ecdsa::VerifyingKey),
}
fn coordinate(jwk: &Map<String, Json>, k: &str) -> Option<[u8; 32]> {
B64.decode(jwk.get(k)?.as_str()?).ok()?.try_into().ok()
}
/// The public key a JWK holds, for `alg`.
pub(super) fn key(jwk: &Map<String, Json>, alg: &str) -> Option<Key> {
if jwk.get("kty")?.as_str()? != "EC" || jwk.contains_key("d") {
return None;
}
let (x, y) = (coordinate(jwk, "x")?, coordinate(jwk, "y")?);
match (alg, jwk.get("crv")?.as_str()?) {
("ES256", "P-256") => {
let p = p256::Sec1Point::from_affine_coordinates(&x.into(), &y.into(), false);
p256::ecdsa::VerifyingKey::from_sec1_point(&p)
.ok()
.map(Key::P256)
}
("ES256K", "secp256k1") => {
let p = k256::Sec1Point::from_affine_coordinates(&x.into(), &y.into(), false);
k256::ecdsa::VerifyingKey::from_sec1_point(&p)
.ok()
.map(Key::K256)
}
_ => None,
}
}
pub(super) fn verify(key: &Key, message: &[u8], sig: &[u8]) -> bool {
use k256::ecdsa::signature::Verifier;
match key {
Key::P256(k) => {
p256::ecdsa::Signature::from_slice(sig).is_ok_and(|s| k.verify(message, &s).is_ok())
}
// Signers need not give the low-S form.
Key::K256(k) => k256::ecdsa::Signature::from_slice(sig)
.is_ok_and(|s| k.verify(message, &s.normalize_s()).is_ok()),
}
}
/// An EC JWK's thumbprint (RFC 7638), base64url.
pub(crate) fn thumbprint(jwk: &Map<String, Json>) -> String {
let canonical = json!({ "crv": jwk["crv"], "kty": jwk["kty"], "x": jwk["x"], "y": jwk["y"] });
B64.encode(Sha256::digest(canonical.to_string().as_bytes()))
}
/// An access token's hash, as a proof's `ath` names it.
pub(crate) fn ath(token: &str) -> String {
B64.encode(Sha256::digest(token.as_bytes()))
}
/// Whether a proof's `htu` names the request's URL: scheme, host, port and path.
fn same_url(htu: &url::Url, request: &url::Url) -> bool {
htu.scheme() == request.scheme()
&& htu.host_str().map(str::to_ascii_lowercase)
== request.host_str().map(str::to_ascii_lowercase)
&& htu.port_or_known_default() == request.port_or_known_default()
&& htu.path() == request.path()
}
impl OAuth {
/// The nonce of period `n`.
fn nonce_of(&self, n: u64) -> String {
B64.encode(&self.mac("nonce", &n.to_be_bytes())[..18])
}
/// The nonce answers carry at `now`: the next period's.
pub fn nonce(&self, now: u64) -> String {
self.nonce_of(now / NONCE_PERIOD + 1)
}
/// Whether the server takes `nonce` at `now`: the previous, current or next period's.
fn takes_nonce(&self, nonce: &str, now: u64) -> bool {
let n = now / NONCE_PERIOD;
[n.saturating_sub(1), n, n + 1]
.iter()
.any(|p| self.nonce_of(*p) == nonce)
}
/// Spend a proof's `jti` in memory: false if it is held there already.
fn spend_proof(&self, jti: &str, now: u64, until: u64) -> bool {
self.proofs
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.spend(jti, now, until)
}
}
/// Check a request's DPoP proof, as `spec/OAUTH.md` orders the checks: None
/// if it has no `DPoP` header. `path` is the request's; `ath`, at XRPC, the
/// access token the proof must name, and at the OAuth endpoints none. A
/// proof that passes all but its `jti` is spent, in memory: the caller
/// keeps it durably (`keep`) once its request passes its token or grant.
pub(crate) fn check(
svc: &Service,
headers: &HeaderMap,
method: &str,
path: &str,
ath_of: Option<&str>,
) -> Result<Option<Proof>, Refusal> {
let invalid = |why: &str| Err(Refusal::Invalid(why.to_string()));
let mut all = headers.get_all("dpop").iter();
let Some(value) = all.next() else {
return Ok(None);
};
if all.next().is_some() {
return invalid("More than one DPoP header");
}
let Ok(jwt) = value.to_str() else {
return invalid("DPoP header is not text");
};
if jwt.is_empty() {
return invalid("DPoP header is empty");
}
// 1. The JWT, its key, its signature and its times.
let mut parts = jwt.split('.');
let (Some(h), Some(c), Some(s), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return invalid("DPoP proof is not a JWT");
};
let object = |part: &str| -> Option<Map<String, Json>> {
match serde_json::from_slice(&B64.decode(part).ok()?).ok()? {
Json::Object(m) => Some(m),
_ => None,
}
};
let (Some(header), Some(claims), Ok(sig)) = (object(h), object(c), B64.decode(s)) else {
return invalid("DPoP proof is not a JWT");
};
if header.get("typ").and_then(Json::as_str) != Some("dpop+jwt") {
return invalid("DPoP proof typ must be dpop+jwt");
}
let Some(alg) = header
.get("alg")
.and_then(Json::as_str)
.filter(|a| ALGS.contains(a))
else {
return invalid("DPoP proof alg is not supported");
};
let Some(jwk) = header.get("jwk").and_then(Json::as_object) else {
return invalid("DPoP proof has no jwk");
};
let Some(key) = key(jwk, alg) else {
return invalid("DPoP proof jwk is not a public key for its alg");
};
if !verify(&key, format!("{h}.{c}").as_bytes(), &sig) {
return invalid("DPoP proof signature is invalid");
}
let now = svc.sessions.now();
let Some(iat) = claims.get("iat").and_then(Json::as_f64) else {
return invalid("DPoP proof has no iat");
};
if iat < now as f64 - IAT_BEFORE || iat > now as f64 + IAT_AFTER {
return invalid("DPoP proof iat is out of range");
}
match claims.get("exp") {
None => {}
Some(e) if e.as_f64().is_some_and(|e| e >= now as f64 - EXP_PAST) => {}
Some(_) => return invalid("DPoP proof is expired"),
}
// 2. What it names.
let nonce = match claims.get("nonce") {
None => None,
Some(Json::String(n)) => Some(n.as_str()),
Some(_) => return invalid("DPoP proof nonce must be a string"),
};
let Some(jti) = claims
.get("jti")
.and_then(Json::as_str)
.filter(|j| !j.is_empty())
else {
return invalid("DPoP proof has no jti");
};
if claims.get("htm").and_then(Json::as_str) != Some(method) {
return invalid("DPoP proof htm does not match the request");
}
let Some(htu) = claims
.get("htu")
.and_then(Json::as_str)
.and_then(|u| url::Url::parse(u).ok())
else {
return invalid("DPoP proof htu is not a URL");
};
if !["http", "https"].contains(&htu.scheme())
|| !htu.username().is_empty()
|| htu.password().is_some()
{
return invalid("DPoP proof htu is not an http URL");
}
let request = url::Url::parse(&svc.oauth.issuer).and_then(|u| u.join(path));
if !request.is_ok_and(|r| same_url(&htu, &r)) {
return invalid("DPoP proof htu does not match the request");
}
// 3. A nonce the server gave.
let Some(nonce) = nonce else {
return Err(Refusal::Nonce(
"Authorization server requires nonce in DPoP proof".into(),
));
};
if !svc.oauth.takes_nonce(nonce, now) {
return Err(Refusal::Nonce("DPoP nonce mismatch".into()));
}
// 4. The access token it is for, if any.
let named = claims.get("ath");
let right = match ath_of {
None => named.is_none(),
Some(token) => named.and_then(Json::as_str) == Some(ath(token).as_str()),
};
if !right {
return invalid("DPoP proof ath is not the access token's");
}
// 5. Never used before: kept durably, or held in memory.
let until = now + JTI_LIFE;
if svc.replay.holds(NS, jti, now) || !svc.oauth.spend_proof(jti, now, until) {
return invalid("DPoP proof jti was used before");
}
Ok(Some(Proof {
jkt: thumbprint(jwk),
jti: jti.to_string(),
until,
}))
}