chadtmiller.com/monolith
An atproto PDS
0
0
//! A confidential client's keys, and its authentication with
//! `private_key_jwt` (RFC 7523 §2.2, §3), as `spec/OAUTH-CLIENTS.md` says
//! under "The client's keys" and "Client authentication".
use super::super::{Out, Params, dpop, refuse};
use crate::Service;
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};
pub(super) const ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
/// How long before the server's clock an assertion's `iat` may be.
const IAT_BEFORE: f64 = 60.0;
/// How long an assertion's `jti` is held: longer than any `iat` is taken.
const JTI_LIFE: u64 = 120;
/// The members a client key may not have: those of a private or secret key.
const PRIVATE: &[&str] = &["d", "p", "q", "dp", "dq", "qi", "oth", "k"];
/// The members of a key the authorization page shows.
const SHOWN: &[&str] = &[
"kty", "crv", "x", "y", "n", "e", "alg", "kid", "use", "key_ops", "x5c", "x5t", "x5t#S256",
"x5u", "ext", "iat", "exp", "nbf", "revoked",
];
fn text<'k>(k: &'k Map<String, Json>, m: &str) -> Option<&'k str> {
k.get(m).and_then(Json::as_str)
}
/// Whether a JWK is a client key: a public key with a `kid`, of a type and
/// curve the page names, its `use` and `key_ops` consistent.
fn client_key(k: &Map<String, Json>) -> bool {
let has = |m: &str| text(k, m).is_some();
let shape = match (text(k, "kty"), text(k, "crv")) {
(Some("EC"), Some("P-256" | "P-384" | "P-521" | "secp256k1")) => has("x") && has("y"),
(Some("RSA"), _) => has("n") && has("e"),
(Some("OKP"), Some("Ed25519" | "Ed448")) => has("x"),
_ => false,
};
let usage = match k.get("use") {
None => None,
Some(Json::String(u)) if u == "sig" || u == "enc" => Some(u.as_str()),
Some(_) => return false,
};
let ops = match k.get("key_ops") {
None => true,
Some(Json::Array(ops)) => {
let ops: Option<Vec<&str>> = ops.iter().map(Json::as_str).collect();
ops.is_some_and(|ops| {
let fits = |o: &str| match usage {
Some("sig") => o == "verify",
Some(_) => o == "encrypt" || o == "wrapKey",
None => ["verify", "encrypt", "wrapKey"].contains(&o),
};
!ops.is_empty()
&& ops
.iter()
.enumerate()
.all(|(i, o)| fits(o) && !ops[..i].contains(o))
})
}
Some(_) => false,
};
has("kid") && shape && ops && !PRIVATE.iter().any(|m| k.contains_key(*m))
}
/// The client keys of a JWKS's `keys`; other entries are ignored.
pub(super) fn client_keys(keys: &[Json]) -> Vec<Map<String, Json>> {
keys.iter()
.filter_map(Json::as_object)
.filter(|k| client_key(k))
.cloned()
.collect()
}
/// A client key as the authorization page shows it.
pub(super) fn shown(k: &Map<String, Json>) -> Json {
Json::Object(
k.iter()
.filter(|(m, _)| SHOWN.contains(&m.as_str()))
.map(|(m, v)| (m.clone(), v.clone()))
.collect(),
)
}
/// Whether a key is fit to verify `alg`: of its type and curve, and its
/// `alg`, `use` and `key_ops`, if given, allowing it.
fn fit(k: &Map<String, Json>, alg: &str) -> bool {
let curve = match alg {
"ES256" => "P-256",
"ES256K" => "secp256k1",
_ => return false,
};
text(k, "kty") == Some("EC")
&& text(k, "crv") == Some(curve)
&& text(k, "alg").is_none_or(|a| a == alg)
&& text(k, "use").is_none_or(|u| u == "sig")
&& k.get("key_ops")
.and_then(Json::as_array)
.is_none_or(|ops| ops.iter().any(|o| o == "verify"))
}
/// What names the key an assertion was signed with: its `kid`, the `alg`,
/// and the public key itself.
fn key_id(k: &Map<String, Json>, alg: &str) -> String {
let public = json!({ "alg": alg, "kid": k["kid"], "kty": k["kty"], "crv": k["crv"], "x": k["x"], "y": k["y"] });
B64.encode(Sha256::digest(public.to_string().as_bytes()))
}
/// Why a client's authentication is refused.
#[derive(Debug, PartialEq, Eq)]
pub(in super::super) enum Refused {
/// 1: the parameters are missing or not of their form.
Request(String),
/// 2: the assertion does not verify.
Client(String),
/// 3: its `jti` was used before.
Replayed,
}
impl Refused {
pub fn out(self) -> Out {
match self {
Refused::Request(d) => refuse(400, "invalid_request", d),
Refused::Client(d) => refuse(400, "invalid_client", d),
Refused::Replayed => {
refuse(400, "invalid_grant", "The client assertion was used before")
}
}
}
}
/// Whether `s` is three dot-separated parts of base64url characters, each at least two.
fn jwt_form(s: &str) -> bool {
let parts: Vec<&str> = s.split('.').collect();
parts.len() == 3
&& parts.iter().all(|p| {
p.len() >= 2
&& p.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
})
}
/// Authenticate a request of `client` (its `client_id`, `keys`): None for a
/// public client, whose assertion, if any, is ignored; for a confidential
/// one, the id of the key that signed its assertion. An assertion that
/// verifies is spent, its entry pushed to `spent`, whatever follows.
pub(in super::super) fn authenticate(
svc: &Service,
client_id: &str,
keys: Option<&[Map<String, Json>]>,
p: &Params,
spent: &mut Vec<Json>,
) -> Result<Option<String>, Refused> {
let Some(keys) = keys else { return Ok(None) };
// 1. Both parameters, of their forms.
let typ = p.text("client_assertion_type").ok().flatten();
let jwt = p.text("client_assertion").ok().flatten();
let (Some(ASSERTION_TYPE), Some(jwt)) = (typ, jwt) else {
return Err(Refused::Request(format!(
"client_assertion_type {ASSERTION_TYPE} and a client_assertion are required"
)));
};
if !jwt_form(jwt) {
return Err(Refused::Request("client_assertion is not a JWT".into()));
}
// 2. The header, the key, the signature, then the claims.
let bad = |why: &str| Err(Refused::Client(why.to_string()));
let mut parts = jwt.split('.');
let (h, c, s) = (
parts.next().unwrap_or_default(),
parts.next().unwrap_or_default(),
parts.next().unwrap_or_default(),
);
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 bad("client_assertion is not a JWT");
};
let Some(alg) = text(&header, "alg").filter(|a| dpop::ALGS.contains(a)) else {
return bad("client_assertion alg is not supported");
};
let Some(kid) = text(&header, "kid") else {
return bad("client_assertion has no kid");
};
let named: Vec<&Map<String, Json>> = keys
.iter()
.filter(|k| text(k, "kid") == Some(kid) && fit(k, alg))
.collect();
let [jwk] = named[..] else {
return bad("client_assertion kid names no one key of the client's fit for its alg");
};
let Some(key) = dpop::key(jwk, alg) else {
return bad("the client's key is not a public key for its alg");
};
if !dpop::verify(&key, format!("{h}.{c}").as_bytes(), &sig) {
return bad("client_assertion signature is invalid");
}
let issuer = &svc.oauth.issuer;
if text(&claims, "iss") != Some(client_id) || text(&claims, "sub") != Some(client_id) {
return bad("client_assertion iss and sub must be the client_id");
}
let aud = match claims.get("aud") {
Some(Json::String(a)) => a == issuer,
Some(Json::Array(a)) => a.iter().any(|a| a == issuer.as_str()),
_ => false,
};
if !aud {
return bad("client_assertion aud must be the issuer");
}
let Some(jti) = claims.get("jti").filter(|j| !j.is_null()) else {
return bad("client_assertion has no jti");
};
let now = svc.sessions.now();
let n = now as f64;
let Some(iat) = claims.get("iat").and_then(Json::as_f64) else {
return bad("client_assertion has no iat");
};
if iat > n || iat < n - IAT_BEFORE {
return bad("client_assertion iat is out of range");
}
if claims
.get("exp")
.is_some_and(|e| e.as_f64().is_none_or(|e| e <= n))
{
return bad("client_assertion is expired");
}
if claims
.get("nbf")
.is_some_and(|e| e.as_f64().is_none_or(|e| e > n))
{
return bad("client_assertion is not yet valid");
}
// 3. Never used before by this client.
let jti = jti.as_str().map_or_else(|| jti.to_string(), str::to_string);
match svc.replay.claim(
&format!("client assertion {client_id}"),
&jti,
now,
now + JTI_LIFE,
) {
Some(e) => spent.push(e),
None => return Err(Refused::Replayed),
}
Ok(Some(key_id(jwk, alg)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn client_keys_are_public_keys_with_a_kid() {
let ec = json!({ "kty": "EC", "crv": "P-256", "x": "AA", "y": "AA", "kid": "a" });
let with = |k: &str, v: Json| {
let mut j = ec.clone();
if v.is_null() {
j.as_object_mut().unwrap().remove(k);
} else {
j[k] = v;
}
j
};
let good = [
ec.clone(),
json!({ "kty": "RSA", "n": "AA", "e": "AQAB", "kid": "r" }),
json!({ "kty": "OKP", "crv": "Ed25519", "x": "AA", "kid": "o" }),
with("use", json!("sig")),
with("use", json!("enc")),
with("key_ops", json!(["verify"])),
with("crv", json!("secp256k1")),
];
for k in &good {
assert_eq!(client_keys(std::slice::from_ref(k)).len(), 1, "{k}");
}
let mut sig_encrypt = with("use", json!("sig"));
sig_encrypt["key_ops"] = json!(["encrypt"]);
let bad = [
with("kid", Json::Null),
with("kid", json!(1)),
with("d", json!("AA")),
with("crv", json!("P-192")),
with("y", Json::Null),
with("use", json!("other")),
with("key_ops", json!([])),
with("key_ops", json!(["verify", "verify"])),
with("key_ops", json!(["sign"])),
sig_encrypt,
json!({ "kty": "oct", "k": "AA", "kid": "s" }),
json!({ "kty": "OKP", "crv": "X25519", "x": "AA", "kid": "o" }),
json!("not a key"),
];
for k in &bad {
assert!(client_keys(std::slice::from_ref(k)).is_empty(), "{k}");
}
let shown = shown(with("other", json!(1)).as_object().unwrap());
assert_eq!(shown, ec);
}
#[test]
fn jwt_forms() {
assert!(jwt_form("aa.bb.cc"));
for bad in [
"abc",
"aa.bb.",
"aa.bb.c",
"aa.b+.cc",
"aa.bb.cc.dd",
"aa.bb=.cc",
] {
assert!(!jwt_form(bad), "{bad}");
}
}
}