~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

OAuth: the authorization server, scopes on every method, and web, native and confidential clients

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:oauthr
crates/pds-server/src/oauth/clients/assertion.rsnew+254−0
@@ -0,0 +1,254 @@
//! 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}");
}
}
}
crates/pds-server/src/oauth/clients/document.rsnew+374−0
@@ -0,0 +1,374 @@
//! A discoverable client's ID and document, checked as
//! `spec/OAUTH-CLIENTS.md` says under "Client IDs" and "What it must say":
//! each field's type, then the checks in the page's order, the first that
//! fails refusing the document.
use super::super::{RESPONSE_TYPES, client, scope};
use super::{Failure, assertion};
use serde_json::{Map, Value as Json};
use std::net::{Ipv4Addr, Ipv6Addr};
use url::{Host, Url};
const META: &str = "invalid_client_metadata";
/// A document failing a numbered check: `invalid_client_metadata`, or for
/// some redirect URIs `invalid_redirect_uri`.
const REFUSED: Failure = Failure::Check(META);
const REDIRECT: Failure = Failure::Check("invalid_redirect_uri");
const GRANT_TYPES: &[&str] = &[
"authorization_code",
"implicit",
"refresh_token",
"password",
"client_credentials",
"urn:ietf:params:oauth:grant-type:jwt-bearer",
"urn:ietf:params:oauth:grant-type:saml2-bearer",
];
const AUTH_METHODS: &[&str] = &["client_secret_basic", "client_secret_jwt", "client_secret_post", "none", "private_key_jwt", "self_signed_tls_client_auth", "tls_client_auth"];
/// A domain name no client on the internet can own: fewer than two labels,
/// or a last label of `test`, `local`, `localhost`, `invalid` or `example`.
pub(super) fn local_name(host: &str) -> bool {
let labels: Vec<&str> = host.split('.').collect();
let last = labels.last().copied().unwrap_or_default();
labels.len() < 2 || ["test", "local", "localhost", "invalid", "example"].iter().any(|l| last.eq_ignore_ascii_case(l))
}
/// A host name as an https client ID or redirect URI may have: not
/// `localhost`, at least two labels, not ending in `.local`.
fn domain_ok(d: &str) -> bool {
let labels: Vec<&str> = d.split('.').collect();
!d.eq_ignore_ascii_case("localhost") && labels.len() >= 2 && labels.iter().all(|l| !l.is_empty()) && !d.to_ascii_lowercase().ends_with(".local")
}
/// A discoverable client's ID, parsed, or the error that refuses it.
pub(super) fn client_id(id: &str) -> Result<Url, &'static str> {
let after = id.strip_prefix("https://").ok_or(META)?;
if id.contains('#') {
return Err(META);
}
let u = Url::parse(id).map_err(|_| META)?;
if !u.username().is_empty() || u.password().is_some() {
return Err(META);
}
let authority = &after[..after.find(['/', '?', '\\']).unwrap_or(after.len())];
let rest = &after[authority.len()..];
let raw_path = &rest[..rest.find('?').unwrap_or(rest.len())];
if raw_path != u.path() || u.path() == "/" || u.path().ends_with('/') {
return Err(META);
}
let Some(Host::Domain(host)) = u.host() else { return Err(META) };
if !domain_ok(host) || authority.contains(':') || u.port().is_some() {
return Err(META);
}
if local_name(host) {
return Err("invalid_client_id");
}
Ok(u)
}
/// A redirect URI's form.
enum Form {
Https(Url),
Loopback(Url),
/// Its scheme.
PrivateUse(String),
}
/// An https URL whose host is not `localhost`, `127.0.0.1` or `[::1]`, and,
/// if a domain name, has at least two labels and does not end in `.local`.
fn https_url(uri: &str) -> Option<Url> {
if !uri.starts_with("https://") {
return None;
}
let u = Url::parse(uri).ok()?;
let ok = match u.host()? {
Host::Domain(d) => domain_ok(d),
Host::Ipv4(a) => a != Ipv4Addr::LOCALHOST,
Host::Ipv6(a) => a != Ipv6Addr::LOCALHOST,
};
ok.then_some(u)
}
fn form(uri: &str) -> Option<Form> {
if let Some(u) = https_url(uri) {
return Some(Form::Https(u));
}
if uri.starts_with("http://") {
return Url::parse(uri).ok().filter(client::loopback).map(Form::Loopback);
}
// A private-use URI: `<label>.<label>…:/path`, its scheme backwards not a local name.
let (scheme, rest) = uri.split_once(':')?;
let labels: Vec<&str> = scheme.split('.').collect();
let label = |l: &&str| l.bytes().next().is_some_and(|b| b.is_ascii_alphabetic()) && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'+');
let backwards: Vec<&str> = labels.iter().rev().copied().collect();
let ok = labels.len() >= 2 && labels.iter().all(label) && rest.starts_with('/') && !rest.starts_with("//") && Url::parse(uri).is_ok() && !local_name(&backwards.join("."));
ok.then(|| Form::PrivateUse(scheme.to_string()))
}
/// Whether `s` is an email address: something, `@`, and a domain name.
fn email(s: &str) -> bool {
s.split_once('@').is_some_and(|(local, domain)| {
!local.is_empty() && !s.contains(char::is_whitespace) && !domain.contains('@') && domain.split('.').count() >= 2 && domain.split('.').all(|l| !l.is_empty())
})
}
/// A document the server took: what the server uses of it, and what the page shows.
#[derive(Debug)]
pub(super) struct Taken {
pub scope: String,
pub redirect_uris: Vec<String>,
pub refresh: bool,
pub confidential: bool,
/// The client keys of its `jwks`, if it has one.
pub jwks: Option<Vec<Map<String, Json>>>,
pub jwks_uri: Option<Url>,
/// The document as taken: the known fields, with their defaults.
pub shown: Json,
}
/// Check the document fetched for client `id` (parsed as `url`): a field
/// not of its type, or no `redirect_uris`, makes it unusable; a numbered
/// check failing refuses it with that check's error.
pub(super) fn check(id: &str, url: &Url, doc: &Map<String, Json>) -> Result<Taken, Failure> {
// Each field of its type; the page shows those known, with defaults.
let mut shown = Map::new();
let mut field = |k: &str, valid: &dyn Fn(&Json) -> bool, default: Option<Json>| -> Result<Option<Json>, Failure> {
match doc.get(k) {
Some(v) if valid(v) => {
shown.insert(k.to_string(), v.clone());
Ok(Some(v.clone()))
}
Some(_) => Err(Failure::Unusable),
None => {
if let Some(d) = &default {
shown.insert(k.to_string(), d.clone());
}
Ok(default)
}
}
};
let string = |v: &Json| v.is_string();
let boolean = |v: &Json| v.is_boolean();
let one_of = |values: &'static [&'static str]| move |v: &Json| v.as_str().is_some_and(|s| values.contains(&s));
let list_of = |values: &'static [&'static str]| move |v: &Json| v.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|s| s.as_str().is_some_and(|s| values.contains(&s))));
let https = |v: &Json| v.as_str().and_then(https_url).is_some();
let strings = |v: &Json| v.as_array().map(|a| a.iter().map(|s| s.as_str().map(str::to_string)).collect::<Option<Vec<String>>>());
let text = |v: Option<Json>| v.and_then(|v| v.as_str().map(str::to_string));
let client_id = text(field("client_id", &|v| v.as_str().is_some_and(|s| !s.is_empty()), None)?);
let redirects = field("redirect_uris", &|v| strings(v).flatten().is_some_and(|r| !r.is_empty() && r.iter().all(|u| form(u).is_some())), None)?;
let redirect_uris = redirects.as_ref().and_then(|v| strings(v).flatten()).ok_or(Failure::Unusable)?;
let response_types = field("response_types", &list_of(RESPONSE_TYPES), Some(Json::from(["code"].as_slice())))?.and_then(|v| strings(&v).flatten()).unwrap_or_default();
let grant_types = field("grant_types", &list_of(GRANT_TYPES), Some(Json::from(["authorization_code"].as_slice())))?.and_then(|v| strings(&v).flatten()).unwrap_or_default();
let scope_string = text(field("scope", &|v| v.as_str().is_some_and(scope::valid), None)?);
let auth = text(field("token_endpoint_auth_method", &one_of(AUTH_METHODS), Some("client_secret_basic".into()))?).unwrap_or_default();
let signing_alg = text(field("token_endpoint_auth_signing_alg", &string, None)?);
let jwks = field("jwks", &|v| v.get("keys").is_some_and(Json::is_array) && v.is_object(), None)?;
let jwks_uri = text(field("jwks_uri", &https, None)?).and_then(|u| https_url(&u));
let application_type = text(field("application_type", &one_of(&["web", "native"]), Some("web".into()))?).unwrap_or_default();
let subject_type = text(field("subject_type", &one_of(&["public", "pairwise"]), Some("public".into()))?).unwrap_or_default();
field("client_name", &string, None)?;
let client_uri = text(field("client_uri", &https, None)?).and_then(|u| https_url(&u));
for k in ["logo_uri", "tos_uri", "policy_uri"] {
field(k, &https, None)?;
}
field("contacts", &|v| strings(v).flatten().is_some_and(|c| c.iter().all(|e| email(e))), None)?;
let dpop_bound = field("dpop_bound_access_tokens", &boolean, None)?;
field("authorization_signed_response_alg", &string, Some("RS256".into()))?;
for k in ["request_object_signing_alg", "authorization_encrypted_response_alg"] {
field(k, &string, None)?;
}
field("require_auth_time", &boolean, None)?;
let tls_bound = field("tls_client_certificate_bound_access_tokens", &boolean, None)?;
let enc = field("authorization_encrypted_response_enc", &one_of(&["A128CBC-HS256"]), None)?;
let details = field("authorization_details_types", &|v| strings(v).flatten().is_some(), None)?;
let max_age = field("default_max_age", &|v| v.is_number(), None)?;
let mut oidc = max_age.is_some();
for k in ["userinfo_signed_response_alg", "userinfo_encrypted_response_alg", "id_token_signed_response_alg"] {
oidc |= field(k, &string, None)?.is_some();
}
let keys = jwks.as_ref().map(|j| assertion::client_keys(j["keys"].as_array().map_or(&[], Vec::as_slice)));
if let Some(k) = &keys {
shown.insert("jwks".into(), serde_json::json!({ "keys": k.iter().map(assertion::shown).collect::<Vec<_>>() }));
}
let forms: Vec<(String, Form)> = redirect_uris.iter().filter_map(|u| form(u).map(|f| (u.clone(), f))).collect();
// The checks, in the page's order.
// 1-3.
if jwks.is_some() && jwks_uri.is_some() {
return Err(REFUSED);
}
if oidc {
return Err(REFUSED);
}
if client_uri.as_ref().is_some_and(|u| matches!(u.host(), Some(Host::Domain(h)) if local_name(h))) {
return Err(REFUSED);
}
// 4. A scope, with atproto, no token twice.
let scope_string = scope_string.ok_or(REFUSED)?;
let tokens = scope::tokens(&scope_string);
if !tokens.contains(&"atproto") || tokens.iter().enumerate().any(|(i, t)| tokens[..i].contains(t)) {
return Err(REFUSED);
}
// 5. Grant types.
let grants: Vec<&str> = grant_types.iter().map(String::as_str).collect();
if grants.iter().enumerate().any(|(i, g)| grants[..i].contains(g) || !["authorization_code", "refresh_token"].contains(g)) {
return Err(REFUSED);
}
// 6-7.
if client_id.as_deref().is_some_and(|c| c != id) || subject_type != "public" {
return Err(REFUSED);
}
// 8. Its authentication.
let confidential = match auth.as_str() {
"none" if signing_alg.is_none() => false,
"private_key_jwt" if (jwks.is_some() || jwks_uri.is_some()) && keys.as_ref().is_none_or(|k| !k.is_empty()) && signing_alg.as_deref().is_some_and(|a| a != "none") => true,
_ => return Err(REFUSED),
};
// 9-12.
if enc.is_some() || tls_bound == Some(Json::Bool(true)) || dpop_bound != Some(Json::Bool(true)) {
return Err(REFUSED);
}
if !response_types.iter().any(|t| t == "code") || !grants.contains(&"authorization_code") {
return Err(REFUSED);
}
if details.as_ref().is_some_and(|d| d.as_array().is_some_and(|a| !a.is_empty())) {
return Err(REFUSED);
}
// 13. Native clients are public.
let native = application_type == "native";
if native && confidential {
return Err(REFUSED);
}
// 14. Each redirect URI.
for (_, f) in &forms {
let refused = match f {
Form::Https(u) | Form::Loopback(u) if !u.username().is_empty() || u.password().is_some() => true,
Form::Loopback(_) | Form::PrivateUse(_) => !native,
Form::Https(u) => matches!(u.host(), Some(Host::Domain(h)) if local_name(h)),
};
if refused {
return Err(REDIRECT);
}
}
// 15-16.
if client_id.is_none() {
return Err(REFUSED);
}
if let Some(c) = &client_uri {
let path = url.path();
let parent = c.path() == path || (c.path().ends_with('/') && path.starts_with(c.path()));
if c.origin() != url.origin() || !parent {
return Err(REFUSED);
}
}
// 17. A native client's redirect URIs are its own.
let host = url.host_str().unwrap_or_default();
let backwards: Vec<&str> = host.split('.').rev().collect();
for (_, f) in &forms {
let refused = match f {
Form::PrivateUse(s) => *s != backwards.join("."),
Form::Https(u) => native && u.origin() != url.origin(),
Form::Loopback(_) => false,
};
if refused {
return Err(REDIRECT);
}
}
Ok(Taken {
scope: scope_string,
redirect_uris,
refresh: grants.contains(&"refresh_token"),
confidential,
jwks: keys,
jwks_uri,
shown: Json::Object(shown),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn client_ids() {
assert!(client_id("https://app.example-client.net/c.json").is_ok());
assert!(client_id("https://app.example-client.net/a/c.json?x=1&y").is_ok());
for (id, why) in [
("http://app.example-client.net/c.json", META),
("HTTPS://app.example-client.net/c.json", META),
("https://app.example-client.net/", META),
("https://app.example-client.net", META),
("https://app.example-client.net?x=1", META),
("https://app.example-client.net/dir/", META),
("https://app.example-client.net/c.json#x", META),
("https://app.example-client.net/c.json#", META),
("https://u:p@app.example-client.net/c.json", META),
("https://app.example-client.net:8443/c.json", META),
("https://app.example-client.net:443/c.json", META),
("https://1.2.3.4/c.json", META),
("https://[2606:4700::1]/c.json", META),
("https://localhost/c.json", META),
("https://harness/c.json", META),
("https://app.harness.local/c.json", META),
("https://app.example-client.net/a/../c.json", META),
("https://app.example-client.net/./c.json", META),
("https://app.example-client.net/c json", META),
("https://app.harness.test/c.json", "invalid_client_id"),
("https://app.harness.EXAMPLE/c.json", "invalid_client_id"),
("https://app.harness.invalid/c.json", "invalid_client_id"),
("https://app.harness.localhost/c.json", "invalid_client_id"),
] {
assert_eq!(client_id(id).err(), Some(why), "{id}");
}
}
#[test]
fn local_names() {
for n in ["harness", "a.test", "a.LOCAL", "a.localhost", "a.invalid", "a.example"] {
assert!(local_name(n), "{n}");
}
for n in ["example.com", "app.example.net", "test.net"] {
assert!(!local_name(n), "{n}");
}
}
#[test]
fn redirect_forms() {
for (u, want) in [
("https://app.example-client.net/cb", "https"),
("https://1.2.3.4/cb", "https"),
("https://app.example-client.net:8443/cb", "https"),
("https://u:p@app.example-client.net/cb", "https"),
("http://127.0.0.1/cb", "loopback"),
("http://[::1]:8080/cb", "loopback"),
("net.example-client.app:/cb", "private"),
("com.example.app:/cb", "private"),
] {
let got = match form(u) {
Some(Form::Https(_)) => "https",
Some(Form::Loopback(_)) => "loopback",
Some(Form::PrivateUse(_)) => "private",
None => "none",
};
assert_eq!(got, want, "{u}");
}
for u in [
"https://localhost/cb",
"https://127.0.0.1/cb",
"https://[::1]/cb",
"https://harness/cb",
"https://a.harness.local/cb",
"http://app.example-client.net/cb",
"http://localhost/cb",
"nope",
"harnessapp:/cb",
"net.example.app://cb",
"test.harness:/cb",
"net.example.app:cb",
] {
assert!(form(u).is_none(), "{u}");
}
}
}
crates/pds-server/src/oauth/clients/fetch.rsnew+262−0
@@ -0,0 +1,262 @@
//! Fetching a client's document or JWKS, as `spec/OAUTH-CLIENTS.md` says
//! under "The document": one `GET`, no redirect followed, `200`, JSON of at
//! most 512 KiB, within 10 seconds, over https from public unicast
//! addresses only; or, for an origin `PDS_OAUTH_CLIENT_FETCH` lists, from
//! the base URL it names instead ("The development fetch").
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
use serde_json::{Map, Value as Json};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use url::{Host, Url};
/// The largest answer taken.
const MAX_BODY: usize = 512 * 1024;
/// How long an answer may take, whole.
const TIMEOUT: Duration = Duration::from_secs(10);
/// The variable that names the development fetch.
const VAR: &str = "PDS_OAUTH_CLIENT_FETCH";
/// The development fetch: each origin, `https://<host>`, and the base URL
/// its documents are fetched from instead.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ClientFetch(Vec<(String, String)>);
impl ClientFetch {
/// `PDS_OAUTH_CLIENT_FETCH`, if set: Err if it does not parse. Set to
/// nothing, it is as unset, as the server's other optional variables are.
pub fn from_env() -> Result<Option<ClientFetch>, String> {
match std::env::var(VAR) {
Ok(v) if !v.trim().is_empty() => ClientFetch::parse(&v).map(Some).map_err(|e| format!("{VAR}: {e}")),
_ => Ok(None),
}
}
/// A comma-separated list of `<origin>=<base URL>`.
pub fn parse(s: &str) -> Result<ClientFetch, String> {
let mut out = Vec::new();
for item in s.split(',').map(str::trim) {
let (origin, base) = item.split_once('=').ok_or_else(|| format!("{item:?} is not <origin>=<base URL>"))?;
let o = Url::parse(origin).map_err(|e| format!("{origin:?}: {e}"))?;
let host = match o.host() {
Some(Host::Domain(h)) => h.to_string(),
_ => return Err(format!("{origin:?} is not an https origin with a host name")),
};
if o.scheme() != "https" || origin != format!("https://{host}") {
return Err(format!("{origin:?} is not https://<host>, with no port or path"));
}
let b = Url::parse(base).map_err(|e| format!("{base:?}: {e}"))?;
let plain = b.username().is_empty() && b.password().is_none() && b.query().is_none() && b.fragment().is_none();
if !["http", "https"].contains(&b.scheme()) || b.host().is_none() || !plain || base.ends_with('/') || base.contains(['?', '#']) {
return Err(format!("{base:?} is not an http or https URL with a host, an optional port and path, and no trailing /"));
}
out.push((origin.to_string(), base.to_string()));
}
Ok(ClientFetch(out))
}
/// Where `url` is fetched from instead, if its origin is listed.
fn target(&self, url: &Url) -> Option<String> {
let origin = url.origin().ascii_serialization();
let (_, base) = self.0.iter().find(|(o, _)| *o == origin)?;
let query = url.query().map(|q| format!("?{q}")).unwrap_or_default();
Some(format!("{base}{}{query}", url.path()))
}
}
/// What is fetched: a document must say it is JSON, a JWKS may say nothing.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Kind {
Document,
Jwks,
}
/// Whether an address is a public unicast one: none of the loopback,
/// private, link-local, shared, documentation, multicast, reserved and
/// other special ranges, nor an IPv6 form of one of those IPv4 addresses.
pub(super) fn public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(a) => public_v4(a),
IpAddr::V6(a) => public_v6(a),
}
}
fn public_v4(a: Ipv4Addr) -> bool {
let [x, y, z, _] = a.octets();
!(x == 0
|| x == 10
|| x == 127
|| (x == 100 && (64..128).contains(&y))
|| (x == 169 && y == 254)
|| (x == 172 && (16..32).contains(&y))
|| (x == 192 && y == 0 && (z == 0 || z == 2))
|| (x == 192 && y == 88 && z == 99)
|| (x == 192 && y == 168)
|| (x == 198 && (18..20).contains(&y))
|| (x == 198 && y == 51 && z == 100)
|| (x == 203 && y == 0 && z == 113)
|| x >= 224)
}
fn public_v6(a: Ipv6Addr) -> bool {
let s = a.segments();
let embedded = |hi: usize| Ipv4Addr::new((s[hi] >> 8) as u8, s[hi] as u8, (s[hi + 1] >> 8) as u8, s[hi + 1] as u8);
if let Some(v4) = a.to_ipv4_mapped() {
return public_v4(v4);
}
// NAT64's well-known prefix, and 6to4, carry an IPv4 address.
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
return public_v4(embedded(6));
}
if s[0] == 0x2002 {
return public_v4(embedded(1));
}
// Global unicast only, less Teredo, ORCHID and documentation.
(s[0] & 0xe000) == 0x2000 && !(s[0] == 0x2001 && (s[1] == 0 || (0x10..0x30).contains(&s[1]) || s[1] == 0x0db8)) && s[0] != 0x3fff
}
/// A resolver that answers a name's addresses only if every one is public:
/// a name that resolves to a private address is refused, not half-taken.
struct PublicOnly;
impl Resolve for PublicOnly {
fn resolve(&self, name: Name) -> Resolving {
let host = name.as_str().to_string();
Box::pin(async move {
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
if addrs.is_empty() {
return Err(format!("{host} has no address").into());
}
if let Some(a) = addrs.iter().find(|a| !public(a.ip())) {
return Err(format!("{host} resolves to {}, which is not a public address", a.ip()).into());
}
Ok(Box::new(addrs.into_iter()) as Addrs)
})
}
}
/// The clients documents and JWKS are fetched with.
pub(super) struct Fetcher {
/// For the internet: https only, public addresses only.
public: reqwest::Client,
/// The development fetch, and its client, which goes wherever it is told.
dev: Option<(ClientFetch, reqwest::Client)>,
}
fn builder(timeout: Duration) -> reqwest::ClientBuilder {
reqwest::Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none()).timeout(timeout)
}
impl Fetcher {
pub fn new(dev: Option<ClientFetch>) -> Result<Fetcher, String> {
Fetcher::with_timeout(dev, TIMEOUT)
}
pub fn with_timeout(dev: Option<ClientFetch>, timeout: Duration) -> Result<Fetcher, String> {
let public = builder(timeout).https_only(true).dns_resolver(Arc::new(PublicOnly)).build().map_err(|e| format!("an HTTP client: {e}"))?;
let dev = match dev {
Some(d) => Some((d, builder(timeout).build().map_err(|e| format!("an HTTP client: {e}"))?)),
None => None,
};
Ok(Fetcher { public, dev })
}
/// The JSON object at `url`, if it is answered as `spec/OAUTH-CLIENTS.md`
/// takes it; else why not.
pub async fn get(&self, url: &Url, kind: Kind) -> Result<Map<String, Json>, String> {
let (http, target) = match self.dev.as_ref().and_then(|(d, http)| Some((http, d.target(url)?))) {
Some(mapped) => mapped,
None => {
if url.scheme() != "https" {
return Err(format!("{url} is not https"));
}
// The resolver checks names; an address given as one is checked here.
let literal = match url.host() {
Some(Host::Ipv4(a)) => Some(IpAddr::V4(a)),
Some(Host::Ipv6(a)) => Some(IpAddr::V6(a)),
Some(Host::Domain(_)) => None,
None => return Err(format!("{url} has no host")),
};
if literal.is_some_and(|a| !public(a)) {
return Err(format!("{url} is not on a public address"));
}
(&self.public, url.to_string())
}
};
let mut res = http.get(&target).header("accept", "application/json").send().await.map_err(|e| format!("fetching {url}: {e}"))?;
if res.status().as_u16() != 200 {
return Err(format!("{url} answered {}", res.status()));
}
let essence = res.headers().get("content-type").map(|v| v.to_str().unwrap_or_default().split(';').next().unwrap_or_default().trim().to_ascii_lowercase());
let json = essence.as_deref().map_or(kind == Kind::Jwks, |e| e == "application/json");
if !json {
return Err(format!("{url} is not answered as application/json"));
}
if res.content_length().is_some_and(|n| n > MAX_BODY as u64) {
return Err(format!("{url} is over {MAX_BODY} bytes"));
}
let mut body = Vec::new();
while let Some(chunk) = res.chunk().await.map_err(|e| format!("reading {url}: {e}"))? {
if body.len() + chunk.len() > MAX_BODY {
return Err(format!("{url} is over {MAX_BODY} bytes"));
}
body.extend_from_slice(&chunk);
}
match serde_json::from_slice(&body) {
Ok(Json::Object(m)) => Ok(m),
_ => Err(format!("{url} is not a JSON object")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn public_addresses() {
for a in ["8.8.8.8", "1.2.3.4", "2606:4700::1111", "::ffff:8.8.8.8", "64:ff9b::808:808", "2002:808:808::1"] {
assert!(public(a.parse().unwrap()), "{a}");
}
for a in [
"0.0.0.0", "127.0.0.1", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1", "169.254.169.254", "100.64.0.1", "192.0.2.1", "198.18.0.1",
"203.0.113.9", "224.0.0.1", "255.255.255.255", "::", "::1", "fe80::1", "fc00::1", "fd12::1", "ff02::1", "2001:db8::1", "2001::1",
"::ffff:127.0.0.1", "::ffff:10.0.0.1", "64:ff9b::7f00:1", "2002:7f00:1::1", "::127.0.0.1",
] {
assert!(!public(a.parse().unwrap()), "{a}");
}
}
#[tokio::test]
async fn names_of_private_addresses_are_refused() {
let r = PublicOnly.resolve("localhost".parse().unwrap()).await;
assert!(r.is_err());
}
#[test]
fn the_development_fetch() {
let f = ClientFetch::parse("https://app.example-client.net=http://127.0.0.1:4100/server/app,https://b.example-client.net=https://x.net").unwrap();
let u = Url::parse("https://app.example-client.net/c.json?x=1").unwrap();
assert_eq!(f.target(&u).as_deref(), Some("http://127.0.0.1:4100/server/app/c.json?x=1"));
assert_eq!(f.target(&Url::parse("https://b.example-client.net/j").unwrap()).as_deref(), Some("https://x.net/j"));
assert_eq!(f.target(&Url::parse("https://other.example-client.net/c.json").unwrap()), None);
for bad in [
"",
"https://a.net",
"https://a.net=",
"http://a.net=http://127.0.0.1",
"https://a.net/=http://127.0.0.1",
"https://a.net:443=http://127.0.0.1",
"https://a.net/p=http://127.0.0.1",
"https://1.2.3.4=http://127.0.0.1",
"https://a.net=ftp://127.0.0.1",
"https://a.net=http://127.0.0.1/",
"https://a.net=http://127.0.0.1/p?q",
"https://a.net=http://u@127.0.0.1",
"https://a.net=http://127.0.0.1,",
] {
assert!(ClientFetch::parse(bad).is_err(), "{bad}");
}
}
}
crates/pds-server/src/oauth/clients/silent.rsnew+67−0
@@ -0,0 +1,67 @@
//! Silent sign-in, as `spec/OAUTH-CLIENTS.md` says: when the authorization
//! page loads a confidential client's request, the accounts signed in on
//! the device, what each needs, and whether the browser is sent back to the
//! client at once, with a code or an error, rather than shown the page.
use super::super::{LOGIN_LIFE, Request, State, new_id};
use serde_json::{Value as Json, json};
/// Whether an account signed in on the device at `at` needs to sign in again for `r`.
pub(in super::super) fn needs_sign_in(r: &Request, at: u64, now: u64) -> bool {
r.prompt.as_deref() == Some("login") || now.saturating_sub(at) > LOGIN_LIFE
}
/// Whether account `did` must consent to `r`: asked to, or it never
/// approved this client every scope token the request asks for.
fn needs_consent(st: &State, r: &Request, did: &str) -> bool {
let approved = st.approved.get(did).and_then(|c| c.get(&r.client_id));
r.prompt.as_deref() == Some("consent") || approved.is_none_or(|a| r.scope.iter().any(|t| !a.contains(t)))
}
/// A request answered at once: the entries to log, and the parameters the
/// browser is sent back to the client with.
pub(in super::super) type SentBack = (Vec<Json>, Vec<(&'static str, String)>);
/// What the page does with request `id`, `r`, of a confidential client,
/// loaded on `device`, whose `login_hint` names the account `hinted`, if
/// any here: None to show the page.
pub(in super::super) fn decide(
st: &State,
issuer: &str,
id: &str,
r: &Request,
device: &str,
hinted: Option<&str>,
now: u64,
) -> Option<SentBack> {
let signed_in = st.signed_in(device);
let hinted: Vec<&(String, u64)> = signed_in.iter().filter(|(d, _)| Some(d.as_str()) == hinted).collect();
let refuse = |error: &str, description: &str| {
let params = vec![("iss", issuer.to_string()), ("state", r.state.clone()), ("error", error.to_string()), ("error_description", description.to_string())];
Some((vec![json!({ "t": "oauthEndRequest", "id": id })], params))
};
let approve = |did: &str| {
let code = format!("cod-{}", new_id(32));
let entries = vec![
json!({ "t": "oauthLoad", "id": id, "device": device, "expires": r.expires }),
json!({ "t": "oauthApprove", "id": id, "code": code, "did": did, "scope": r.scope, "at": now }),
];
Some((entries, vec![("iss", issuer.to_string()), ("state", r.state.clone()), ("code", code)]))
};
let ready = |(did, at): &(String, u64)| !needs_sign_in(r, *at, now) && !needs_consent(st, r, did);
match r.prompt.as_deref() {
Some("select_account") if signed_in.is_empty() => refuse("account_selection_required", "No account is signed in"),
Some("none") => match hinted[..] {
[] => refuse("login_required", "No account signed in on this device is the one hinted"),
[(_, at)] if needs_sign_in(r, *at, now) => refuse("login_required", "The account must sign in again"),
[(did, _)] if needs_consent(st, r, did) => refuse("consent_required", "The account has not approved this client for these scopes"),
[(did, _)] => approve(did),
_ => refuse("account_selection_required", "More than one account is hinted"),
},
None if r.login_hint.is_some() => match hinted[..] {
[one] if ready(one) => approve(&one.0),
_ => None,
},
_ => None,
}
}
crates/pds-server/src/oauth/clients/tests.rsnew+959−0
959 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/client.rsnew+180−0
@@ -0,0 +1,180 @@
//! The clients the server takes: loopback clients, whose `client_id` is
//! their metadata (`atproto/oauth.md`, "Localhost Client Development"), and
//! the redirect URIs they may name, as `spec/OAUTH.md` says under "Clients".
//! Discoverable clients, whose `client_id` is an `https://` URL, are loaded
//! by `super::clients` into the same `Client`.
use super::scope;
use serde_json::{Map, Value as Json, json};
use std::net::{Ipv4Addr, Ipv6Addr};
use url::{Host, Url};
/// The redirect URIs of a loopback client that names none.
const DEFAULT_REDIRECTS: &[&str] = &["http://127.0.0.1/", "http://[::1]/"];
/// A client, by its `client_id`.
pub(crate) struct Client {
pub id: String,
/// Its scope string.
pub scope: String,
/// In the order given.
pub redirect_uris: Vec<String>,
/// Whether its grant types include `refresh_token`.
pub refresh: bool,
/// A confidential client's keys (`private_key_jwt`); None for a public client.
pub keys: Option<Vec<Map<String, Json>>>,
/// A discoverable client's document, as the authorization page shows it.
pub document: Option<Json>,
}
/// An `http:` URL on `127.0.0.1` or `[::1]`.
pub(super) fn loopback(u: &Url) -> bool {
u.scheme() == "http"
&& match u.host() {
Some(Host::Ipv4(a)) => a == Ipv4Addr::LOCALHOST,
Some(Host::Ipv6(a)) => a == Ipv6Addr::LOCALHOST,
_ => false,
}
}
/// The client a `client_id` names, or the error that refuses it.
pub(crate) fn client(id: &str) -> Result<Client, &'static str> {
const META: &str = "invalid_client_metadata";
let rest = id.strip_prefix("http://localhost").ok_or(META)?;
let rest = rest.strip_prefix('/').unwrap_or(rest);
let query = if rest.is_empty() { "" } else { rest.strip_prefix('?').ok_or(META)? };
if query.contains('#') {
return Err(META);
}
let mut scope = None;
let mut redirect_uris = Vec::new();
for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
match &*k {
"scope" if scope.is_none() => {
let tokens = scope::tokens(&v);
let distinct = tokens.iter().enumerate().all(|(i, t)| !tokens[..i].contains(t));
if !scope::valid(&v) || !tokens.contains(&"atproto") || !distinct {
return Err(META);
}
scope = Some(v.into_owned());
}
"redirect_uri" => {
let u = Url::parse(&v).map_err(|_| META)?;
if !loopback(&u) {
return Err(META);
}
if !u.username().is_empty() || u.password().is_some() {
return Err("invalid_redirect_uri");
}
redirect_uris.push(v.into_owned());
}
_ => return Err(META),
}
}
if redirect_uris.is_empty() {
redirect_uris = DEFAULT_REDIRECTS.iter().map(|u| u.to_string()).collect();
}
Ok(Client { id: id.to_string(), scope: scope.unwrap_or_else(|| "atproto".into()), redirect_uris, refresh: true, keys: None, document: None })
}
impl Client {
/// Its metadata, as the authorization page shows it.
pub fn metadata(&self) -> Json {
if let Some(d) = &self.document {
return d.clone();
}
json!({
"client_id": self.id, "scope": self.scope, "redirect_uris": self.redirect_uris,
"response_types": ["code"], "grant_types": ["authorization_code", "refresh_token"],
"token_endpoint_auth_method": "none", "application_type": "native",
"subject_type": "public", "authorization_signed_response_alg": "RS256",
"dpop_bound_access_tokens": true,
})
}
/// The redirect URI a request gets: the one given, if it is one of the
/// client's, or the client's only one if none is given.
pub fn redirect_uri(&self, given: Option<&str>) -> Option<String> {
match given {
None => match &self.redirect_uris[..] {
[only] => Some(only.clone()),
_ => None,
},
Some(g) => self.redirect_uris.iter().any(|mine| matches(mine, g)).then(|| g.to_string()),
}
}
}
/// Whether a redirect URI given matches one of the client's: equal, or both
/// loopback, the client's with no port, and equal but for the port (RFC 8252 §7.3).
fn matches(mine: &str, given: &str) -> bool {
if mine == given {
return true;
}
let (Ok(m), Ok(mut g)) = (Url::parse(mine), Url::parse(given)) else { return false };
loopback(&m) && loopback(&g) && m.port().is_none() && g.set_port(None).is_ok() && m.as_str() == g.as_str()
}
/// Whether a redirect URI is of a form a request may name: an `https:` URL,
/// an `http:` one on `127.0.0.1` or `[::1]`, or a private-use scheme's.
pub(crate) fn redirect_form(uri: &str) -> bool {
let Ok(u) = Url::parse(uri) else { return false };
match u.scheme() {
"https" => true,
"http" => loopback(&u),
scheme => {
let rest = &uri[scheme.len() + 1..];
scheme.contains('.') && rest.starts_with('/') && !rest.starts_with("//")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn loopback_clients() {
let c = client("http://localhost").unwrap();
assert_eq!((c.scope.as_str(), c.redirect_uris.clone()), ("atproto", vec!["http://127.0.0.1/".to_string(), "http://[::1]/".to_string()]));
let c = client("http://localhost/?scope=atproto+transition:generic&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2Fcb&redirect_uri=http://[::1]/x").unwrap();
assert_eq!(c.scope, "atproto transition:generic");
assert_eq!(c.redirect_uris, ["http://127.0.0.1:8080/cb", "http://[::1]/x"]);
assert_eq!(c.metadata()["redirect_uris"], json!(c.redirect_uris));
for bad in [
"https://localhost",
"http://localhost:80",
"http://localhost/path",
"http://localhost#x",
"http://localhost?other=1",
"http://localhost?scope=transition:generic",
"http://localhost?scope=atproto&scope=atproto",
"http://localhost?scope=atproto+atproto",
"http://localhost?scope=",
"http://localhost?redirect_uri=http://localhost/",
"http://localhost?redirect_uri=https://127.0.0.1/",
"https://example.com/client-metadata.json",
"http://localhostx",
] {
assert_eq!(client(bad).err(), Some("invalid_client_metadata"), "{bad}");
}
assert_eq!(client("http://localhost?redirect_uri=http://u:p@127.0.0.1/").err(), Some("invalid_redirect_uri"));
}
#[test]
fn redirect_uris() {
let c = client("http://localhost?redirect_uri=http://127.0.0.1/cb").unwrap();
assert_eq!(c.redirect_uri(None).as_deref(), Some("http://127.0.0.1/cb"));
assert_eq!(c.redirect_uri(Some("http://127.0.0.1:5000/cb")).as_deref(), Some("http://127.0.0.1:5000/cb"));
assert_eq!(c.redirect_uri(Some("http://127.0.0.1/other")), None);
assert_eq!(client("http://localhost").unwrap().redirect_uri(None), None);
let ported = client("http://localhost?redirect_uri=http://127.0.0.1:1/cb").unwrap();
assert_eq!(ported.redirect_uri(Some("http://127.0.0.1:2/cb")), None);
for ok in ["https://example.com/cb", "http://127.0.0.1:1/", "http://[::1]/", "com.example.app:/cb"] {
assert!(redirect_form(ok), "{ok}");
}
for bad in ["http://localhost/", "http://example.com/", "app:/cb", "com.example.app://cb", "not a url"] {
assert!(!redirect_form(bad), "{bad}");
}
}
}
crates/pds-server/src/oauth/clients.rsnew+161−0
@@ -0,0 +1,161 @@
//! Discoverable clients, whose `client_id` is an `https://` URL, as
//! `spec/OAUTH-CLIENTS.md` says: their documents and JWKS, fetched
//! (`fetch`), checked (`document`) and kept 10 minutes; confidential
//! clients' authentication with `private_key_jwt` (`assertion`); and silent
//! sign-in (`silent`).
//!
//! Documents and JWKS are kept in memory only, each cache behind its own
//! lock, never held across a fetch: a restart forgets them. What must
//! survive (the key a request and session are bound to, the clients each
//! account approved, spent assertions) is in what OAuth logs.
mod assertion;
mod document;
mod fetch;
pub(super) mod silent;
#[cfg(test)]
mod tests;
pub(super) use assertion::authenticate;
pub(crate) use fetch::ClientFetch;
use super::client::{self, Client};
use crate::Service;
use serde_json::{Map, Value as Json};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
const META: &str = "invalid_client_metadata";
/// How long a document or JWKS is kept from when it was fetched.
const KEEP: u64 = 10 * 60;
/// How many of each are kept at most: the oldest goes first.
const KEPT_MAX: usize = 1024;
/// How long a confidential client's session lasts from when it started,
/// and from its last token answer.
pub(super) const CONFIDENTIAL_LIFE: u64 = 730 * 24 * 60 * 60;
pub(super) const CONFIDENTIAL_IDLE: u64 = 90 * 24 * 60 * 60;
/// Why a client cannot be loaded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Failure {
/// Its `client_id` is refused, with this error.
Id(&'static str),
/// Its document or JWKS could not be had, or is not of the form the
/// field table and the redirect URI forms give.
Unusable,
/// Its document fails a numbered check, with this error.
Check(&'static str),
}
impl Failure {
/// The error wherever a client is loaded but at `consent`.
pub fn error(self) -> &'static str {
match self {
Failure::Id(e) | Failure::Check(e) => e,
Failure::Unusable => META,
}
}
/// The error `consent` ends its request with.
pub fn at_consent(self) -> &'static str {
match self {
Failure::Unusable => "server_error",
Failure::Id(_) | Failure::Check(_) => "invalid_request",
}
}
}
/// What is kept by URL, with when it was fetched.
struct Cache<T>(Mutex<HashMap<String, (u64, T)>>);
impl<T: Clone> Cache<T> {
fn new() -> Self {
Cache(Mutex::new(HashMap::new()))
}
fn get(&self, url: &str, now: u64) -> Option<T> {
let kept = self.0.lock().unwrap_or_else(PoisonError::into_inner);
kept.get(url).filter(|(at, _)| now < at + KEEP).map(|(_, v)| v.clone())
}
fn put(&self, url: &str, now: u64, value: T) {
let mut kept = self.0.lock().unwrap_or_else(PoisonError::into_inner);
kept.retain(|_, (at, _)| now < *at + KEEP);
if kept.len() >= KEPT_MAX
&& let Some(oldest) = kept.iter().min_by_key(|(_, (at, _))| *at).map(|(k, _)| k.clone())
{
kept.remove(&oldest);
}
kept.insert(url.to_string(), (now, value));
}
}
/// The documents and JWKS kept, and how they are fetched.
pub(crate) struct Clients {
fetcher: fetch::Fetcher,
documents: Cache<Arc<document::Taken>>,
jwks: Cache<Arc<Vec<Map<String, Json>>>>,
}
impl Clients {
pub fn new(dev: Option<ClientFetch>) -> Result<Clients, String> {
Ok(Clients { fetcher: fetch::Fetcher::new(dev)?, documents: Cache::new(), jwks: Cache::new() })
}
}
/// The client a `client_id` names, as the server checks it wherever it
/// takes one: a loopback client, or a discoverable one, its document and
/// JWKS fetched or kept; or the error that refuses it.
pub(super) async fn load(svc: &Service, id: &str) -> Result<Client, &'static str> {
load_why(svc, id).await.map_err(Failure::error)
}
/// `load`, saying why it fails.
pub(super) async fn load_why(svc: &Service, id: &str) -> Result<Client, Failure> {
if !discoverable(id) {
return client::client(id).map_err(Failure::Id);
}
let url = document::client_id(id).map_err(Failure::Id)?;
let clients = &svc.oauth.clients;
let taken = match clients.documents.get(id, svc.sessions.now()) {
Some(t) => t,
None => {
let doc = clients.fetcher.get(&url, fetch::Kind::Document).await.map_err(|_| Failure::Unusable)?;
let t = Arc::new(document::check(id, &url, &doc)?);
clients.documents.put(id, svc.sessions.now(), t.clone());
t
}
};
// A `jwks_uri` is fetched (or kept) whenever its client is loaded.
let fetched = match &taken.jwks_uri {
Some(u) => Some(jwks(svc, u).await?),
None => None,
};
let keys = taken.confidential.then(|| fetched.map(|k| k.to_vec()).or_else(|| taken.jwks.clone()).unwrap_or_default());
Ok(Client {
id: id.to_string(),
scope: taken.scope.clone(),
redirect_uris: taken.redirect_uris.clone(),
refresh: taken.refresh,
keys,
document: Some(taken.shown.clone()),
})
}
/// The client keys of the JWKS at `url`, fetched or kept.
async fn jwks(svc: &Service, url: &url::Url) -> Result<Arc<Vec<Map<String, Json>>>, Failure> {
let clients = &svc.oauth.clients;
if let Some(k) = clients.jwks.get(url.as_str(), svc.sessions.now()) {
return Ok(k);
}
let set = clients.fetcher.get(url, fetch::Kind::Jwks).await.map_err(|_| Failure::Unusable)?;
let Some(Json::Array(keys)) = set.get("keys") else { return Err(Failure::Unusable) };
let keys = Arc::new(assertion::client_keys(keys));
clients.jwks.put(url.as_str(), svc.sessions.now(), keys.clone());
Ok(keys)
}
/// Whether a `client_id` is a discoverable client's.
pub(super) fn discoverable(id: &str) -> bool {
id.starts_with("https://")
}
crates/pds-server/src/oauth/dpop.rsnew+211−0
crates/pds-server/src/oauth/page.rsnew+671−0
671 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/scope.rsnew+174−0
crates/pds-server/src/oauth/tests.rsnew+1178−0
1178 lines changed: not loaded until asked for.
crates/pds-server/src/scopes/tests.rsnew+484−0
484 lines changed: not loaded until asked for.
crates/pds-server/src/blobs.rs+22−16
crates/pds-server/src/compact.rs+49−5
crates/pds-server/src/lib.rs+35−6
crates/pds-server/src/log.rs+108−4
crates/pds-server/src/oauth.rsnew+1131−0
1131 lines changed: not loaded until asked for.
crates/pds-server/src/replay.rsnew+135−0
crates/pds-server/src/repo.rs+12−6
crates/pds-server/src/scopes.rsnew+440−0
440 lines changed: not loaded until asked for.
crates/pds-server/src/server.rs+11−3
crates/pds-server/src/sessions.rs+17−6
crates/pds-server/Cargo.toml+3−0
harness/checks/crashes.mjs+6−0
harness/checks/limits.mjs+2−1
harness/checks/oauth-clients.mjsnew+736−0
736 lines changed: not loaded until asked for.
harness/checks/oauth-limits.mjsnew+219−0
harness/checks/oauth-scopes.mjsnew+306−0
harness/checks/oauth.mjsnew+1105−0
1105 lines changed: not loaded until asked for.
harness/lib/clients.mjsnew+82−0
harness/lib/env.mjs+9−6
harness/lib/oauth.mjsnew+218−0
harness/lib/processes.mjs+3−1
harness/compare.mjs+9−0
harness/package-lock.json+74−0
harness/package.json+1−0
spec/atproto/LICENSE.txtnew+13−0
spec/atproto/oauth.mdnew+398−0
spec/atproto/permission.mdnew+330−0
spec/rfc/draft-client-id-metadata-document.txtnew+672−0
672 lines changed: not loaded until asked for.
spec/rfc/rfc6749.txtnew+4259−0
A large diff, not shown.
spec/rfc/rfc6750.txtnew+1011−0
1011 lines changed: not loaded until asked for.
spec/rfc/rfc7009.txtnew+619−0
619 lines changed: not loaded until asked for.
spec/rfc/rfc7523.txtnew+675−0
675 lines changed: not loaded until asked for.
spec/rfc/rfc7636.txtnew+1123−0
1123 lines changed: not loaded until asked for.
spec/rfc/rfc8252.txtnew+1179−0
1179 lines changed: not loaded until asked for.
spec/rfc/rfc8414.txtnew+1291−0
1291 lines changed: not loaded until asked for.
spec/rfc/rfc9126.txtnew+938−0
938 lines changed: not loaded until asked for.
spec/rfc/rfc9207.txtnew+447−0
447 lines changed: not loaded until asked for.
spec/rfc/rfc9449.txtnew+2067−0
A large diff, not shown.
spec/rfc/rfc9728.txtnew+1284−0
1284 lines changed: not loaded until asked for.
spec/DURABILITY.md+2−1
spec/LIMITS.md+25−1
spec/OAUTH-CLIENTS.mdnew+443−0
443 lines changed: not loaded until asked for.
spec/OAUTH-SCOPES.mdnew+247−0
spec/OAUTH.mdnew+718−0
718 lines changed: not loaded until asked for.
spec/PDS.md+10−2
spec/SESSIONS.md+4−4
Cargo.lock+3−0
Cargo.toml+3−0
README.md+5−2