chadtmiller.com/monolith
An atproto PDS
0
0
Spaces: the space repo, credentials, and the space authority with its policies
crates/pds-cli/src/lib.rs+33−9
| @@ -103,7 +103,7 @@ fn group_help(group: &str) -> String { | ||
} | ||
| ||
/// `--encoding`, the `Content-Type` of a command whose method takes its body | ||
/// as it is (`uploadBlob`), which it reads from standard input. | ||
/// as it is, of any type (`uploadBlob`), which it reads from standard input. | ||
static ENCODING: LazyLock<Arg> = LazyLock::new(|| Arg { | ||
name: "encoding".into(), | ||
ty: Type::String, | ||
| @@ -113,9 +113,15 @@ static ENCODING: LazyLock<Arg> = LazyLock::new(|| Arg { | ||
def: json!({ "type": "string" }), | ||
}); | ||
| ||
/// A command's flags: its method's arguments, and `--encoding` for one whose body is standard input. | ||
/// The one type a method's raw body may be, as `importSpaceMeta`'s | ||
/// `application/octet-stream`; None for one of any type, as `uploadBlob`'s `*/*`. | ||
fn fixed_encoding(m: &Method) -> Option<&str> { | ||
m.input.as_deref().filter(|i| m.raw_input() && !i.contains('*')) | ||
} | ||
| ||
/// A command's flags: its method's arguments, and `--encoding` for one whose body is standard input of any type. | ||
fn flags_of(m: &Method) -> impl Iterator<Item = &Arg> { | ||
m.args.iter().chain(m.raw_input().then(|| &*ENCODING)) | ||
m.args.iter().chain((m.raw_input() && fixed_encoding(m).is_none()).then(|| &*ENCODING)) | ||
} | ||
| ||
fn command_help(m: &Method) -> String { | ||
| @@ -332,18 +338,22 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> { | ||
} | ||
} | ||
} | ||
// A body of any type is standard input, sent as `--encoding` says. | ||
let raw = match (m.raw_input(), args.get("encoding")) { | ||
(true, Some(Json::String(encoding))) => { | ||
let encoding = encoding.clone(); | ||
args.remove("encoding"); | ||
// A raw body is standard input, sent as its method's one type, or as `--encoding` says. | ||
let given = if m.raw_input() { args.remove("encoding") } else { None }; | ||
let encoding = match (fixed_encoding(m), given) { | ||
(Some(fixed), _) => Some(fixed.to_string()), | ||
(None, Some(Json::String(encoding))) => Some(encoding), | ||
_ => None, | ||
}; | ||
let raw = match encoding { | ||
Some(encoding) => { | ||
let mut body = Vec::new(); | ||
if let Err(e) = std::io::stdin().read_to_end(&mut body) { | ||
return usage(format!("cannot read standard input: {e}")); | ||
} | ||
Some((encoding, body)) | ||
} | ||
_ => None, | ||
None => None, | ||
}; | ||
let mut res = server.send(m, &args, raw)?; | ||
// A method that answers nothing prints `{}`. | ||
| @@ -423,4 +433,18 @@ mod tests { | ||
assert_eq!(Json::Object(got), json!({ "did": "did:plc:x", "cid": "bafy" })); | ||
assert!(flags("com.atproto.sync.getBlob", &["--encoding", "a/b"]).is_err()); | ||
} | ||
| ||
/// `import-space-meta` takes its body from standard input as its one | ||
/// type, `application/octet-stream`: it has no `--encoding`, nor any other flag. | ||
#[test] | ||
fn space_meta_commands() { | ||
let import = pds_lexicon::method("com.atproto.space.importSpaceMeta").unwrap(); | ||
assert_eq!(fixed_encoding(import), Some("application/octet-stream")); | ||
assert_eq!(fixed_encoding(pds_lexicon::method("com.atproto.repo.uploadBlob").unwrap()), None); | ||
assert_eq!(flags("com.atproto.space.importSpaceMeta", &[]).unwrap().unwrap(), Map::new()); | ||
assert!(flags("com.atproto.space.importSpaceMeta", &["--encoding", "application/octet-stream"]).is_err()); | ||
assert!(command_help(import).contains("It takes no flags.")); | ||
let got = flags("com.atproto.space.exportSpaceMeta", &["--space", "at://did:plc:x/space/a.b.c/k"]).unwrap().unwrap(); | ||
assert_eq!(Json::Object(got), json!({ "space": "at://did:plc:x/space/a.b.c/k" })); | ||
} | ||
} | ||
crates/pds-lexicon/src/lib.rs+46−7
| @@ -144,7 +144,15 @@ impl Method { | ||
| ||
/// The procedures that may delete or replace a record, as `spec/COMMANDS.md` | ||
/// lists them: their lexicons cannot say so. | ||
const DESTRUCTIVE: &[&str] = &["com.atproto.repo.deleteRecord", "com.atproto.repo.putRecord", "com.atproto.repo.applyWrites"]; | ||
const DESTRUCTIVE: &[&str] = &[ | ||
"com.atproto.repo.deleteRecord", | ||
"com.atproto.repo.putRecord", | ||
"com.atproto.repo.applyWrites", | ||
"com.atproto.space.deleteRecord", | ||
"com.atproto.space.putRecord", | ||
"com.atproto.space.applyWrites", | ||
"com.atproto.space.clearRecords", | ||
]; | ||
| ||
/// `createRecord` as `create_record` (with `_`) or `create-record` (with `-`). | ||
pub fn split_case(name: &str, sep: char) -> String { | ||
| @@ -336,6 +344,7 @@ fn in_format(format: &str, s: &str) -> bool { | ||
"handle" => valid_handle(s), | ||
"nsid" => valid_nsid(s), | ||
"record-key" => valid_rkey(s), | ||
"space-ref" => pds_space::SpaceRef::parse(s).is_some(), | ||
"tid" => pds_repo::valid_tid(s), | ||
"cid" => valid_cid_string(s), | ||
"at-uri" => s.starts_with("at://"), | ||
| @@ -398,6 +407,9 @@ pub fn validate(nsid: &str, def: &Json, value: &Json, path: &str) -> Result<(), | ||
if def["maxLength"].as_u64().is_some_and(|m| items.len() as u64 > m) { | ||
return bad(&format!("no more than {} elements", def["maxLength"])); | ||
} | ||
if def["minLength"].as_u64().is_some_and(|m| (items.len() as u64) < m) { | ||
return bad(&format!("no fewer than {} elements", def["minLength"])); | ||
} | ||
for (i, v) in items.iter().enumerate() { | ||
validate(nsid, &def["items"], v, &format!("{path}/{i}"))?; | ||
} | ||
| @@ -516,17 +528,30 @@ mod tests { | ||
let delete = method("com.atproto.server.deleteSession").unwrap(); | ||
assert_eq!((delete.tool().as_deref(), delete.output.as_deref(), delete.input.as_deref()), (Some("server_delete_session"), None, None)); | ||
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect(); | ||
assert_eq!(tools.len(), 26, "{tools:?}"); | ||
assert_eq!(tools.len(), 47, "{tools:?}"); | ||
assert!(tools.contains(&"sync_list_repos".to_string()) && tools.contains(&"sync_get_repo_status".to_string())); | ||
// uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command. | ||
for nsid in ["com.atproto.repo.uploadBlob", "com.atproto.sync.getBlob"] { | ||
assert!(tools.contains(&"space_create_space".to_string()) && tools.contains(&"memberspace_put_member".to_string())); | ||
// uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command; | ||
// nor have a space meta archive's export and import. | ||
for nsid in ["com.atproto.repo.uploadBlob", "com.atproto.sync.getBlob", "com.atproto.space.exportSpaceMeta", "com.atproto.space.importSpaceMeta"] { | ||
let m = method(nsid).unwrap(); | ||
assert_eq!((m.tool(), m.command().is_some()), (None, true), "{nsid}"); | ||
} | ||
assert!(method("com.atproto.repo.uploadBlob").unwrap().raw_input()); | ||
assert!(method("com.atproto.space.importSpaceMeta").unwrap().raw_input()); | ||
assert!(!method("com.atproto.repo.createRecord").unwrap().raw_input()); | ||
assert_eq!(groups(), ["identity", "repo", "server", "sync"]); | ||
assert_eq!(groups(), ["identity", "memberspace", "repo", "server", "space", "sync"]); | ||
assert!(method("com.atproto.repo.defs").is_none()); | ||
assert!(method("com.atproto.space.policy").is_none()); | ||
} | ||
| ||
#[test] | ||
fn space_refs_are_checked() { | ||
let m = method("com.atproto.space.getSpace").unwrap(); | ||
assert!(m.parse_params([("space", "at://did:plc:abc/space/com.example.forum/main")]).is_ok()); | ||
for bad in ["at://did:plc:abc/space/com.example.forum", "at://alice.test/space/com.example.forum/main", "nope"] { | ||
assert!(m.parse_params([("space", bad)]).is_err(), "{bad}"); | ||
} | ||
} | ||
| ||
#[test] | ||
| @@ -556,10 +581,18 @@ mod tests { | ||
assert!(!create.arg("did").unwrap().names_account()); | ||
assert_eq!(create.input_schema()["required"], json!(["handle"])); | ||
let hints = |nsid: &str| method(nsid).unwrap().annotations(); | ||
for nsid in ["com.atproto.repo.deleteRecord", "com.atproto.repo.putRecord", "com.atproto.repo.applyWrites"] { | ||
for nsid in [ | ||
"com.atproto.repo.deleteRecord", | ||
"com.atproto.repo.putRecord", | ||
"com.atproto.repo.applyWrites", | ||
"com.atproto.space.deleteRecord", | ||
"com.atproto.space.putRecord", | ||
"com.atproto.space.applyWrites", | ||
"com.atproto.space.clearRecords", | ||
] { | ||
assert_eq!(hints(nsid), Some(json!({ "readOnlyHint": false, "destructiveHint": true })), "{nsid}"); | ||
} | ||
for nsid in ["com.atproto.repo.createRecord", "com.atproto.server.createSession"] { | ||
for nsid in ["com.atproto.repo.createRecord", "com.atproto.server.createSession", "com.atproto.space.createRecord"] { | ||
assert_eq!(hints(nsid), Some(json!({ "readOnlyHint": false, "destructiveHint": false })), "{nsid}"); | ||
} | ||
assert_eq!(hints("com.atproto.sync.subscribeRepos"), None); | ||
| @@ -596,5 +629,11 @@ mod tests { | ||
assert!(del.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "swapRecord": null })).is_err()); | ||
assert!(put.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "a", "record": 5 })).is_err()); | ||
assert!(put.check_input(&json!({ "repo": "alice.test", "collection": "com.example.note", "rkey": "x".repeat(513), "record": {} })).is_err()); | ||
let space = method("com.atproto.space.createRecord").unwrap(); | ||
let body = |s: &str| json!({ "space": s, "repo": "did:plc:abc", "collection": "com.example.note", "record": {} }); | ||
space.check_input(&body("at://did:plc:abc/space/com.example.forum/main")).unwrap(); | ||
for bad in ["at://alice.test/space/com.example.forum/main", "at://did:plc:abc/space/com.example.forum", "did:plc:abc"] { | ||
assert!(space.check_input(&body(bad)).is_err(), "{bad}"); | ||
} | ||
} | ||
} | ||
crates/pds-lexicon/Cargo.toml+1−0
| @@ -6,4 +6,5 @@ publish.workspace = true | ||
| ||
[dependencies] | ||
pds-repo.workspace = true | ||
pds-space.workspace = true | ||
serde_json.workspace = true | ||
crates/pds-repo/src/data.rs+7−1
| @@ -248,7 +248,13 @@ pub fn from_json(j: &Json) -> Result<V, String> { | ||
Ok(match j { | ||
Json::Null => V::Null, | ||
Json::Bool(b) => V::Bool(*b), | ||
Json::Number(n) => V::Int(n.as_i64().ok_or("numbers must be 64-bit integers")?), | ||
// A number whose value is whole is an integer however it is written: | ||
// `1e3` and `1000.0` are 1000, and `-0` is 0. | ||
Json::Number(n) => V::Int(match (n.as_i64(), n.as_f64()) { | ||
(Some(i), _) => i, | ||
(None, Some(f)) if f.fract() == 0.0 && (-(2f64.powi(63))..2f64.powi(63)).contains(&f) => f as i64, | ||
_ => return Err("numbers must be 64-bit integers".into()), | ||
}), | ||
Json::String(s) => V::Str(s.clone()), | ||
Json::Array(a) => V::Arr(a.iter().map(from_json).collect::<Result<_, _>>()?), | ||
Json::Object(o) => { | ||
crates/pds-repo/src/lib.rs+7−0
| @@ -191,6 +191,13 @@ impl Repo { | ||
self.key.verifying_key() | ||
} | ||
| ||
/// Sign `message` with the repository's key, as an `ES256K` JWT is | ||
/// signed: ECDSA over SHA-256 of it, `r ‖ s`, `s` in the lower half. | ||
pub fn sign(&self, message: &[u8]) -> [u8; 64] { | ||
let sig: k256::ecdsa::Signature = self.key.sign_prehash(&Sha256::digest(message)).expect("signing a 32-byte digest"); | ||
sig.normalize_s().unwrap_or(sig).to_bytes().into() | ||
} | ||
| ||
pub fn head_string(&self) -> String { | ||
cid_string(&self.head) | ||
} | ||
crates/pds-server/src/space_credentials/attestation.rsnew+169−0
| @@ -0,0 +1,169 @@ | ||
//! 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. | ||
| ||
use super::jwt::{Jwt, Key}; | ||
use crate::Service; | ||
use crate::single_use::SingleUse; | ||
use serde_json::{Map, Value as Json}; | ||
| ||
/// An attestation's `typ`. | ||
const TYP: &str = "atproto-client-attestation+jwt"; | ||
| ||
/// The most of a client's metadata, or of its key set, read. | ||
const MAX_DOCUMENT: usize = 64 * 1024; | ||
| ||
/// 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. | ||
pub(super) async fn verify(s: &Service, token: &str, authority: &str) -> Option<String> { | ||
let jwt = well_formed(token)?; | ||
let client_id = jwt.claim("iss")?.to_string(); | ||
let keys = client_keys(&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`, a non-empty `jti`, and `iss` its `sub`. | ||
fn well_formed(token: &str) -> 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() | ||
&& 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`: its `jwks`, or the set its `jwks_uri` answers. | ||
async fn client_keys(client_id: &str) -> Option<Vec<Json>> { | ||
let http = reqwest::Client::builder() | ||
.redirect(reqwest::redirect::Policy::none()) | ||
.connect_timeout(std::time::Duration::from_secs(5)) | ||
.timeout(std::time::Duration::from_secs(10)) | ||
.build() | ||
.ok()?; | ||
let metadata = fetch(&http, 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(&http, uri).await?, | ||
_ => return None, | ||
}; | ||
jwks.get("keys")?.as_array().cloned() | ||
} | ||
| ||
/// The JSON object an `https` URL answers `200` with, to `GET` with | ||
/// `Accept: application/json`, following no redirect. | ||
async fn fetch(http: &reqwest::Client, url: &str) -> Option<Map<String, Json>> { | ||
let url = reqwest::Url::parse(url).ok().filter(|u| u.scheme() == "https" && u.host_str().is_some())?; | ||
let mut res = http.get(url).header(reqwest::header::ACCEPT, "application/json").send().await.ok()?; | ||
if res.status() != reqwest::StatusCode::OK { | ||
return None; | ||
} | ||
let mut body = Vec::new(); | ||
while let Some(chunk) = res.chunk().await.ok()? { | ||
body.extend_from_slice(&chunk); | ||
if body.len() > MAX_DOCUMENT { | ||
return None; | ||
} | ||
} | ||
match serde_json::from_slice(&body).ok()? { | ||
Json::Object(m) => Some(m), | ||
_ => None, | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; | ||
use p256::ecdsa::signature::Signer; | ||
use serde_json::json; | ||
| ||
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_encoded_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).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"); | ||
// 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).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)).unwrap(), &keys, "did:plc:auth", 900)); | ||
} | ||
| ||
#[tokio::test] | ||
async fn metadata_is_had_only_from_https() { | ||
for id in ["http://127.0.0.1:1/client.json", "not a url", "https://"] { | ||
assert_eq!(client_keys(id).await, None, "{id}"); | ||
} | ||
} | ||
} | ||
crates/pds-server/src/space_credentials/jwt.rsnew+330−0
| @@ -0,0 +1,330 @@ | ||
//! The JWTs of spaces' credentials (`spec/SPACES-CREDENTIALS.md`): compact | ||
//! JWTs signed with ECDSA, read and written; and the keys they are held to, | ||
//! an issuer's `#atproto` key from its DID document ("Issuers' keys") or a | ||
//! client's JSON Web Key. | ||
| ||
use crate::Service; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; | ||
use k256::ecdsa::signature::Verifier; | ||
use pds_repo::Repo; | ||
use serde_json::{Map, Value as Json, json}; | ||
use std::collections::HashMap; | ||
use std::sync::Mutex; | ||
| ||
/// A compact JWT, its parts read: the header and payload, JSON objects; the | ||
/// bytes signed, `<header>.<payload>` as sent; and the signature. | ||
pub(crate) struct Jwt { | ||
pub header: Map<String, Json>, | ||
pub payload: Map<String, Json>, | ||
pub signed: String, | ||
/// None where the third part is not base64url. | ||
pub signature: Option<Vec<u8>>, | ||
} | ||
| ||
impl Jwt { | ||
/// A token of three parts joined by `.`, its header and payload each | ||
/// base64url, without padding, of a JSON object; None if it is not. | ||
pub fn parse(token: &str) -> Option<Jwt> { | ||
let mut parts = token.split('.'); | ||
let (Some(h), Some(p), Some(sig), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return None }; | ||
let object = |part: &str| match serde_json::from_slice(&B64.decode(part).ok()?).ok()? { | ||
Json::Object(m) => Some(m), | ||
_ => None, | ||
}; | ||
Some(Jwt { header: object(h)?, payload: object(p)?, signed: format!("{h}.{p}"), signature: B64.decode(sig).ok() }) | ||
} | ||
| ||
/// A header field's text. | ||
pub fn header(&self, k: &str) -> Option<&str> { | ||
self.header.get(k).and_then(Json::as_str) | ||
} | ||
| ||
/// A claim's text. | ||
pub fn claim(&self, k: &str) -> Option<&str> { | ||
self.payload.get(k).and_then(Json::as_str) | ||
} | ||
| ||
/// A claim that is a number. | ||
pub fn number(&self, k: &str) -> Option<f64> { | ||
self.payload.get(k).filter(|v| v.is_number()).and_then(Json::as_f64) | ||
} | ||
| ||
/// The header's `alg`, if it is a string that is not empty. | ||
pub fn alg(&self) -> Option<&str> { | ||
self.header("alg").filter(|a| !a.is_empty()) | ||
} | ||
} | ||
| ||
/// A JWT of type `typ` with these claims, signed by the repository's key: | ||
/// `ES256K`, low-S, the key named `#atproto`. | ||
pub(crate) fn sign(repo: &Repo, typ: &str, payload: &Json) -> String { | ||
let header = B64.encode(json!({ "alg": "ES256K", "typ": typ, "kid": "#atproto" }).to_string()); | ||
let payload = B64.encode(payload.to_string()); | ||
let sig = repo.sign(format!("{header}.{payload}").as_bytes()); | ||
format!("{header}.{payload}.{}", B64.encode(sig)) | ||
} | ||
| ||
/// A token's `jti`: 16 random bytes as 32 lower case hex digits. | ||
pub(crate) fn new_jti() -> String { | ||
hex::encode(rand::random::<[u8; 16]>()) | ||
} | ||
| ||
/// A public key a JWT may be signed with. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub(crate) enum Key { | ||
K256(k256::ecdsa::VerifyingKey), | ||
P256(p256::ecdsa::VerifyingKey), | ||
} | ||
| ||
/// The multicodecs of a secp256k1 and a P-256 public key, as varints. | ||
const SECP256K1_PUB: [u8; 2] = [0xe7, 0x01]; | ||
const P256_PUB: [u8; 2] = [0x80, 0x24]; | ||
| ||
impl Key { | ||
/// The `alg` of a JWT signed with this key. | ||
pub fn alg(&self) -> &'static str { | ||
match self { | ||
Key::K256(_) => "ES256K", | ||
Key::P256(_) => "ES256", | ||
} | ||
} | ||
| ||
/// A key in `Multikey` form, as a `did:key` is less its `did:key:`: `z`, | ||
/// base58btc of its multicodec and its compressed point. | ||
fn multikey(s: &str) -> Option<Key> { | ||
let bytes = bs58::decode(s.strip_prefix('z')?).into_vec().ok()?; | ||
if let Some(point) = bytes.strip_prefix(&SECP256K1_PUB[..]) { | ||
k256::ecdsa::VerifyingKey::from_sec1_bytes(point).ok().map(Key::K256) | ||
} else { | ||
p256::ecdsa::VerifyingKey::from_sec1_bytes(bytes.strip_prefix(&P256_PUB[..])?).ok().map(Key::P256) | ||
} | ||
} | ||
| ||
/// A key in the legacy form (`atproto/did.md`): `z`, base58btc of the | ||
/// point alone, its curve the method's `type`. | ||
fn legacy(typ: &str, s: &str) -> Option<Key> { | ||
let point = bs58::decode(s.strip_prefix('z')?).into_vec().ok()?; | ||
match typ { | ||
"EcdsaSecp256k1VerificationKey2019" => k256::ecdsa::VerifyingKey::from_sec1_bytes(&point).ok().map(Key::K256), | ||
"EcdsaSecp256r1VerificationKey2019" => p256::ecdsa::VerifyingKey::from_sec1_bytes(&point).ok().map(Key::P256), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// The `#atproto` key of `did`'s document: the first verification method | ||
/// whose `id` is `#atproto` or `<did>#atproto`, as a `Multikey` or in the | ||
/// legacy form. None for a document of another DID. | ||
pub fn of_document(doc: &Json, did: &str) -> Option<Key> { | ||
if doc["id"] != did { | ||
return None; | ||
} | ||
let full = format!("{did}#atproto"); | ||
let method = doc["verificationMethod"].as_array()?.iter().find(|m| m["id"] == "#atproto" || m["id"] == full.as_str())?; | ||
let (typ, multibase) = (method["type"].as_str()?, method["publicKeyMultibase"].as_str()?); | ||
if typ == "Multikey" { Key::multikey(multibase) } else { Key::legacy(typ, multibase) } | ||
} | ||
| ||
/// An elliptic-curve JSON Web Key (RFC 7518 §6.2), on P-256 or secp256k1. | ||
pub fn of_jwk(jwk: &Map<String, Json>) -> Option<Key> { | ||
let coord = |k: &str| B64.decode(jwk.get(k)?.as_str()?).ok().filter(|c| c.len() == 32); | ||
if jwk.get("kty")?.as_str()? != "EC" { | ||
return None; | ||
} | ||
let point = [&[4u8][..], &coord("x")?, &coord("y")?].concat(); | ||
match jwk.get("crv")?.as_str()? { | ||
"P-256" => p256::ecdsa::VerifyingKey::from_sec1_bytes(&point).ok().map(Key::P256), | ||
"secp256k1" => k256::ecdsa::VerifyingKey::from_sec1_bytes(&point).ok().map(Key::K256), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// Whether `sig`, 64 bytes `r ‖ s`, signs `message` with this key under | ||
/// `alg`, which must be the key's. A high-S signature verifies only if | ||
/// `high_s` says it may. | ||
pub fn verifies(&self, alg: &str, message: &[u8], sig: &[u8], high_s: bool) -> bool { | ||
if alg != self.alg() || sig.len() != 64 { | ||
return false; | ||
} | ||
match self { | ||
Key::K256(k) => { | ||
let Ok(sig) = k256::ecdsa::Signature::from_slice(sig) else { return false }; | ||
let sig = match sig.normalize_s() { | ||
Some(low) if high_s => low, | ||
Some(_) => return false, | ||
None => sig, | ||
}; | ||
k.verify(message, &sig).is_ok() | ||
} | ||
Key::P256(k) => { | ||
let Ok(sig) = p256::ecdsa::Signature::from_slice(sig) else { return false }; | ||
(high_s || sig.normalize_s().is_none()) && k.verify(message, &sig).is_ok() | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// Where `did`'s document is: for a `did:plc`, at the directory; for a | ||
/// `did:web`, at its host's `/.well-known/did.json`. None for another. | ||
fn document_url(plc_url: &str, did: &str) -> Option<String> { | ||
if did.starts_with("did:plc:") { | ||
return Some(format!("{}/{did}", plc_url.trim_end_matches('/'))); | ||
} | ||
// A `did:web` with a path, its segments after `:`, is none atproto uses. | ||
let id = did.strip_prefix("did:web:").filter(|id| !id.is_empty() && !id.contains(':'))?; | ||
let host = id.replace("%3A", ":").replace("%3a", ":"); | ||
(!host.contains(['/', '%', '#', '?', '@'])).then(|| format!("https://{host}/.well-known/did.json")) | ||
} | ||
| ||
/// How long a key read from a document is kept before it is read again, in seconds. | ||
const KEY_KEPT: u64 = 300; | ||
/// The most keys kept; past it, all are forgotten. | ||
const KEYS_KEPT: usize = 10_000; | ||
| ||
/// Issuers' keys, as their documents last gave them, and when. | ||
#[derive(Default)] | ||
pub(crate) struct Keys(Mutex<HashMap<String, (Key, u64)>>); | ||
| ||
/// Why a JWT does not verify against its issuer's key. | ||
#[derive(Debug, PartialEq, Eq)] | ||
pub(crate) enum Unverified { | ||
/// The issuer's document cannot be read, or names no `#atproto` key. | ||
NoKey, | ||
/// The signature does not verify against it. | ||
Signature, | ||
} | ||
| ||
/// Verify `jwt`'s signature against `iss`'s `#atproto` key. A key kept is | ||
/// tried first; if it does not verify, the document is read again, and the | ||
/// token verifies if it verifies against the key read then. | ||
pub(crate) async fn verify_issuer(s: &Service, iss: &str, jwt: &Jwt, high_s: bool) -> Result<(), Unverified> { | ||
let alg = jwt.header("alg").unwrap_or_default(); | ||
let sig = jwt.signature.as_deref().unwrap_or_default(); | ||
let now = s.sessions.now(); | ||
let kept = keys_of(&s.space_credentials.keys).get(iss).filter(|(_, at)| now < at + KEY_KEPT).map(|(k, _)| k.clone()); | ||
if let Some(k) = &kept | ||
&& k.verifies(alg, jwt.signed.as_bytes(), sig, high_s) | ||
{ | ||
return Ok(()); | ||
} | ||
let Some(key) = fetch_key(s, iss).await else { return Err(if kept.is_some() { Unverified::Signature } else { Unverified::NoKey }) }; | ||
{ | ||
let mut keys = keys_of(&s.space_credentials.keys); | ||
if keys.len() >= KEYS_KEPT { | ||
keys.clear(); | ||
} | ||
keys.insert(iss.to_string(), (key.clone(), now)); | ||
} | ||
if key.verifies(alg, jwt.signed.as_bytes(), sig, high_s) { Ok(()) } else { Err(Unverified::Signature) } | ||
} | ||
| ||
fn keys_of(k: &Keys) -> std::sync::MutexGuard<'_, HashMap<String, (Key, u64)>> { | ||
k.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) | ||
} | ||
| ||
/// `did`'s `#atproto` key, from its document as served now. | ||
async fn fetch_key(s: &Service, did: &str) -> Option<Key> { | ||
let url = document_url(&s.config.plc_url, did)?; | ||
match crate::plc::document(&s.http, &url).await { | ||
Ok(Some(doc)) => Key::of_document(&doc, did), | ||
Ok(None) => None, | ||
Err(why) => { | ||
eprintln!("pds: {why}"); | ||
None | ||
} | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
#[test] | ||
fn documents_name_keys() { | ||
let k = k256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); | ||
let p = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); | ||
let did_key = crate::plc::did_key(k.verifying_key()); | ||
let doc = |id: &str, typ: &str, mb: &str| json!({ "id": "did:plc:x", "verificationMethod": [{ "id": id, "type": typ, "publicKeyMultibase": mb }] }); | ||
let multikey = did_key.trim_start_matches("did:key:"); | ||
assert_eq!(Key::of_document(&doc("did:plc:x#atproto", "Multikey", multikey), "did:plc:x"), Some(Key::K256(*k.verifying_key()))); | ||
assert_eq!(Key::of_document(&doc("#atproto", "Multikey", multikey), "did:plc:x"), Some(Key::K256(*k.verifying_key()))); | ||
assert_eq!(Key::of_document(&doc("#atproto", "Multikey", multikey), "did:plc:y"), None); | ||
assert_eq!(Key::of_document(&doc("#atproto_kem", "Multikey", multikey), "did:plc:x"), None); | ||
let mut p256_mk = P256_PUB.to_vec(); | ||
p256_mk.extend_from_slice(p.verifying_key().to_encoded_point(true).as_bytes()); | ||
let p256_mk = format!("z{}", bs58::encode(p256_mk).into_string()); | ||
assert_eq!(Key::of_document(&doc("#atproto", "Multikey", &p256_mk), "did:plc:x"), Some(Key::P256(*p.verifying_key()))); | ||
let raw = |b: &[u8]| format!("z{}", bs58::encode(b).into_string()); | ||
let legacy_k = raw(k.verifying_key().to_encoded_point(false).as_bytes()); | ||
let legacy_p = raw(p.verifying_key().to_encoded_point(false).as_bytes()); | ||
assert_eq!(Key::of_document(&doc("#atproto", "EcdsaSecp256k1VerificationKey2019", &legacy_k), "did:plc:x"), Some(Key::K256(*k.verifying_key()))); | ||
assert_eq!(Key::of_document(&doc("#atproto", "EcdsaSecp256r1VerificationKey2019", &legacy_p), "did:plc:x"), Some(Key::P256(*p.verifying_key()))); | ||
assert_eq!(Key::of_document(&doc("#atproto", "EcdsaSecp256r1VerificationKey2019", &legacy_k), "did:plc:x"), None); | ||
assert_eq!(Key::of_document(&json!({ "id": "did:plc:x" }), "did:plc:x"), None); | ||
} | ||
| ||
#[test] | ||
fn signatures_verify_under_their_alg_and_low_s() { | ||
use k256::ecdsa::signature::Signer; | ||
let k = k256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); | ||
let key = Key::K256(*k.verifying_key()); | ||
let sig: k256::ecdsa::Signature = k.sign(b"m"); | ||
let low = sig.normalize_s().unwrap_or(sig); | ||
let order = hex::decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141").unwrap(); | ||
let high = k256::ecdsa::Signature::from_scalars(low.r().to_bytes(), sub(&order, &low.s().to_bytes())).unwrap(); | ||
assert!(key.verifies("ES256K", b"m", &low.to_bytes(), false)); | ||
assert!(!key.verifies("ES256K", b"n", &low.to_bytes(), false)); | ||
assert!(!key.verifies("ES256", b"m", &low.to_bytes(), false)); | ||
assert!(!key.verifies("ES256K", b"m", &high.to_bytes(), false)); | ||
assert!(key.verifies("ES256K", b"m", &high.to_bytes(), true)); | ||
assert!(!key.verifies("ES256K", b"m", &low.to_der().to_bytes(), true)); | ||
| ||
let p = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); | ||
let key = Key::P256(*p.verifying_key()); | ||
let sig: p256::ecdsa::Signature = p.sign(b"m"); | ||
let low = sig.normalize_s().unwrap_or(sig); | ||
let order = hex::decode("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551").unwrap(); | ||
let high = p256::ecdsa::Signature::from_scalars(low.r().to_bytes(), sub(&order, &low.s().to_bytes())).unwrap(); | ||
assert!(key.verifies("ES256", b"m", &low.to_bytes(), false)); | ||
assert!(!key.verifies("ES256K", b"m", &low.to_bytes(), false)); | ||
assert!(!key.verifies("ES256", b"m", &high.to_bytes(), false)); | ||
assert!(key.verifies("ES256", b"m", &high.to_bytes(), true)); | ||
} | ||
| ||
/// `a − b`, 32 bytes big-endian each. | ||
fn sub(a: &[u8], b: &[u8]) -> [u8; 32] { | ||
let mut out = [0u8; 32]; | ||
let mut borrow = 0i16; | ||
for i in (0..32).rev() { | ||
let d = a[i] as i16 - b[i] as i16 - borrow; | ||
borrow = (d < 0) as i16; | ||
out[i] = d.rem_euclid(256) as u8; | ||
} | ||
out | ||
} | ||
| ||
#[test] | ||
fn jwks() { | ||
let p = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap(); | ||
let point = p.verifying_key().to_encoded_point(false); | ||
let jwk = json!({ "kty": "EC", "crv": "P-256", "x": B64.encode(point.x().unwrap()), "y": B64.encode(point.y().unwrap()), "kid": "a" }); | ||
assert_eq!(Key::of_jwk(jwk.as_object().unwrap()), Some(Key::P256(*p.verifying_key()))); | ||
let mut other = jwk.clone(); | ||
other["crv"] = json!("P-384"); | ||
assert_eq!(Key::of_jwk(other.as_object().unwrap()), None); | ||
other["crv"] = json!("secp256k1"); | ||
assert_eq!(Key::of_jwk(other.as_object().unwrap()), None, "a P-256 point is not on secp256k1"); | ||
other["kty"] = json!("RSA"); | ||
assert_eq!(Key::of_jwk(other.as_object().unwrap()), None); | ||
} | ||
| ||
#[test] | ||
fn document_urls() { | ||
assert_eq!(document_url("http://plc/", "did:plc:abc").as_deref(), Some("http://plc/did:plc:abc")); | ||
assert_eq!(document_url("http://plc", "did:web:example.com").as_deref(), Some("https://example.com/.well-known/did.json")); | ||
assert_eq!(document_url("http://plc", "did:web:localhost%3A8080").as_deref(), Some("https://localhost:8080/.well-known/did.json")); | ||
for none in ["did:key:zQ3", "did:web:", "did:web:a.com:path", "did:web:a.com%2Fx"] { | ||
assert_eq!(document_url("http://plc", none), None, "{none}"); | ||
} | ||
} | ||
} | ||
crates/pds-server/src/space_credentials/tests.rsnew+717−0
717 lines changed: not loaded until asked for.
crates/pds-server/src/blobs.rs+3−3
| @@ -499,7 +499,7 @@ pub(crate) async fn upload( | ||
let authorization = crate::authorization(&headers); | ||
let bearer = crate::sessions::Bearer::of(authorization.as_deref()); | ||
let client = crate::limits::client(&headers, peer.map(|Extension(p)| p.0)); | ||
let call = Call { nsid: UPLOAD, method: &method, params: &[], body: &[], bearer, client, charged: OnceLock::new() }; | ||
let call = Call { nsid: UPLOAD, method: &method, params: &[], body: &[], bearer, headers: &headers, client, charged: OnceLock::new() }; | ||
let answer = upload_blob(svc, &call, &headers, &mut body).await; | ||
// A client still sending its body when it is refused, as one too large | ||
// is, may take the connection closing for a failure and never read the | ||
| @@ -875,7 +875,7 @@ pub(crate) async fn test_upload(s: &Shared, token: Option<&str>, content_type: O | ||
}; | ||
let authorization = crate::authorization(&headers); | ||
let bearer = crate::sessions::Bearer::of(authorization.as_deref()); | ||
let call = Call { nsid: UPLOAD, method: &Method::POST, params: &[], body: &[], bearer, client: "127.0.0.1".into(), charged: OnceLock::new() }; | ||
let call = Call { nsid: UPLOAD, method: &Method::POST, params: &[], body: &[], bearer, headers: &headers, client: "127.0.0.1".into(), charged: OnceLock::new() }; | ||
match upload_blob(s.clone(), &call, &headers, &mut body).await { | ||
Ok(Resp::Json(j)) => Ok(j), | ||
Ok(_) => Err((0, "not JSON".into())), | ||
| @@ -1011,7 +1011,7 @@ mod tests { | ||
} | ||
let mut headers = HeaderMap::new(); | ||
headers.insert(header::AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {token}")).unwrap()); | ||
let wrong = Call { nsid: UPLOAD, method: &Method::GET, params: &[], body: &[], bearer: crate::sessions::Bearer::Token(&token), client: String::new(), charged: OnceLock::new() }; | ||
let wrong = Call { nsid: UPLOAD, method: &Method::GET, params: &[], body: &[], bearer: crate::sessions::Bearer::Token(&token), headers: &headers, client: String::new(), charged: OnceLock::new() }; | ||
assert_eq!(upload_blob(s.clone(), &wrong, &headers, &mut Body::empty()).await.err().map(|e| e.name), Some("InvalidRequest")); | ||
// A refused upload leaves nothing behind. | ||
assert_eq!(files(&dir, &did), Vec::<String>::new()); | ||
crates/pds-server/src/compact.rs+39−8
| @@ -55,15 +55,18 @@ pub(crate) fn after_append(s: &Shared) { | ||
| ||
/// Compact `accounts.log` now. | ||
pub(crate) fn run(s: &Service) -> Result<(), String> { | ||
let before = s.sessions.now().saturating_sub(MARGIN); | ||
s.log.rewrite(|frames| fold(frames, before))?; | ||
let now = s.sessions.now(); | ||
let before = now.saturating_sub(MARGIN); | ||
s.log.rewrite(|frames| fold(frames, before, now))?; | ||
s.compaction.base.store(s.log.len(), Ordering::SeqCst); | ||
Ok(()) | ||
} | ||
| ||
/// What `frames` hold now, as entries, without sessions that expired before `before`. | ||
fn fold(frames: Vec<Vec<Json>>, before: u64) -> Result<Vec<Vec<Json>>, String> { | ||
/// What `frames` hold now, as entries, without sessions that expired before | ||
/// `before`, nor single-use values and revocations whose `until` is not after `now`. | ||
fn fold(frames: Vec<Vec<Json>>, before: u64, now: u64) -> Result<Vec<Vec<Json>>, String> { | ||
let mut accounts = Vec::new(); | ||
let mut held = Vec::new(); | ||
let mut keeps: Vec<(String, Keep)> = Vec::new(); | ||
let mut by_did: HashMap<String, usize> = HashMap::new(); | ||
let invites = crate::invites::Invites::default(); | ||
| @@ -79,11 +82,18 @@ fn fold(frames: Vec<Vec<Json>>, before: u64) -> Result<Vec<Vec<Json>>, String> { | ||
keeps[at].1.apply(&e)?; | ||
} | ||
Some(t) if crate::invites::ENTRIES.contains(&t) => invites.replay(&e)?, | ||
Some(t) if t == crate::single_use::ENTRY || t == crate::space_credentials::ENTRY => { | ||
let until = e["until"].as_u64().ok_or_else(|| format!("a {t} entry with no until: {e}"))?; | ||
if until > now { | ||
held.push(e); | ||
} | ||
} | ||
t => return Err(format!("a log entry of no known type: {t:?}")), | ||
} | ||
} | ||
let mut entries = accounts; | ||
entries.extend(invites.entries()); | ||
entries.extend(held); | ||
for (did, k) in &keeps { | ||
entries.extend(k.entries(did, before)); | ||
} | ||
| @@ -98,7 +108,8 @@ mod tests { | ||
| ||
/// Refreshing a session again and again leaves `accounts.log` no larger | ||
/// than what it keeps and a constant factor of slack, and a restart | ||
/// finds every account, session, app password and invite code as before. | ||
/// finds every account, session, app password, invite code, single-use | ||
/// value and credential revocation as before. | ||
#[tokio::test] | ||
async fn refreshing_leaves_the_log_bounded() { | ||
let plc = plc().await; | ||
| @@ -112,6 +123,9 @@ mod tests { | ||
let app = call(&s, "com.atproto.server.createAppPassword", Some(&token), json!({ "name": "phone" })).await.unwrap(); | ||
let login = json!({ "identifier": "alice.test", "password": app["password"] }); | ||
let mut refresh = call(&s, "com.atproto.server.createSession", None, login).await.unwrap()["refreshJwt"].as_str().unwrap().to_string(); | ||
let now = s.sessions.now(); | ||
assert!(crate::single_use::SingleUse::check_and_record(&*s, "nonce", now + 3600)); | ||
s.space_credentials.revoke(&s.log, "at://did:plc:a/space/a.b.c/x", &["j"], now).unwrap(); | ||
let path = dir.join(crate::log::ACCOUNTS_LOG); | ||
let mut largest = 0; | ||
for _ in 0..1500 { | ||
| @@ -129,10 +143,12 @@ mod tests { | ||
// The account keeps at most its sessions' limit, so the log stays small. | ||
assert!(s.sessions.count(&did) <= crate::sessions::MAX_SESSIONS); | ||
assert!(base < 200 * 1024, "{base}"); | ||
let before = (s.sessions.snapshot(), s.invites.snapshot()); | ||
let held = |s: &Service| (s.single_use.snapshot(now), s.space_credentials.snapshot(now)); | ||
let before = (s.sessions.snapshot(), s.invites.snapshot(), held(&s)); | ||
drop(s); | ||
let s = open(&dir, &plc); | ||
assert_eq!((s.sessions.snapshot(), s.invites.snapshot()), before); | ||
assert_eq!((s.sessions.snapshot(), s.invites.snapshot(), held(&s)), before); | ||
assert!(!crate::single_use::SingleUse::check_and_record(&*s, "nonce", now + 3600)); | ||
// The latest token works, and the code can still be used. | ||
call(&s, "com.atproto.server.refreshSession", Some(&refresh), Json::Null).await.unwrap(); | ||
let body = json!({ "handle": "carol.test", "email": "carol@mail.com", "password": "pw", "inviteCode": code["code"] }); | ||
| @@ -151,11 +167,26 @@ mod tests { | ||
vec![session("old", 10), session("recent", 100), session("live", 1000)], | ||
vec![json!({ "t": "refresh", "did": did, "id": "live", "next": "after", "exp": 1000, "nextExp": 2000 })], | ||
]; | ||
let folded = fold(frames, 50).unwrap(); | ||
let folded = fold(frames, 50, 50).unwrap(); | ||
let ids: Vec<&str> = folded.iter().flatten().filter(|e| e["t"] == "session").map(|e| e["id"].as_str().unwrap()).collect(); | ||
// In the order they were made, so that a replay orders them alike. | ||
assert_eq!(ids, ["recent", "live", "after"]); | ||
let live = folded.iter().flatten().find(|e| e["id"] == "live").unwrap(); | ||
assert_eq!(live["next"], json!("after")); | ||
} | ||
| ||
/// Single-use values and revocations are kept until their `until` passes. | ||
#[test] | ||
fn fold_keeps_held_values_until_they_pass() { | ||
let frames = vec![vec![ | ||
json!({ "t": crate::single_use::ENTRY, "v": "a", "until": 40 }), | ||
json!({ "t": crate::single_use::ENTRY, "v": "b", "until": 60 }), | ||
json!({ "t": crate::space_credentials::ENTRY, "space": "s", "credentials": ["old"], "until": 50 }), | ||
json!({ "t": crate::space_credentials::ENTRY, "space": "s", "credentials": ["new"], "until": 51 }), | ||
]]; | ||
let folded: Vec<Json> = fold(frames, 0, 50).unwrap().into_iter().flatten().collect(); | ||
assert_eq!(folded.len(), 2); | ||
assert_eq!(folded[0]["v"], json!("b")); | ||
assert_eq!(folded[1]["credentials"], json!(["new"])); | ||
} | ||
} | ||
crates/pds-server/src/federation.rs+4−2
| @@ -130,12 +130,14 @@ mod tests { | ||
/// A query whose answer is a CAR file: its bytes, or the error's name. | ||
async fn car(s: &Shared, nsid: &str, p: &[(&str, &str)]) -> Result<Vec<u8>, String> { | ||
let p = params(p); | ||
let call = Call { nsid, method: &Method::GET, params: &p, body: b"", bearer: crate::sessions::Bearer::None, client: String::new(), charged: std::sync::OnceLock::new() }; | ||
let headers = Default::default(); | ||
let call = Call { nsid, method: &Method::GET, params: &p, body: b"", bearer: crate::sessions::Bearer::None, headers: &headers, client: String::new(), charged: std::sync::OnceLock::new() }; | ||
match answer(s, &call).await { | ||
Ok(Resp::Car(b)) => Ok(b), | ||
Ok(Resp::Json(j)) => panic!("{nsid} answered JSON: {j}"), | ||
Ok(Resp::Json(j) | Resp::Headed(j, _)) => panic!("{nsid} answered JSON: {j}"), | ||
Ok(Resp::Nothing) => panic!("{nsid} answered nothing"), | ||
Ok(Resp::Blob(_)) => panic!("{nsid} answered a blob"), | ||
Ok(Resp::Octets(_)) => panic!("{nsid} answered an archive"), | ||
Err(e) => Err(e.name.to_string()), | ||
} | ||
} | ||
crates/pds-server/src/lib.rs+54−8
crates/pds-server/src/limits.rs+31−3
crates/pds-server/src/log.rs+276−6
crates/pds-server/src/mcp.rs+7−3
crates/pds-server/src/repo.rs+3−3
crates/pds-server/src/server.rs+1−1
crates/pds-server/src/sessions.rs+1−1
crates/pds-server/src/single_use.rsnew+182−0
crates/pds-server/src/space_authority.rsnew+1554−0
1554 lines changed: not loaded until asked for.
crates/pds-server/src/space_authz.rsnew+547−0
547 lines changed: not loaded until asked for.
crates/pds-server/src/space_credentials.rsnew+406−0
406 lines changed: not loaded until asked for.
crates/pds-server/src/space_repo.rsnew+1537−0
1537 lines changed: not loaded until asked for.
crates/pds-server/Cargo.toml+1−0
crates/pds-space/src/lib.rs+2−0
crates/pds-space/src/space_ref.rsnew+61−0
harness/checks/commands.mjs+3−2
harness/spaces/compare.mjs+26−6
harness/spaces/credentials.mjsnew+600−0
600 lines changed: not loaded until asked for.
harness/spaces/policies.mjsnew+853−0
853 lines changed: not loaded until asked for.
harness/spaces/repo.mjsnew+705−0
705 lines changed: not loaded until asked for.
spec/lexicons/com/atproto/managedspace/policy.jsonnew+22−0
spec/lexicons/com/atproto/memberspace/listMembers.jsonnew+75−0
spec/lexicons/com/atproto/memberspace/member.jsonnew+25−0
spec/lexicons/com/atproto/memberspace/policy.jsonnew+40−0
spec/lexicons/com/atproto/memberspace/putMember.jsonnew+49−0
spec/lexicons/com/atproto/memberspace/removeMember.jsonnew+41−0
spec/lexicons/com/atproto/personalspace/policy.jsonnew+11−0
spec/lexicons/com/atproto/space/applyWrites.jsonnew+163−0
spec/lexicons/com/atproto/space/clearRecords.jsonnew+36−0
spec/lexicons/com/atproto/space/createRecord.jsonnew+79−0
spec/lexicons/com/atproto/space/createSpace.jsonnew+62−0
spec/spaces/lexicons/com/atproto/space/defs.json → spec/lexicons/com/atproto/space/defs.jsonrenamed+0−0
Moved without changes.
spec/lexicons/com/atproto/space/deleteRecord.jsonnew+51−0
spec/lexicons/com/atproto/space/deleteSpace.jsonnew+32−0
spec/lexicons/com/atproto/space/exportSpaceMeta.jsonnew+32−0
spec/lexicons/com/atproto/space/getDelegationToken.jsonnew+34−0
spec/lexicons/com/atproto/space/getLatestCommit.jsonnew+61−0
spec/lexicons/com/atproto/space/getRecord.jsonnew+80−0
spec/lexicons/com/atproto/space/getSpace.jsonnew+45−0
spec/lexicons/com/atproto/space/getSpaceCredential.jsonnew+84−0
spec/lexicons/com/atproto/space/importSpaceMeta.jsonnew+22−0
spec/lexicons/com/atproto/space/listRecords.jsonnew+108−0
spec/lexicons/com/atproto/space/listRepoOps.jsonnew+115−0
spec/lexicons/com/atproto/space/listSpaces.jsonnew+65−0
spec/lexicons/com/atproto/space/notifyCredentialRevoked.jsonnew+31−0
spec/lexicons/com/atproto/space/policy.jsonnew+26−0
spec/lexicons/com/atproto/space/putRecord.jsonnew+75−0
spec/lexicons/com/atproto/space/removeWriter.jsonnew+37−0
spec/lexicons/com/atproto/space/updateSpace.jsonnew+45−0
spec/spaces/lexicons/com/atproto/managedspace/checkUserAccess.jsonnew+48−0
spec/spaces/README.md+10−1
spec/LIMITS.md+22−3
spec/PDS.md+12−0
spec/SPACES-CREDENTIALS.mdnew+398−0
spec/SPACES-POLICIES.mdnew+481−0
481 lines changed: not loaded until asked for.