~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
320 lines · 12.1 KB Raw History
//! Client attestations (`spec/SPACES-CREDENTIALS.md`, "Verifying a client
//! attestation"): a `private_key_jwt` client assertion addressed to the
//! space host, verified against the keys of the client's metadata, which is
//! fetched through the guard (`outbound`).

use super::jwt::{Jwt, Key};
use crate::Service;
use crate::outbound::{self, Outbound};
use crate::single_use::SingleUse;
use serde_json::{Map, Value as Json};

/// An attestation's `typ`.
const TYP: &str = "atproto-client-attestation+jwt";

/// The furthest ahead of now an attestation's `exp` may be, in seconds.
const MAX_AHEAD: f64 = 3600.0;

/// The client an attestation addressed to the space host of `authority`
/// attests, by its `client_id`; None if it fails. It is spent if it passes.
/// Nothing is fetched for one that fails step 1.
pub(super) async fn verify(s: &Service, token: &str, authority: &str) -> Option<String> {
    let jwt = well_formed(token, s.sessions.now())?;
    let client_id = jwt.claim("iss")?.to_string();
    let keys = client_keys(&s.outbound, &client_id).await?;
    let now = s.sessions.now();
    if !verifies(&jwt, &keys, authority, now) {
        return None;
    }
    let until = jwt
        .number("exp")
        .map_or(0, |e| e.ceil().clamp(0.0, u64::MAX as f64) as u64);
    s.check_and_record(
        &format!("attestation {client_id} {}", jwt.claim("jti")?),
        until,
    )
    .then_some(client_id)
}

/// Step 1: three parts; its `typ` and `alg`; `iss`, `sub` and `aud`, a
/// number `exp` not more than an hour after `now`, a non-empty `jti`, and
/// `iss` its `sub`.
fn well_formed(token: &str, now: u64) -> Option<Jwt> {
    let jwt = Jwt::parse(token)?;
    let present = |k: &str| jwt.payload.get(k).is_some_and(|v| !v.is_null());
    let ok = jwt.header("typ") == Some(TYP)
        && jwt.alg().is_some()
        && ["iss", "sub", "aud"].iter().all(|k| present(k))
        && jwt
            .number("exp")
            .is_some_and(|exp| exp - now as f64 <= MAX_AHEAD)
        && jwt.claim("jti").is_some_and(|j| !j.is_empty())
        && jwt.claim("iss").is_some()
        && jwt.payload.get("iss") == jwt.payload.get("sub");
    ok.then_some(jwt)
}

/// Step 3: signed by the key of the set whose `kid` is the header's, under
/// the header's `alg`; addressed to the authority's PDS; not expired.
fn verifies(jwt: &Jwt, keys: &[Json], authority: &str, now: u64) -> bool {
    let Some(kid) = jwt.header("kid") else {
        return false;
    };
    let alg = jwt.alg().unwrap_or_default();
    let Some(jwk) = keys
        .iter()
        .filter_map(Json::as_object)
        .find(|k| k.get("kid").and_then(Json::as_str) == Some(kid))
    else {
        return false;
    };
    let key_alg = jwk.get("alg").and_then(Json::as_str);
    let signed = Key::of_jwk(jwk).is_some_and(|key| {
        key_alg.is_none_or(|a| a == alg)
            && key.verifies(
                alg,
                jwt.signed.as_bytes(),
                jwt.signature.as_deref().unwrap_or_default(),
                true,
            )
    });
    signed
        && jwt.claim("aud") == Some(format!("{authority}#atproto_pds").as_str())
        && jwt.number("exp").is_some_and(|exp| now as f64 <= exp)
}

/// Step 2: the keys of the client's metadata, fetched from its
/// `client_id`, an `https` URL: its `jwks`, or the set its `jwks_uri`, an
/// `https` URL too, answers.
async fn client_keys(out: &Outbound, client_id: &str) -> Option<Vec<Json>> {
    let metadata = fetch(out, https(client_id)?).await?;
    if metadata.get("client_id").and_then(Json::as_str) != Some(client_id) {
        return None;
    }
    let jwks = match (
        metadata.get("jwks"),
        metadata.get("jwks_uri").and_then(Json::as_str),
    ) {
        (Some(Json::Object(set)), _) => set.clone(),
        (None, Some(uri)) => fetch(out, https(uri)?).await?,
        _ => return None,
    };
    jwks.get("keys")?.as_array().cloned()
}

fn https(url: &str) -> Option<reqwest::Url> {
    reqwest::Url::parse(url)
        .ok()
        .filter(|u| u.scheme() == "https" && u.host_str().is_some())
}

/// The JSON object `url` answers `200` with, to `GET` with `Accept:
/// application/json`, through the guard: no redirect followed (a `3xx` is
/// none), at most `JSON_DOC_MAX` bytes, within `WAIT`.
async fn fetch(out: &Outbound, url: reqwest::Url) -> Option<Map<String, Json>> {
    let request = out
        .client()
        .get(url)
        .header(reqwest::header::ACCEPT, "application/json");
    let got = out
        .fetch_limited(
            crate::ops::Target::Client,
            request,
            outbound::JSON_DOC_MAX,
            outbound::WAIT,
        )
        .await
        .ok()?;
    if got.status != 200 {
        return None;
    }
    match serde_json::from_slice(&got.body).ok()? {
        Json::Object(m) => Some(m),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::space_credentials::tests::counting;
    use axum::Router;
    use axum::http::{StatusCode, header};
    use axum::response::IntoResponse;
    use axum::routing::get;
    use base64::Engine;
    use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
    use p256::ecdsa::signature::Signer;
    use serde_json::json;
    use std::sync::atomic::Ordering;

    fn token(header: Json, payload: Json, key: &p256::ecdsa::SigningKey) -> String {
        let signed = format!(
            "{}.{}",
            B64.encode(header.to_string()),
            B64.encode(payload.to_string())
        );
        let sig: p256::ecdsa::Signature = key.sign(signed.as_bytes());
        format!("{signed}.{}", B64.encode(sig.to_bytes()))
    }

    #[test]
    fn attestations_verify_against_the_clients_keys() {
        let key = p256::ecdsa::SigningKey::from_slice(&[3u8; 32]).unwrap();
        let point = key.verifying_key().to_sec1_point(false);
        let jwk = json!({ "kty": "EC", "crv": "P-256", "kid": "k1", "x": B64.encode(point.x().unwrap()), "y": B64.encode(point.y().unwrap()) });
        let keys = vec![json!({ "kty": "EC", "kid": "other" }), jwk.clone()];
        let client = "https://app.example/client-metadata.json";
        let header = json!({ "typ": TYP, "alg": "ES256", "kid": "k1" });
        let payload = json!({ "iss": client, "sub": client, "aud": "did:plc:auth#atproto_pds", "exp": 1000, "jti": "j" });
        let ok = |h: &Json, p: &Json| {
            let t = token(h.clone(), p.clone(), &key);
            well_formed(&t, 900).is_some_and(|jwt| verifies(&jwt, &keys, "did:plc:auth", 900))
        };
        assert!(ok(&header, &payload));
        // Step 1, each part.
        for (k, v) in [
            ("typ", json!("JWT")),
            ("alg", json!("")),
            ("alg", Json::Null),
        ] {
            let mut h = header.clone();
            h[k] = v;
            assert!(!ok(&h, &payload), "{h}");
        }
        for (k, v) in [
            ("sub", json!("https://other.example")),
            ("exp", json!("1000")),
            ("jti", json!("")),
            ("aud", Json::Null),
            ("iss", Json::Null),
        ] {
            let mut p = payload.clone();
            p[k] = v;
            assert!(!ok(&header, &p), "{p}");
        }
        // Step 3: the key named, the alg, the audience, the time.
        for (k, v) in [
            ("kid", json!("other")),
            ("kid", json!("none")),
            ("alg", json!("ES256K")),
        ] {
            let mut h = header.clone();
            h[k] = v;
            assert!(!ok(&h, &payload), "{h}");
        }
        for (k, v) in [
            ("aud", json!("did:plc:auth")),
            ("aud", json!("did:plc:else#atproto_pds")),
            ("exp", json!(899)),
        ] {
            let mut p = payload.clone();
            p[k] = v;
            assert!(!ok(&header, &p), "{p}");
        }
        let mut p = payload.clone();
        p["exp"] = json!(900);
        assert!(ok(&header, &p), "valid until its exp");
        // An `exp` at most an hour ahead: one more is refused at step 1.
        p["exp"] = json!(900 + 3600);
        assert!(well_formed(&token(header.clone(), p.clone(), &key), 900).is_some());
        p["exp"] = json!(900 + 3601);
        assert!(well_formed(&token(header.clone(), p.clone(), &key), 900).is_none());
        p["exp"] = json!(900.0 + 3600.5);
        assert!(well_formed(&token(header.clone(), p.clone(), &key), 900).is_none());
        // A key whose own alg is another.
        let mut other = jwk.clone();
        other["alg"] = json!("ES256K");
        let t = token(header.clone(), payload.clone(), &key);
        assert!(!verifies(
            &well_formed(&t, 900).unwrap(),
            &[other],
            "did:plc:auth",
            900
        ));
        // Signed by another key.
        let wrong = p256::ecdsa::SigningKey::from_slice(&[4u8; 32]).unwrap();
        assert!(!verifies(
            &well_formed(&token(header.clone(), payload.clone(), &wrong), 900).unwrap(),
            &keys,
            "did:plc:auth",
            900
        ));
    }

    /// Only `https` client ids; and with SSRF protection, none at an IP
    /// address or `localhost`, with no connection made.
    #[tokio::test]
    async fn metadata_is_had_only_from_https() {
        let open = Outbound::new(false).unwrap();
        for id in ["http://127.0.0.1:1/client.json", "not a url", "https://"] {
            assert_eq!(client_keys(&open, id).await, None, "{id}");
        }
        let (port, connections) = counting().await;
        let guarded = Outbound::new(true).unwrap();
        for id in [
            format!("https://localhost:{port}/c.json"),
            format!("https://127.0.0.1:{port}/c.json"),
            format!("https://[::ffff:127.0.0.1]:{port}/c.json"),
        ] {
            assert_eq!(client_keys(&guarded, &id).await, None, "{id}");
        }
        assert_eq!(connections.load(Ordering::SeqCst), 0);
        // Without protection, the same is tried (and fails, no TLS there).
        assert_eq!(
            client_keys(&open, &format!("https://127.0.0.1:{port}/c.json")).await,
            None
        );
        for _ in 0..100 {
            if connections.load(Ordering::SeqCst) > 0 {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        assert_eq!(connections.load(Ordering::SeqCst), 1);
    }

    /// A document is a `200` with a JSON object, followed through no
    /// redirect, of at most `JSON_DOC_MAX` bytes.
    #[tokio::test]
    async fn documents_are_fetched_whole_and_unredirected() {
        let max = outbound::JSON_DOC_MAX;
        // A JSON object of exactly `n` bytes.
        let of = |n: usize| format!("{{\"p\":\"{}\"}}", "x".repeat(n - 8));
        let (edge, over) = (of(max), of(max + 1));
        assert_eq!(edge.len(), max);
        let app = Router::new()
            .route(
                "/ok",
                get(|| async { ([(header::CONTENT_TYPE, "application/json")], r#"{"a":1}"#) }),
            )
            .route(
                "/moved",
                get(|| async { (StatusCode::FOUND, [(header::LOCATION, "/ok")]).into_response() }),
            )
            .route("/edge", get(move || async move { edge }))
            .route("/over", get(move || async move { over }))
            .route("/list", get(|| async { "[1]" }))
            .route(
                "/gone",
                get(|| async { (StatusCode::NOT_FOUND, r#"{"a":1}"#) }),
            );
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let out = Outbound::new(false).unwrap();
        let at = |p: &str| reqwest::Url::parse(&format!("{base}{p}")).unwrap();
        assert_eq!(
            fetch(&out, at("/ok")).await,
            Some(json!({ "a": 1 }).as_object().unwrap().clone())
        );
        assert!(fetch(&out, at("/edge")).await.is_some());
        for refused in ["/moved", "/over", "/list", "/gone"] {
            assert_eq!(fetch(&out, at(refused)).await, None, "{refused}");
        }
        // With protection, not even the `http` URL is asked.
        assert_eq!(fetch(&Outbound::new(true).unwrap(), at("/ok")).await, None);
    }
}