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

The code gates: rustfmt, clippy, cargo-deny and no unsafe code, among the gates

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:code-s
.knotless/workflows/gates.yml+11−8
@@ -1,17 +1,16 @@
# The gates, as `just gates` runs them: the server's own tests, every
# harness run of the server against the reference PDS, several at once,
# and then the performance step, alone. On every pull into main, so the
# merge queue waits on them, and on every push to main. The code gates
# (cargo fmt, clippy, cargo deny, no unsafe code) are not among them:
# `just code` runs them.
# The gates, as `just gates` runs them: the code gates (cargo fmt, clippy,
# cargo deny, no unsafe code), the server's own tests, every harness run of
# the server against the reference PDS, several at once, and then the
# performance step, alone. On every pull into main, so the merge queue waits
# on them, and on every push to main.
#
# Node, the harness's packages and the build are kept between runs.
# Node, the harness's packages, cargo-deny and the build are kept between runs.
image: rust:1.98
runners: [runner.knotless.dev]
on:
push: {refs: [refs/heads/main]}
pull: {base: [refs/heads/main]}
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, harness/node_modules, harness/spaces/node_modules]
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, /opt/cargo-deny, harness/node_modules, harness/spaces/node_modules]
steps:
- uses: chadtmiller.com/steps/node@1
with: {version: 24.22.1}
@@ -20,6 +19,10 @@ steps:
- uses: chadtmiller.com/steps/npm-ci@1
with: {dir: harness/spaces}
# A step at a time, each under the runner's limit on one.
- name: tools
run: rustup component add rustfmt clippy && (test -x /opt/cargo-deny/bin/cargo-deny || cargo install --locked --root /opt/cargo-deny cargo-deny)
- name: code
run: cd harness && PATH=/opt/cargo-deny/bin:/opt/node/bin:$PATH node gates.mjs code
- name: test
run: cargo test
- name: build
crates/pds/src/main.rs+2−0
@@ -1,5 +1,7 @@
//! `pds`: `pds serve` runs the server; anything else is the CLI, calling a running one.
#![forbid(unsafe_code)]
const SERVE_HELP: &str = "Usage: pds serve\n\n\
Run the server, configured by its environment: PDS_PORT, PDS_DATA_DIR, PDS_HOSTNAME,\n\
PDS_PUBLIC_URL, PDS_HANDLE_DOMAINS, PDS_PLC_URL, PDS_PLC_ROTATION_KEY_HEX and,\n\
crates/pds-cli/src/lib.rs+239−52
@@ -4,6 +4,8 @@
//! Exit statuses: 0 for the method's answer, 1 for an error it answers, 2 for
//! a usage error (no call made), 3 for a server that cannot be reached.
#![forbid(unsafe_code)]
use pds_lexicon::{Arg, JSON, Kind, Method, Type};
use serde_json::{Map, Value as Json, json};
use std::io::{Read, Write};
@@ -56,13 +58,20 @@ fn command(args: &[String]) -> Result<u8, Stop> {
if !pds_lexicon::groups().contains(&group.as_str()) {
return usage(format!("no group {group}; `pds --help` lists them"));
}
let Some(name) = args.get(1) else { return usage(format!("pds {group} needs a command\n\n{}", group_help(group))) };
let Some(name) = args.get(1) else {
return usage(format!(
"pds {group} needs a command\n\n{}",
group_help(group)
));
};
if is_help(name) {
print!("{}", group_help(group));
return Ok(0);
}
let Some(m) = pds_lexicon::by_command(group, name) else {
return usage(format!("pds {group} has no command {name}; `pds {group} --help` lists them"));
return usage(format!(
"pds {group} has no command {name}; `pds {group} --help` lists them"
));
};
let Some(args) = parse(m, &args[2..])? else {
print!("{}", command_help(m));
@@ -84,20 +93,30 @@ fn top_help() -> String {
for g in pds_lexicon::groups() {
out.push_str(&format!(" {g}\n"));
for (name, m) in commands(g) {
out.push_str(&format!(" {name:<20} {}\n", m.description.as_deref().unwrap_or("")));
out.push_str(&format!(
" {name:<20} {}\n",
m.description.as_deref().unwrap_or("")
));
}
}
out
}
fn commands(group: &str) -> Vec<(String, &'static Method)> {
pds_lexicon::methods().iter().filter(|m| m.group == group).filter_map(|m| Some((m.command()?, m))).collect()
pds_lexicon::methods()
.iter()
.filter(|m| m.group == group)
.filter_map(|m| Some((m.command()?, m)))
.collect()
}
fn group_help(group: &str) -> String {
let mut out = format!("Usage: pds {group} <command> [flags]\n\nCommands:\n");
for (name, m) in commands(group) {
out.push_str(&format!(" {name:<20} {}\n", m.description.as_deref().unwrap_or("")));
out.push_str(&format!(
" {name:<20} {}\n",
m.description.as_deref().unwrap_or("")
));
}
out
}
@@ -116,16 +135,24 @@ static ENCODING: LazyLock<Arg> = LazyLock::new(|| Arg {
/// 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('*'))
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() && fixed_encoding(m).is_none()).then(|| &*ENCODING))
m.args
.iter()
.chain((m.raw_input() && fixed_encoding(m).is_none()).then(|| &*ENCODING))
}
fn command_help(m: &Method) -> String {
let mut out = format!("Usage: pds {} {} [flags]\n", m.group, m.command().unwrap_or_default());
let mut out = format!(
"Usage: pds {} {} [flags]\n",
m.group,
m.command().unwrap_or_default()
);
if let Some(d) = &m.description {
out.push_str(&format!("\n{d}\n"));
}
@@ -143,7 +170,11 @@ fn command_help(m: &Method) -> String {
about.push_str(a.description.as_deref().unwrap_or(""));
if a.names_account() {
let left_out = "Left out with PDS_TOKEN set, the token's account's DID.";
about.push_str(&if about.is_empty() { left_out.to_string() } else { format!(" {left_out}") });
about.push_str(&if about.is_empty() {
left_out.to_string()
} else {
format!(" {left_out}")
});
}
out.push_str(&format!(" {flag:<32} {}\n", about.trim_end()));
}
@@ -162,13 +193,19 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop
if is_help(a) {
return Ok(None);
}
let Some(flag) = a.strip_prefix("--") else { return usage(format!("unexpected argument {a:?}: flags are --name value")) };
let Some(flag) = a.strip_prefix("--") else {
return usage(format!("unexpected argument {a:?}: flags are --name value"));
};
let (name, inline) = match flag.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (flag, None),
};
let Some(arg) = flags_of(m).find(|x| x.flag() == name) else {
return usage(format!("pds {} {} takes no flag --{name}", m.group, m.command().unwrap_or_default()));
return usage(format!(
"pds {} {} takes no flag --{name}",
m.group,
m.command().unwrap_or_default()
));
};
if values.contains_key(&arg.name) {
return usage(format!("--{name} is given twice"));
@@ -193,9 +230,17 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop
let value = value(arg, text, &mut stdin_read)?;
values.insert(arg.name.clone(), value);
}
let missing: Vec<String> = flags_of(m).filter(|a| a.needed() && !values.contains_key(&a.name)).map(|a| format!("--{}", a.flag())).collect();
let missing: Vec<String> = flags_of(m)
.filter(|a| a.needed() && !values.contains_key(&a.name))
.map(|a| format!("--{}", a.flag()))
.collect();
if !missing.is_empty() {
return usage(format!("pds {} {} needs {}", m.group, m.command().unwrap_or_default(), missing.join(", ")));
return usage(format!(
"pds {} {} needs {}",
m.group,
m.command().unwrap_or_default(),
missing.join(", ")
));
}
Ok(Some(values))
}
@@ -203,11 +248,20 @@ fn parse(m: &Method, flags: &[String]) -> Result<Option<Map<String, Json>>, Stop
/// A flag's value, from its text (None for a bare boolean flag).
fn value(arg: &Arg, text: Option<String>, stdin_read: &mut bool) -> Result<Json, Stop> {
let flag = arg.flag();
let Some(text) = text else { return Ok(Json::Bool(true)) };
let Some(text) = text else {
return Ok(Json::Bool(true));
};
match arg.ty {
Type::String => Ok(Json::String(text)),
Type::Integer => match text.parse::<i64>() {
Ok(n) if text.trim_start_matches('-').bytes().all(|b| b.is_ascii_digit()) => Ok(json!(n)),
Ok(n)
if text
.trim_start_matches('-')
.bytes()
.all(|b| b.is_ascii_digit()) =>
{
Ok(json!(n))
}
_ => usage(format!("--{flag} takes an integer, not {text:?}")),
},
Type::Boolean => match text.as_str() {
@@ -257,18 +311,33 @@ struct Server {
impl Server {
/// Call a method: a query with `args` as its parameters, a procedure with
/// them as its JSON input, or with `raw`, a type and bytes, as its body.
fn send(&self, m: &Method, args: &Map<String, Json>, raw: Option<(String, Vec<u8>)>) -> Result<reqwest::blocking::Response, Stop> {
fn send(
&self,
m: &Method,
args: &Map<String, Json>,
raw: Option<(String, Vec<u8>)>,
) -> Result<reqwest::blocking::Response, Stop> {
let url = format!("{}/xrpc/{}", self.url, m.nsid);
let mut req = match (m.kind, raw) {
(Kind::Procedure, Some((encoding, body))) => self.http.post(&url).header("content-type", encoding).body(body),
(Kind::Procedure, Some((encoding, body))) => self
.http
.post(&url)
.header("content-type", encoding)
.body(body),
// A procedure that takes no input is sent none.
(Kind::Procedure, None) if m.input.is_none() && args.is_empty() => self.http.post(&url),
(Kind::Procedure, None) => self.http.post(&url).header("content-type", JSON).body(Json::Object(args.clone()).to_string()),
(Kind::Procedure, None) => self
.http
.post(&url)
.header("content-type", JSON)
.body(Json::Object(args.clone()).to_string()),
_ => {
let mut params = Vec::new();
for (k, v) in args {
match v {
Json::Array(items) => params.extend(items.iter().map(|i| (k.as_str(), param_text(i)))),
Json::Array(items) => {
params.extend(items.iter().map(|i| (k.as_str(), param_text(i))))
}
v => params.push((k.as_str(), param_text(v))),
}
}
@@ -280,23 +349,34 @@ impl Server {
} else if let Some(password) = &self.admin {
req = req.basic_auth("admin", Some(password));
}
req.send().map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url)))
req.send()
.map_err(|e| Stop::Unreachable(format!("cannot reach {}: {e}", self.url)))
}
/// The token's account's DID, as `getSession` answers it; None for a
/// token it does not answer for.
fn account(&self) -> Result<Option<String>, Stop> {
let get_session = pds_lexicon::method("com.atproto.server.getSession").expect("getSession's lexicon");
let get_session =
pds_lexicon::method("com.atproto.server.getSession").expect("getSession's lexicon");
let (status, body) = answer(self.send(get_session, &Map::new(), None)?, &self.url)?;
Ok(body["did"].as_str().filter(|_| status == 200).map(str::to_string))
Ok(body["did"]
.as_str()
.filter(|_| status == 200)
.map(str::to_string))
}
}
/// A JSON answer's status and body.
fn answer(res: reqwest::blocking::Response, url: &str) -> Result<(u16, Json), Stop> {
let status = res.status().as_u16();
let bytes = res.bytes().map_err(|e| Stop::Unreachable(format!("cannot read the answer of {url}: {e}")))?;
Ok((status, serde_json::from_slice(&bytes).unwrap_or_else(|_| Json::String(String::from_utf8_lossy(&bytes).into_owned()))))
let bytes = res
.bytes()
.map_err(|e| Stop::Unreachable(format!("cannot read the answer of {url}: {e}")))?;
Ok((
status,
serde_json::from_slice(&bytes)
.unwrap_or_else(|_| Json::String(String::from_utf8_lossy(&bytes).into_owned())),
))
}
fn print_line(v: &Json) {
@@ -306,7 +386,10 @@ fn print_line(v: &Json) {
/// Print an error the server answered, as `{status, error, message}`.
fn print_error(status: u16, body: &Json) -> u8 {
let reason = reqwest::StatusCode::from_u16(status).ok().and_then(|s| s.canonical_reason()).unwrap_or("Error");
let reason = reqwest::StatusCode::from_u16(status)
.ok()
.and_then(|s| s.canonical_reason())
.unwrap_or("Error");
let error = body["error"].as_str().unwrap_or(reason);
let message = match (&body["message"], body) {
(Json::String(m), _) => m.clone(),
@@ -321,25 +404,51 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> {
let token = std::env::var("PDS_TOKEN").ok().filter(|t| !t.is_empty());
// A `repo` or `did` left out is the token's account's; with no token, it
// is as required as the lexicon says.
let left_out: Vec<&Arg> = m.args.iter().filter(|a| a.names_account() && !args.contains_key(&a.name)).collect();
let left_out: Vec<&Arg> = m
.args
.iter()
.filter(|a| a.names_account() && !args.contains_key(&a.name))
.collect();
if token.is_none() && !left_out.is_empty() {
let missing: Vec<String> = left_out.iter().map(|a| format!("--{}", a.flag())).collect();
return usage(format!("pds {} {} needs {}, or PDS_TOKEN for its account's", m.group, m.command().unwrap_or_default(), missing.join(", ")));
return usage(format!(
"pds {} {} needs {}, or PDS_TOKEN for its account's",
m.group,
m.command().unwrap_or_default(),
missing.join(", ")
));
}
let Ok(url) = std::env::var("PDS_URL") else { return Err(Stop::Unreachable("PDS_URL is not set: it is the server's URL".into())) };
let http = reqwest::blocking::Client::builder().no_proxy().build().map_err(|e| Stop::Unreachable(e.to_string()))?;
let Ok(url) = std::env::var("PDS_URL") else {
return Err(Stop::Unreachable(
"PDS_URL is not set: it is the server's URL".into(),
));
};
let http = reqwest::blocking::Client::builder()
.no_proxy()
.build()
.map_err(|e| Stop::Unreachable(e.to_string()))?;
let admin = std::env::var("PDS_ADMIN_PASSWORD").ok();
let server = Server { url: url.trim_end_matches('/').to_string(), token, admin, http };
let server = Server {
url: url.trim_end_matches('/').to_string(),
token,
admin,
http,
};
// A token getSession does not answer for leaves them out, for the method to answer it.
if server.token.is_some() && !left_out.is_empty() {
if let Some(did) = server.account()? {
for a in left_out {
args.insert(a.name.clone(), json!(did));
}
if server.token.is_some()
&& !left_out.is_empty()
&& let Some(did) = server.account()?
{
for a in left_out {
args.insert(a.name.clone(), json!(did));
}
}
// 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 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),
@@ -371,7 +480,8 @@ fn call(m: &Method, mut args: Map<String, Json>) -> Result<u8, Stop> {
}
// Bytes, as getRepo's and getBlob's: written as they come.
let mut out = std::io::stdout().lock();
res.copy_to(&mut out).map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?;
res.copy_to(&mut out)
.map_err(|e| Stop::Unreachable(format!("cannot read the answer of {}: {e}", server.url)))?;
let _ = out.flush();
Ok(0)
}
@@ -390,13 +500,53 @@ mod tests {
#[test]
fn flag_values() {
let list = "com.atproto.repo.listRecords";
let got = flags(list, &["--collection", "a.b.c", "--limit", "5", "--reverse"]).unwrap().unwrap();
assert_eq!(Json::Object(got), json!({ "collection": "a.b.c", "limit": 5, "reverse": true }));
let got = flags(list, &["--collection=a.b.c", "--reverse", "false", "--cursor", "--x"]).unwrap().unwrap();
assert_eq!(Json::Object(got), json!({ "collection": "a.b.c", "reverse": false, "cursor": "--x" }));
let put = flags("com.atproto.repo.putRecord", &["--collection", "a.b.c", "--rkey", "-", "--record", r#"{"n":1}"#]).unwrap().unwrap();
assert_eq!(Json::Object(put), json!({ "collection": "a.b.c", "rkey": "-", "record": { "n": 1 } }));
assert_eq!(flags(list, &["--collection", "a.b.c", "--help"]).unwrap(), None);
let got = flags(
list,
&["--collection", "a.b.c", "--limit", "5", "--reverse"],
)
.unwrap()
.unwrap();
assert_eq!(
Json::Object(got),
json!({ "collection": "a.b.c", "limit": 5, "reverse": true })
);
let got = flags(
list,
&[
"--collection=a.b.c",
"--reverse",
"false",
"--cursor",
"--x",
],
)
.unwrap()
.unwrap();
assert_eq!(
Json::Object(got),
json!({ "collection": "a.b.c", "reverse": false, "cursor": "--x" })
);
let put = flags(
"com.atproto.repo.putRecord",
&[
"--collection",
"a.b.c",
"--rkey",
"-",
"--record",
r#"{"n":1}"#,
],
)
.unwrap()
.unwrap();
assert_eq!(
Json::Object(put),
json!({ "collection": "a.b.c", "rkey": "-", "record": { "n": 1 } })
);
assert_eq!(
flags(list, &["--collection", "a.b.c", "--help"]).unwrap(),
None
);
}
#[test]
@@ -424,13 +574,28 @@ mod tests {
#[test]
fn blob_commands() {
let upload = "com.atproto.repo.uploadBlob";
assert_eq!(Json::Object(flags(upload, &["--encoding", "image/png"]).unwrap().unwrap()), json!({ "encoding": "image/png" }));
assert_eq!(
Json::Object(
flags(upload, &["--encoding", "image/png"])
.unwrap()
.unwrap()
),
json!({ "encoding": "image/png" })
);
assert!(flags(upload, &[]).is_err());
assert!(flags(upload, &["--encoding", "a/b", "--repo", "x"]).is_err());
let help = command_help(pds_lexicon::method(upload).unwrap());
assert!(help.contains("--encoding <string>"), "{help}");
let got = flags("com.atproto.sync.getBlob", &["--did", "did:plc:x", "--cid", "bafy"]).unwrap().unwrap();
assert_eq!(Json::Object(got), json!({ "did": "did:plc:x", "cid": "bafy" }));
let got = flags(
"com.atproto.sync.getBlob",
&["--did", "did:plc:x", "--cid", "bafy"],
)
.unwrap()
.unwrap();
assert_eq!(
Json::Object(got),
json!({ "did": "did:plc:x", "cid": "bafy" })
);
assert!(flags("com.atproto.sync.getBlob", &["--encoding", "a/b"]).is_err());
}
@@ -440,11 +605,33 @@ mod tests {
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_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" }));
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/format.rs+157−30
@@ -2,7 +2,9 @@
//! says the server holds them: atproto's syntax vectors, but where the
//! reference differs (`cid`, `uri`).
use pds_repo::data::{valid_at_identifier, valid_cid_string, valid_did, valid_handle, valid_nsid, valid_rkey};
use pds_repo::data::{
valid_at_identifier, valid_cid_string, valid_did, valid_handle, valid_nsid, valid_rkey,
};
/// Whether `s` is a string of `format`; a format the server does not know takes any string.
pub fn valid(format: &str, s: &str) -> bool {
@@ -27,25 +29,47 @@ pub fn valid(format: &str, s: &str) -> bool {
/// optionally a collection's NSID and then a record key; no trailing slash,
/// query or fragment, and at most 8 KB.
pub fn valid_at_uri(s: &str) -> bool {
let Some(rest) = s.strip_prefix("at://").filter(|_| s.len() <= 8 * 1024) else { return false };
let Some(rest) = s.strip_prefix("at://").filter(|_| s.len() <= 8 * 1024) else {
return false;
};
let mut parts = rest.split('/');
let authority = parts.next().unwrap_or_default();
valid_at_identifier(authority)
&& parts.next().is_none_or(|collection| {
valid_nsid(collection) && parts.next().is_none_or(|rkey| valid_rkey(rkey) && parts.next().is_none())
valid_nsid(collection)
&& parts
.next()
.is_none_or(|rkey| valid_rkey(rkey) && parts.next().is_none())
})
}
/// What JavaScript's `\s` matches.
fn js_space(c: char) -> bool {
matches!(c, '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' | '\u{205f}' | '\u{3000}' | '\u{feff}')
matches!(
c,
'\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
..='\u{200a}'
| '\u{2028}'
| '\u{2029}'
| '\u{202f}'
| '\u{205f}'
| '\u{3000}'
| '\u{feff}'
)
}
/// A URI as the reference takes one: what `^\w+:(?:\/\/)?[^\s/][^\s]*$`
/// matches, `\w` being ASCII letters, digits and `_`, of any length.
pub fn valid_uri(s: &str) -> bool {
let Some((scheme, rest)) = s.split_once(':') else { return false };
if scheme.is_empty() || !scheme.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') || rest.chars().any(js_space) {
let Some((scheme, rest)) = s.split_once(':') else {
return false;
};
if scheme.is_empty()
|| !scheme
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'_')
|| rest.chars().any(js_space)
{
return false;
}
// `[^\s/]` after the scheme, or after a `//` that follows it.
@@ -86,18 +110,30 @@ pub fn valid_datetime(s: &str) -> bool {
return false;
}
let num = |from: usize, to: usize| -> Option<i64> {
b[from..to].iter().try_fold(0i64, |n, c| c.is_ascii_digit().then(|| n * 10 + i64::from(c - b'0')))
b[from..to].iter().try_fold(0i64, |n, c| {
c.is_ascii_digit().then(|| n * 10 + i64::from(c - b'0'))
})
};
let punct = [(4, b'-'), (7, b'-'), (10, b'T'), (13, b':'), (16, b':')];
if punct.iter().any(|&(i, c)| b[i] != c) {
return false;
}
let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) =
(num(0, 4), num(5, 7), num(8, 10), num(11, 13), num(14, 16), num(17, 19))
else {
let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) = (
num(0, 4),
num(5, 7),
num(8, 10),
num(11, 13),
num(14, 16),
num(17, 19),
) else {
return false;
};
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 59 {
if !(1..=12).contains(&month)
|| !(1..=31).contains(&day)
|| hour > 23
|| minute > 59
|| second > 59
{
return false;
}
let mut rest = &b[19..];
@@ -114,11 +150,18 @@ pub fn valid_datetime(s: &str) -> bool {
if ![h1, h2, m1, m2].iter().all(u8::is_ascii_digit) {
return false;
}
let (h, m) = (i64::from(h1 - b'0') * 10 + i64::from(h2 - b'0'), i64::from(m1 - b'0') * 10 + i64::from(m2 - b'0'));
let (h, m) = (
i64::from(h1 - b'0') * 10 + i64::from(h2 - b'0'),
i64::from(m1 - b'0') * 10 + i64::from(m2 - b'0'),
);
if h > 23 || m > 59 {
return false;
}
if sign == b'+' { h * 60 + m } else { -(h * 60 + m) }
if sign == b'+' {
h * 60 + m
} else {
-(h * 60 + m)
}
}
_ => return false,
};
@@ -130,8 +173,23 @@ pub fn valid_datetime(s: &str) -> bool {
/// The irregular grandfathered tags of RFC 5646, taken only exactly as it
/// writes them; its grammar takes none of them.
const IRREGULAR: &[&str] = &[
"en-GB-oed", "i-ami", "i-bnn", "i-default", "i-enochian", "i-hak", "i-klingon", "i-lux", "i-mingo", "i-navajo", "i-pwn", "i-tao", "i-tay", "i-tsu", "sgn-BE-FR",
"sgn-BE-NL", "sgn-CH-DE",
"en-GB-oed",
"i-ami",
"i-bnn",
"i-default",
"i-enochian",
"i-hak",
"i-klingon",
"i-lux",
"i-mingo",
"i-navajo",
"i-pwn",
"i-tao",
"i-tay",
"i-tsu",
"sgn-BE-FR",
"sgn-BE-NL",
"sgn-CH-DE",
];
/// A `Language-Tag` of RFC 5646 §2.1's grammar, with no variant or
@@ -145,10 +203,18 @@ pub fn valid_language(s: &str) -> bool {
}
let tags: Vec<&str> = s.split('-').collect();
let n = tags.len();
let alpha = |t: &str, len: std::ops::RangeInclusive<usize>| len.contains(&t.len()) && t.bytes().all(|c| c.is_ascii_alphabetic());
let alnum = |t: &str, len: std::ops::RangeInclusive<usize>| len.contains(&t.len()) && t.bytes().all(|c| c.is_ascii_alphanumeric());
let alpha = |t: &str, len: std::ops::RangeInclusive<usize>| {
len.contains(&t.len()) && t.bytes().all(|c| c.is_ascii_alphabetic())
};
let alnum = |t: &str, len: std::ops::RangeInclusive<usize>| {
len.contains(&t.len()) && t.bytes().all(|c| c.is_ascii_alphanumeric())
};
// A private use subtag sequence from `i`: `x` and one or more of 1–8 alphanumerics, to the end.
let private = |i: usize| tags[i].eq_ignore_ascii_case("x") && i + 1 < n && tags[i + 1..].iter().all(|t| alnum(t, 1..=8));
let private = |i: usize| {
tags[i].eq_ignore_ascii_case("x")
&& i + 1 < n
&& tags[i + 1..].iter().all(|t| alnum(t, 1..=8))
};
if private(0) {
return true;
}
@@ -162,11 +228,19 @@ pub fn valid_language(s: &str) -> bool {
if i < n && alpha(tags[i], 4..=4) {
i += 1;
}
if i < n && (alpha(tags[i], 2..=2) || (tags[i].len() == 3 && tags[i].bytes().all(|c| c.is_ascii_digit()))) {
if i < n
&& (alpha(tags[i], 2..=2)
|| (tags[i].len() == 3 && tags[i].bytes().all(|c| c.is_ascii_digit())))
{
i += 1;
}
let mut variants: Vec<String> = Vec::new();
while i < n && (alnum(tags[i], 5..=8) || (tags[i].len() == 4 && tags[i].as_bytes()[0].is_ascii_digit() && alnum(tags[i], 4..=4))) {
while i < n
&& (alnum(tags[i], 5..=8)
|| (tags[i].len() == 4
&& tags[i].as_bytes()[0].is_ascii_digit()
&& alnum(tags[i], 4..=4)))
{
let v = tags[i].to_ascii_lowercase();
if variants.contains(&v) {
return false;
@@ -212,7 +286,10 @@ mod tests {
("cid", "z7x3CtScH765HvShXT"),
("cid", "zdj7WhuEjrB52m1BisYCtmjH1hSKa7yZ3jEZ9JcXaFRD51wVz"),
("cid", "7134036155352661643226414134664076"),
("cid", "f017012202c5f688262e0ece8569aa6f94d60aad55ca8d9d83734e4a7430d0cff6588ec2b"),
(
"cid",
"f017012202c5f688262e0ece8569aa6f94d60aad55ca8d9d83734e4a7430d0cff6588ec2b",
),
("uri", "content-type:text/plan"),
("uri", "microsoft.windows.camera:thing"),
];
@@ -233,8 +310,15 @@ mod tests {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let name = path.file_name().unwrap().to_str().unwrap().to_string();
let Some((stem, kind)) = name.strip_suffix(".txt").and_then(|n| n.split_once('_')) else { continue };
let format = formats.iter().find(|(f, _)| *f == stem).unwrap_or_else(|| panic!("{name}: no format")).1;
let Some((stem, kind)) = name.strip_suffix(".txt").and_then(|n| n.split_once('_'))
else {
continue;
};
let format = formats
.iter()
.find(|(f, _)| *f == stem)
.unwrap_or_else(|| panic!("{name}: no format"))
.1;
let want = kind == "syntax_valid";
for line in std::fs::read_to_string(&path).unwrap().lines() {
if line.is_empty() || line.starts_with('#') {
@@ -242,7 +326,11 @@ mod tests {
}
// The very long URI the vectors call invalid matches the reference's pattern.
let long_uri = format == "uri" && line.len() > 8000;
let expect = if differs.contains(&(format, line)) || long_uri { !want } else { want };
let expect = if differs.contains(&(format, line)) || long_uri {
!want
} else {
want
};
if valid(format, line) != expect {
wrong.push(format!("{name}: {line:?}"));
}
@@ -255,7 +343,13 @@ mod tests {
#[test]
fn datetimes() {
for ok in ["2023-02-30T00:00:00Z", "2023-04-31T00:00:00Z", "9999-12-31T23:59:59.999Z", "0000-01-01T01:00:00+01:00", "9999-12-31T22:00:00-01:00"] {
for ok in [
"2023-02-30T00:00:00Z",
"2023-04-31T00:00:00Z",
"9999-12-31T23:59:59.999Z",
"0000-01-01T01:00:00+01:00",
"9999-12-31T22:00:00-01:00",
] {
assert!(valid_datetime(ok), "{ok}");
}
for bad in [
@@ -268,7 +362,10 @@ mod tests {
] {
assert!(!valid_datetime(bad), "{bad}");
}
assert!(valid_datetime(&format!("1985-04-12T23:20:50.{}Z", "1".repeat(43))));
assert!(valid_datetime(&format!(
"1985-04-12T23:20:50.{}Z",
"1".repeat(43)
)));
}
#[test]
@@ -285,14 +382,44 @@ mod tests {
#[test]
fn languages() {
for ok in [
"ja", "ban", "ja-jpn", "en-latn-us", "zh-YUE-hk", "en-X-A", "x-fr-ch", "X-fr-CH", "en-GB-oed", "i-default", "sgn-BE-NL", "zh-hakka", "zh-Hakka",
"art-lojban", "no-bok", "zh-min-nan", "sl-rozaj-biske",
"ja",
"ban",
"ja-jpn",
"en-latn-us",
"zh-YUE-hk",
"en-X-A",
"x-fr-ch",
"X-fr-CH",
"en-GB-oed",
"i-default",
"sgn-BE-NL",
"zh-hakka",
"zh-Hakka",
"art-lojban",
"no-bok",
"zh-min-nan",
"sl-rozaj-biske",
] {
assert!(valid_language(ok), "{ok}");
}
for bad in [
"JA", "Ja", "ZH-HAKKA", "Zh-hakka", "jaja", "abcde", "x", "I-default", "i-Klingon", "en-gb-oed", "sgn-be-nl", "i-foo", "de-DE-1901-1901",
"en-u-co-phonebk-U-ca-buddhist", "en-a", "en-", "",
"JA",
"Ja",
"ZH-HAKKA",
"Zh-hakka",
"jaja",
"abcde",
"x",
"I-default",
"i-Klingon",
"en-gb-oed",
"sgn-be-nl",
"i-foo",
"de-DE-1901-1901",
"en-u-co-phonebk-U-ca-buddhist",
"en-a",
"en-",
"",
] {
assert!(!valid_language(bad), "{bad}");
}
crates/pds-lexicon/src/lib.rs+552−128
680 lines changed: not loaded until asked for.
crates/pds-lexicon/build.rs+11−3
@@ -16,16 +16,24 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
fn main() {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let root = manifest.join("../../spec/lexicons").canonicalize().expect("spec/lexicons");
let root = manifest
.join("../../spec/lexicons")
.canonicalize()
.expect("spec/lexicons");
println!("cargo:rerun-if-changed={}", root.display());
let mut files = Vec::new();
walk(&root, &mut files);
files.sort();
let mut src = String::from("/// Every lexicon under `spec/lexicons`, as its JSON text, in path order.\npub static LEXICONS: &[&str] = &[\n");
let mut src = String::from(
"/// Every lexicon under `spec/lexicons`, as its JSON text, in path order.\npub static LEXICONS: &[&str] = &[\n",
);
for f in &files {
// Directories are watched by their mtime, which a changed file does not touch.
println!("cargo:rerun-if-changed={}", f.display());
src.push_str(&format!(" include_str!({:?}),\n", f.display().to_string()));
src.push_str(&format!(
" include_str!({:?}),\n",
f.display().to_string()
));
}
src.push_str("];\n");
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("lexicons.rs");
crates/pds-repo/src/data.rs+161−35
@@ -82,7 +82,12 @@ pub fn cid_string(cid: &[u8]) -> String {
pub fn parse_cid(s: &str) -> Option<Vec<u8>> {
let rest = s.strip_prefix('b')?;
let bytes = base32_decode(rest)?;
if bytes.len() == 36 && bytes[0] == 1 && (bytes[1] == 0x71 || bytes[1] == 0x55) && bytes[2] == 0x12 && bytes[3] == 0x20 {
if bytes.len() == 36
&& bytes[0] == 1
&& (bytes[1] == 0x71 || bytes[1] == 0x55)
&& bytes[2] == 0x12
&& bytes[3] == 0x20
{
Some(bytes)
} else {
None
@@ -94,7 +99,10 @@ pub fn parse_cid(s: &str) -> Option<Vec<u8>> {
/// lower-case base32 whose multihash is as long as it says.
pub fn valid_cid_string(s: &str) -> bool {
if s.starts_with("Qm") {
return s.len() == 46 && bs58::decode(s).into_vec().is_ok_and(|b| b.len() == 34 && b[..2] == [0x12, 0x20]);
return s.len() == 46
&& bs58::decode(s)
.into_vec()
.is_ok_and(|b| b.len() == 34 && b[..2] == [0x12, 0x20]);
}
fn varint(rest: &mut &[u8]) -> Option<u64> {
let mut n = 0;
@@ -108,7 +116,9 @@ pub fn valid_cid_string(s: &str) -> bool {
}
None
}
let Some(bytes) = s.strip_prefix('b').and_then(base32_decode) else { return false };
let Some(bytes) = s.strip_prefix('b').and_then(base32_decode) else {
return false;
};
let rest = &mut bytes.as_slice();
matches!((varint(rest), varint(rest), varint(rest), varint(rest)), (Some(1), Some(_), Some(_), Some(len)) if rest.len() as u64 == len)
}
@@ -187,7 +197,11 @@ fn enc(v: &V, out: &mut Vec<u8>) {
pub fn decode(data: &[u8]) -> Result<V, String> {
let mut pos = 0;
let v = dec(data, &mut pos, 0)?;
if pos == data.len() { Ok(v) } else { Err("bytes after the value".into()) }
if pos == data.len() {
Ok(v)
} else {
Err("bytes after the value".into())
}
}
/// Decode the DAG-CBOR value at the start of `data`; answers it and how many bytes it took.
@@ -198,7 +212,9 @@ pub fn decode_prefix(data: &[u8]) -> Result<(V, usize), String> {
}
fn take<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], String> {
let s = data.get(*pos..pos.saturating_add(n)).ok_or("the value is cut short")?;
let s = data
.get(*pos..pos.saturating_add(n))
.ok_or("the value is cut short")?;
*pos += n;
Ok(s)
}
@@ -211,7 +227,9 @@ fn dec(d: &[u8], pos: &mut usize, depth: usize) -> Result<V, String> {
let (major, info) = (first >> 5, first & 31);
let n = match info {
0..=23 => u64::from(info),
24..=27 => take(d, pos, 1 << (info - 24))?.iter().fold(0, |n, &b| (n << 8) | u64::from(b)),
24..=27 => take(d, pos, 1 << (info - 24))?
.iter()
.fold(0, |n, &b| (n << 8) | u64::from(b)),
_ => return Err(format!("unsupported CBOR head {first:#x}")),
};
let int = || i64::try_from(n).map_err(|_| "integer out of range".to_string());
@@ -220,12 +238,21 @@ fn dec(d: &[u8], pos: &mut usize, depth: usize) -> Result<V, String> {
(0, _) => V::Int(int()?),
(1, _) => V::Int(-1 - int()?),
(2, _) => V::Bytes(take(d, pos, len()?)?.to_vec()),
(3, _) => V::Str(String::from_utf8(take(d, pos, len()?)?.to_vec()).map_err(|_| "a string that is not UTF-8")?),
(4, _) => V::Arr((0..n).map(|_| dec(d, pos, depth + 1)).collect::<Result<_, _>>()?),
(3, _) => V::Str(
String::from_utf8(take(d, pos, len()?)?.to_vec())
.map_err(|_| "a string that is not UTF-8")?,
),
(4, _) => V::Arr(
(0..n)
.map(|_| dec(d, pos, depth + 1))
.collect::<Result<_, _>>()?,
),
(5, _) => {
let mut m = Vec::new();
for _ in 0..n {
let V::Str(k) = dec(d, pos, depth + 1)? else { return Err("a map key that is not a string".into()) };
let V::Str(k) = dec(d, pos, depth + 1)? else {
return Err("a map key that is not a string".into());
};
m.push((k, dec(d, pos, depth + 1)?));
}
V::Map(m)
@@ -252,7 +279,11 @@ pub fn from_json(j: &Json) -> Result<V, String> {
// `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,
(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()),
@@ -268,7 +299,10 @@ pub fn from_json(j: &Json) -> Result<V, String> {
if o.len() != 1 {
return Err("$bytes object with other fields".into());
}
let bytes = b.as_str().and_then(|s| B64.decode(s).ok()).ok_or("invalid $bytes")?;
let bytes = b
.as_str()
.and_then(|s| B64.decode(s).ok())
.ok_or("invalid $bytes")?;
return Ok(V::Bytes(bytes));
}
let mut m = Vec::new();
@@ -284,8 +318,12 @@ pub fn from_json(j: &Json) -> Result<V, String> {
/// has one, is a non-empty string. An object within it may have a `$type` of
/// any value, or none (`spec/VALIDATION.md`): its lexicon, if checked, says.
pub fn record_from_json(j: &Json) -> Result<V, String> {
let Some(o) = j.as_object() else { return Err("record must be an object".into()) };
if o.get("$type").is_some_and(|t| t.as_str().is_none_or(str::is_empty)) {
let Some(o) = j.as_object() else {
return Err("record must be an object".into());
};
if o.get("$type")
.is_some_and(|t| t.as_str().is_none_or(str::is_empty))
{
return Err("$type must be a non-empty string".into());
}
from_json(j)
@@ -330,7 +368,10 @@ pub fn valid_nsid(s: &str) -> bool {
}
}
let n = name.as_bytes();
!n.is_empty() && n.len() <= 63 && n[0].is_ascii_alphabetic() && n.iter().all(|c| c.is_ascii_alphanumeric())
!n.is_empty()
&& n.len() <= 63
&& n[0].is_ascii_alphabetic()
&& n.iter().all(|c| c.is_ascii_alphanumeric())
}
pub fn valid_rkey(s: &str) -> bool {
@@ -338,17 +379,22 @@ pub fn valid_rkey(s: &str) -> bool {
&& s.len() <= 512
&& s != "."
&& s != ".."
&& s.bytes().all(|c| c.is_ascii_alphanumeric() || b".-_:~".contains(&c))
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b".-_:~".contains(&c))
}
/// Whether `s` is a DID: `did:`, a lowercase method, then its identifier (`atproto/did.md`).
pub fn valid_did(s: &str) -> bool {
let Some((method, id)) = s.strip_prefix("did:").and_then(|r| r.split_once(':')) else { return false };
let Some((method, id)) = s.strip_prefix("did:").and_then(|r| r.split_once(':')) else {
return false;
};
s.len() <= 2048
&& !method.is_empty()
&& method.bytes().all(|c| c.is_ascii_lowercase())
&& !id.is_empty()
&& id.bytes().all(|c| c.is_ascii_alphanumeric() || b"._:%-".contains(&c))
&& id
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._:%-".contains(&c))
&& !id.ends_with([':', '%'])
}
@@ -362,7 +408,13 @@ pub fn valid_handle(s: &str) -> bool {
&& b[b.len() - 1].is_ascii_alphanumeric()
&& b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
};
s.len() <= 253 && s.split('.').count() >= 2 && s.split('.').all(label) && !s.rsplit('.').next().is_some_and(|l| l.starts_with(|c: char| c.is_ascii_digit()))
s.len() <= 253
&& s.split('.').count() >= 2
&& s.split('.').all(label)
&& !s
.rsplit('.')
.next()
.is_some_and(|l| l.starts_with(|c: char| c.is_ascii_digit()))
}
/// Whether `s` is an at-identifier: a DID or a handle.
@@ -400,7 +452,13 @@ pub fn civil_from_days(days: i64) -> (i64, i64, i64) {
pub fn datetime_string(ms: i64) -> String {
let (days, rem) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000));
let (year, month, day) = civil_from_days(days);
format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3_600_000, rem / 60_000 % 60, rem / 1000 % 60, rem % 1000)
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
rem / 3_600_000,
rem / 60_000 % 60,
rem / 1000 % 60,
rem % 1000
)
}
/// A datetime as `atproto/lexicon.md` defines the format, as milliseconds
@@ -411,9 +469,17 @@ pub fn datetime_millis(s: &str) -> Option<i64> {
let b = s.as_bytes();
let digits = |r: std::ops::Range<usize>| -> Option<i64> {
let part = b.get(r)?;
part.iter().all(u8::is_ascii_digit).then(|| part.iter().fold(0, |n, c| n * 10 + i64::from(c - b'0')))
part.iter()
.all(u8::is_ascii_digit)
.then(|| part.iter().fold(0, |n, c| n * 10 + i64::from(c - b'0')))
};
if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
if b.len() < 20
|| b[4] != b'-'
|| b[7] != b'-'
|| b[10] != b'T'
|| b[13] != b':'
|| b[16] != b':'
{
return None;
}
let (year, month, day) = (digits(0..4)?, digits(5..7)?, digits(8..10)?);
@@ -429,7 +495,9 @@ pub fn datetime_millis(s: &str) -> Option<i64> {
if i == start || i - start > 20 {
return None;
}
millis = (start..start + 3).map(|j| if j < i { i64::from(b[j] - b'0') } else { 0 }).fold(0, |n, d| n * 10 + d);
millis = (start..start + 3)
.map(|j| if j < i { i64::from(b[j] - b'0') } else { 0 })
.fold(0, |n, d| n * 10 + d);
}
let offset = match &b[i..] {
b"Z" => 0,
@@ -443,8 +511,27 @@ pub fn datetime_millis(s: &str) -> Option<i64> {
_ => return None,
};
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let month_days = [31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if !(1..=12).contains(&month) || day < 1 || day > month_days[(month - 1) as usize] || hour > 23 || minute > 59 || second > 59 {
let month_days = [
31,
if leap { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
if !(1..=12).contains(&month)
|| day < 1
|| day > month_days[(month - 1) as usize]
|| hour > 23
|| minute > 59
|| second > 59
{
return None;
}
let local = ((days_from_civil(year, month, day) * 24 + hour) * 60 + minute) * 60 + second;
@@ -464,12 +551,19 @@ mod tests {
#[test]
fn fixtures() {
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/data-model/data-model-fixtures.json")).unwrap();
let text = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../spec/interop/data-model/data-model-fixtures.json"
))
.unwrap();
let fixtures: Vec<Json> = serde_json::from_str(&text).unwrap();
for f in fixtures {
let v = from_json(&f["json"]).unwrap();
let cbor = encode(&v);
assert_eq!(B64.encode(&cbor), f["cbor_base64"].as_str().unwrap().trim_end_matches('='));
assert_eq!(
B64.encode(&cbor),
f["cbor_base64"].as_str().unwrap().trim_end_matches('=')
);
assert_eq!(cid_string(&cid_of(0x71, &cbor)), f["cid"].as_str().unwrap());
assert_eq!(to_json(&v), f["json"]);
assert_eq!(encode(&decode(&cbor).unwrap()), cbor);
@@ -479,12 +573,29 @@ mod tests {
#[test]
fn syntax() {
assert!(valid_did("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa") && valid_did("did:web:example.com"));
assert!(!valid_did("did:PLC:abc") && !valid_did("did:plc:") && !valid_did("plc:abc") && !valid_did("did:plc:abc:"));
assert!(
!valid_did("did:PLC:abc")
&& !valid_did("did:plc:")
&& !valid_did("plc:abc")
&& !valid_did("did:plc:abc:")
);
assert!(valid_handle("alice.test") && valid_handle("a.b-c.example"));
assert!(!valid_handle("alice") && !valid_handle("alice.3com") && !valid_handle("-a.test") && !valid_handle("a..test"));
assert!(
!valid_handle("alice")
&& !valid_handle("alice.3com")
&& !valid_handle("-a.test")
&& !valid_handle("a..test")
);
let cid = cid_string(&cid_of(0x71, b"x"));
assert!(valid_cid_string(&cid) && valid_cid_string("QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG"));
assert!(!valid_cid_string(&cid[..cid.len() - 2]) && !valid_cid_string("bafy") && !valid_cid_string("not a cid"));
assert!(
valid_cid_string(&cid)
&& valid_cid_string("QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG")
);
assert!(
!valid_cid_string(&cid[..cid.len() - 2])
&& !valid_cid_string("bafy")
&& !valid_cid_string("not a cid")
);
}
#[test]
@@ -530,20 +641,32 @@ mod tests {
assert!(!valid_datetime(s), "{s}");
}
assert_eq!(datetime_millis("1970-01-01T01:00:00.5+01:00"), Some(500));
assert_eq!(datetime_string(datetime_millis("2026-11-09T12:34:56.789Z").unwrap()), "2026-11-09T12:34:56.789Z");
assert_eq!(
datetime_string(datetime_millis("2026-11-09T12:34:56.789Z").unwrap()),
"2026-11-09T12:34:56.789Z"
);
}
/// The data model's invalid values are refused, but for the maps that
/// look like a blob or a link and are kept as they are (`spec/BLOBS.md`).
#[test]
fn invalid() {
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/data-model/data-model-invalid.json")).unwrap();
let text = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../spec/interop/data-model/data-model-invalid.json"
))
.unwrap();
let cases: Vec<Json> = serde_json::from_str(&text).unwrap();
let kept = ["blob with string size", "blob with missing key", "link with extra fields"];
let kept = [
"blob with string size",
"blob with missing key",
"link with extra fields",
];
for c in cases {
let j = &c["json"];
let note = c["note"].as_str().unwrap();
let (x, parse): (&Json, fn(&Json) -> Result<V, String>) = match (j.get("rcrd"), j.get("blb").or(j.get("lnk"))) {
type Parse = fn(&Json) -> Result<V, String>;
let (x, parse): (&Json, Parse) = match (j.get("rcrd"), j.get("blb").or(j.get("lnk"))) {
(Some(r), _) => (r, record_from_json),
(None, Some(x)) => (x, from_json),
(None, None) => continue,
@@ -571,6 +694,9 @@ mod tests {
#[test]
fn base32() {
assert_eq!(base32_decode(&base32_encode(b"hello world")).unwrap(), b"hello world");
assert_eq!(
base32_decode(&base32_encode(b"hello world")).unwrap(),
b"hello world"
);
}
}
crates/pds-repo/src/lib.rs+379−80
459 lines changed: not loaded until asked for.
crates/pds-repo/src/mst.rs+179−36
@@ -63,7 +63,11 @@ impl Node {
/// The subtree in gap `i`: before entry 0 for `i == 0`, else after entry `i - 1`.
fn gap(&self, i: usize) -> Option<&Node> {
if i == 0 { self.left.as_deref() } else { self.entries[i - 1].sub.as_deref() }
if i == 0 {
self.left.as_deref()
} else {
self.entries[i - 1].sub.as_deref()
}
}
/// This node and the chain of nodes down its left (or right) edge.
@@ -84,7 +88,10 @@ impl Node {
let at = x.entries.partition_point(|e| e.key.as_slice() < key);
let found = x.entries.get(at).is_some_and(|e| e.key == key);
// The subtrees beside the key's position: undoing may merge or split them.
let (lo, hi) = (at.saturating_sub(1), (at + if found { 2 } else { 1 }).min(x.entries.len()));
let (lo, hi) = (
at.saturating_sub(1),
(at + if found { 2 } else { 1 }).min(x.entries.len()),
);
for g in lo..=hi {
if let Some(s) = x.gap(g) {
s.spine(true, out);
@@ -120,9 +127,19 @@ impl Node {
/// The tree nodes a commit's `#commit` event carries, in CID order: those of
/// `after` that `before` lacks (all of them for a first commit, which has no
/// `before`), and the context of each key the commit wrote.
pub fn event_nodes<'a, 'k>(before: Option<&Node>, after: &'a Node, keys: impl IntoIterator<Item = &'k [u8]>) -> Vec<&'a Node> {
let old: HashSet<&[u8]> = before.map(|b| b.nodes().into_iter().map(|n| n.cid.as_slice()).collect()).unwrap_or_default();
let mut out: Vec<&Node> = after.nodes().into_iter().filter(|n| !old.contains(n.cid.as_slice())).collect();
pub fn event_nodes<'a, 'k>(
before: Option<&Node>,
after: &'a Node,
keys: impl IntoIterator<Item = &'k [u8]>,
) -> Vec<&'a Node> {
let old: HashSet<&[u8]> = before
.map(|b| b.nodes().into_iter().map(|n| n.cid.as_slice()).collect())
.unwrap_or_default();
let mut out: Vec<&Node> = after
.nodes()
.into_iter()
.filter(|n| !old.contains(n.cid.as_slice()))
.collect();
for k in keys {
after.context(k, &mut out);
}
@@ -139,8 +156,16 @@ pub fn build_tree(entries: &[(Vec<u8>, Vec<u8>)]) -> Node {
match node(entries, &depths, level) {
Some(r) => *r,
None => {
let bytes = encode(&V::Map(vec![("e".into(), V::Arr(vec![])), ("l".into(), V::Null)]));
Node { cid: cid_of(0x71, &bytes), bytes, left: None, entries: vec![] }
let bytes = encode(&V::Map(vec![
("e".into(), V::Arr(vec![])),
("l".into(), V::Null),
]));
Node {
cid: cid_of(0x71, &bytes),
bytes,
left: None,
entries: vec![],
}
}
}
}
@@ -151,7 +176,11 @@ fn node(entries: &[(Vec<u8>, Vec<u8>)], depths: &[usize], level: usize) -> Optio
}
let here: Vec<usize> = (0..entries.len()).filter(|&i| depths[i] == level).collect();
let sub = |from: usize, to: usize| {
if level == 0 { None } else { node(&entries[from..to], &depths[from..to], level - 1) }
if level == 0 {
None
} else {
node(&entries[from..to], &depths[from..to], level - 1)
}
};
let left = sub(0, here.first().copied().unwrap_or(entries.len()));
let mut list = Vec::new();
@@ -161,21 +190,39 @@ fn node(entries: &[(Vec<u8>, Vec<u8>)], depths: &[usize], level: usize) -> Optio
let end = here.get(n + 1).copied().unwrap_or(entries.len());
let tree = sub(i + 1, end);
let key = &entries[i].0;
let p = prev.iter().zip(key.iter()).take_while(|(a, b)| a == b).count();
let p = prev
.iter()
.zip(key.iter())
.take_while(|(a, b)| a == b)
.count();
list.push(V::Map(vec![
("p".into(), V::Int(p as i64)),
("k".into(), V::Bytes(key[p..].to_vec())),
("v".into(), V::Link(entries[i].1.clone())),
("t".into(), tree.as_ref().map_or(V::Null, |t| V::Link(t.cid.clone()))),
(
"t".into(),
tree.as_ref().map_or(V::Null, |t| V::Link(t.cid.clone())),
),
]));
kids.push(Entry { key: key.clone(), sub: tree });
kids.push(Entry {
key: key.clone(),
sub: tree,
});
prev = key;
}
let bytes = encode(&V::Map(vec![
("l".into(), left.as_ref().map_or(V::Null, |t| V::Link(t.cid.clone()))),
(
"l".into(),
left.as_ref().map_or(V::Null, |t| V::Link(t.cid.clone())),
),
("e".into(), V::Arr(list)),
]));
Some(Box::new(Node { cid: cid_of(0x71, &bytes), bytes, left, entries: kids }))
Some(Box::new(Node {
cid: cid_of(0x71, &bytes),
bytes,
left,
entries: kids,
}))
}
/// The `(key, value cid)` entries of a tree read from its blocks, in key
@@ -193,29 +240,48 @@ pub fn walk<'a>(root: &[u8], block: impl Fn(&[u8]) -> Option<&'a [u8]>) -> Resul
Ok(out)
}
fn visit<'a>(cid: &[u8], block: &impl Fn(&[u8]) -> Option<&'a [u8]>, out: &mut Walked) -> Result<(), String> {
fn visit<'a>(
cid: &[u8],
block: &impl Fn(&[u8]) -> Option<&'a [u8]>,
out: &mut Walked,
) -> Result<(), String> {
let bad = |why: &str| format!("tree node {}: {why}", cid_string(cid));
let bytes = block(cid).ok_or_else(|| bad("missing"))?;
out.1.push(cid.to_vec());
let V::Map(mut m) = decode(bytes).map_err(|e| bad(&e))? else { return Err(bad("not a map")) };
let V::Map(mut m) = decode(bytes).map_err(|e| bad(&e))? else {
return Err(bad("not a map"));
};
let link = |v: Option<V>| match v {
Some(V::Null) => Ok(None),
Some(V::Link(l)) => Ok(Some(l)),
_ => Err(bad("a subtree that is no link or null")),
};
let (l, e) = (take(&mut m, "l"), take(&mut m, "e"));
let (Some(V::Arr(entries)), true) = (e, m.is_empty()) else { return Err(bad("not exactly l and a list e")) };
let (Some(V::Arr(entries)), true) = (e, m.is_empty()) else {
return Err(bad("not exactly l and a list e"));
};
if let Some(l) = link(l)? {
visit(&l, block, out)?;
}
let mut prev: Vec<u8> = Vec::new();
for e in entries {
let V::Map(mut e) = e else { return Err(bad("an entry not a map")) };
let (p, k, v, t) = (take(&mut e, "p"), take(&mut e, "k"), take(&mut e, "v"), take(&mut e, "t"));
let (Some(V::Int(p)), Some(V::Bytes(k)), Some(V::Link(v)), true) = (p, k, v, e.is_empty()) else {
let V::Map(mut e) = e else {
return Err(bad("an entry not a map"));
};
let (p, k, v, t) = (
take(&mut e, "p"),
take(&mut e, "k"),
take(&mut e, "v"),
take(&mut e, "t"),
);
let (Some(V::Int(p)), Some(V::Bytes(k)), Some(V::Link(v)), true) = (p, k, v, e.is_empty())
else {
return Err(bad("an entry not exactly p, k, v and t"));
};
let p = usize::try_from(p).ok().filter(|p| *p <= prev.len()).ok_or_else(|| bad("a prefix longer than the key before"))?;
let p = usize::try_from(p)
.ok()
.filter(|p| *p <= prev.len())
.ok_or_else(|| bad("a prefix longer than the key before"))?;
prev.truncate(p);
prev.extend(k);
if out.0.last().is_some_and(|(last, _)| *last >= prev) {
@@ -241,10 +307,19 @@ mod tests {
#[test]
fn heights() {
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/mst/key_heights.json")).unwrap();
let text = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../spec/interop/mst/key_heights.json"
))
.unwrap();
let cases: Vec<serde_json::Value> = serde_json::from_str(&text).unwrap();
for c in cases {
assert_eq!(depth(c["key"].as_str().unwrap().as_bytes()), c["height"].as_u64().unwrap() as usize, "{}", c["key"]);
assert_eq!(
depth(c["key"].as_str().unwrap().as_bytes()),
c["height"].as_u64().unwrap() as usize,
"{}",
c["key"]
);
}
}
@@ -253,27 +328,67 @@ mod tests {
#[test]
fn commit_proofs() {
use crate::data::{cid_string, parse_cid};
let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/firehose/commit-proof-fixtures.json")).unwrap();
let text = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../spec/interop/firehose/commit-proof-fixtures.json"
))
.unwrap();
let cases: Vec<serde_json::Value> = serde_json::from_str(&text).unwrap();
assert!(!cases.is_empty());
for c in cases {
let leaf = parse_cid(c["leafValue"].as_str().unwrap()).unwrap();
let strs = |k: &str| c[k].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect::<Vec<_>>();
let strs = |k: &str| {
c[k].as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap().to_string())
.collect::<Vec<_>>()
};
let (keys, adds, dels) = (strs("keys"), strs("adds"), strs("dels"));
let tree = |ks: Vec<&String>| {
let mut e: Vec<(Vec<u8>, Vec<u8>)> = ks.into_iter().map(|k| (k.as_bytes().to_vec(), leaf.clone())).collect();
let mut e: Vec<(Vec<u8>, Vec<u8>)> = ks
.into_iter()
.map(|k| (k.as_bytes().to_vec(), leaf.clone()))
.collect();
e.sort();
build_tree(&e)
};
let before = tree(keys.iter().collect());
let after = tree(keys.iter().filter(|k| !dels.contains(k)).chain(&adds).collect());
assert_eq!(cid_string(&before.cid), c["rootBeforeCommit"], "{}", c["comment"]);
assert_eq!(cid_string(&after.cid), c["rootAfterCommit"], "{}", c["comment"]);
let carried = event_nodes(Some(&before), &after, adds.iter().chain(&dels).map(|k| k.as_bytes()));
assert!(carried.windows(2).all(|w| w[0].cid < w[1].cid), "{}: in CID order", c["comment"]);
let after = tree(
keys.iter()
.filter(|k| !dels.contains(k))
.chain(&adds)
.collect(),
);
assert_eq!(
cid_string(&before.cid),
c["rootBeforeCommit"],
"{}",
c["comment"]
);
assert_eq!(
cid_string(&after.cid),
c["rootAfterCommit"],
"{}",
c["comment"]
);
let carried = event_nodes(
Some(&before),
&after,
adds.iter().chain(&dels).map(|k| k.as_bytes()),
);
assert!(
carried.windows(2).all(|w| w[0].cid < w[1].cid),
"{}: in CID order",
c["comment"]
);
let carried: HashSet<String> = carried.iter().map(|n| cid_string(&n.cid)).collect();
for b in strs("blocksInProof") {
assert!(carried.contains(&b), "{}: {b} missing from the event", c["comment"]);
assert!(
carried.contains(&b),
"{}: {b} missing from the event",
c["comment"]
);
}
}
}
@@ -284,10 +399,21 @@ mod tests {
fn walks() {
use std::collections::HashMap;
for n in [0usize, 1, 40, 1000] {
let mut entries: Vec<(Vec<u8>, Vec<u8>)> = (0..n).map(|i| (format!("a.b.c/k{i}").into_bytes(), cid_of(0x71, &i.to_le_bytes()))).collect();
let mut entries: Vec<(Vec<u8>, Vec<u8>)> = (0..n)
.map(|i| {
(
format!("a.b.c/k{i}").into_bytes(),
cid_of(0x71, &i.to_le_bytes()),
)
})
.collect();
entries.sort();
let tree = build_tree(&entries);
let blocks: HashMap<Vec<u8>, Vec<u8>> = tree.nodes().into_iter().map(|x| (x.cid.clone(), x.bytes.clone())).collect();
let blocks: HashMap<Vec<u8>, Vec<u8>> = tree
.nodes()
.into_iter()
.map(|x| (x.cid.clone(), x.bytes.clone()))
.collect();
let (got, nodes) = walk(&tree.cid, |c| blocks.get(c).map(Vec::as_slice)).unwrap();
assert_eq!(got, entries);
let mut want: Vec<Vec<u8>> = blocks.keys().cloned().collect();
@@ -297,13 +423,30 @@ mod tests {
assert_eq!(nodes, want);
if n > 1 {
let leaf = tree.nodes()[0].cid.clone();
assert!(walk(&tree.cid, |c| if *c == leaf[..] { None } else { blocks.get(c).map(Vec::as_slice) }).is_err());
assert!(
walk(&tree.cid, |c| if *c == leaf[..] {
None
} else {
blocks.get(c).map(Vec::as_slice)
})
.is_err()
);
}
}
// Two keys swapped in one node.
let (a, b) = (b"a.b.c/2".to_vec(), b"a.b.c/1".to_vec());
let e = |k: &[u8]| V::Map(vec![("p".into(), V::Int(0)), ("k".into(), V::Bytes(k.to_vec())), ("v".into(), V::Link(cid_of(0x71, b"x"))), ("t".into(), V::Null)]);
let bytes = encode(&V::Map(vec![("l".into(), V::Null), ("e".into(), V::Arr(vec![e(&a), e(&b)]))]));
let e = |k: &[u8]| {
V::Map(vec![
("p".into(), V::Int(0)),
("k".into(), V::Bytes(k.to_vec())),
("v".into(), V::Link(cid_of(0x71, b"x"))),
("t".into(), V::Null),
])
};
let bytes = encode(&V::Map(vec![
("l".into(), V::Null),
("e".into(), V::Arr(vec![e(&a), e(&b)])),
]));
let cid = cid_of(0x71, &bytes);
assert!(walk(&cid, |c| (*c == cid[..]).then_some(bytes.as_slice())).is_err());
}
crates/pds-server/src/lifecycle/tests.rs+1247−217
1464 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/clients/assertion.rs+85−21
@@ -19,7 +19,8 @@ const JTI_LIFE: u64 = 120;
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",
"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> {
@@ -51,7 +52,11 @@ fn client_key(k: &Map<String, Json>) -> bool {
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))
!ops.is_empty()
&& ops
.iter()
.enumerate()
.all(|(i, o)| fits(o) && !ops[..i].contains(o))
})
}
Some(_) => false,
@@ -61,12 +66,21 @@ fn client_key(k: &Map<String, Json>) -> bool {
/// 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()
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())
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
@@ -81,7 +95,9 @@ fn fit(k: &Map<String, Json>, alg: &str) -> bool {
&& 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"))
&& 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`,
@@ -107,7 +123,9 @@ impl Refused {
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"),
Refused::Replayed => {
refuse(400, "invalid_grant", "The client assertion was used before")
}
}
}
}
@@ -115,7 +133,12 @@ impl Refused {
/// 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'_'))
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
@@ -134,7 +157,9 @@ pub(in super::super) fn authenticate(
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")));
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()));
@@ -142,19 +167,36 @@ pub(in super::super) fn authenticate(
// 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 (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") };
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");
}
@@ -170,22 +212,37 @@ pub(in super::super) fn authenticate(
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 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") };
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)) {
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)) {
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) {
match svc.replay.claim(
&format!("client assertion {client_id}"),
&jti,
now,
now + JTI_LIFE,
) {
Some(e) => spent.push(e),
None => return Err(Refused::Replayed),
}
@@ -247,7 +304,14 @@ mod tests {
#[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"] {
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.rs+206−39
@@ -24,21 +24,35 @@ const GRANT_TYPES: &[&str] = &[
"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"];
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))
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")
!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.
@@ -57,7 +71,9 @@ pub(super) fn client_id(id: &str) -> Result<Url, &'static str> {
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) };
let Some(Host::Domain(host)) = u.host() else {
return Err(META);
};
if !domain_ok(host) || authority.contains(':') || u.port().is_some() {
return Err(META);
}
@@ -95,21 +111,37 @@ fn form(uri: &str) -> Option<Form> {
return Some(Form::Https(u));
}
if uri.starts_with("http://") {
return Url::parse(uri).ok().filter(client::loopback).map(Form::Loopback);
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 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("."));
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())
!local.is_empty()
&& !s.contains(char::is_whitespace)
&& !domain.contains('@')
&& domain.split('.').count() >= 2
&& domain.split('.').all(|l| !l.is_empty())
})
}
@@ -133,7 +165,10 @@ pub(super) struct Taken {
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> {
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());
@@ -150,49 +185,150 @@ pub(super) fn check(id: &str, url: &Url, doc: &Map<String, Json>) -> Result<Take
};
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 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 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 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 = 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();
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)?;
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(
"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 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"] {
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)));
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<_>>() }));
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();
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.
@@ -202,18 +338,28 @@ pub(super) fn check(id: &str, url: &Url, doc: &Map<String, Json>) -> Result<Take
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))) {
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)) {
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)) {
if grants.iter().enumerate().any(|(i, g)| {
grants[..i].contains(g) || !["authorization_code", "refresh_token"].contains(g)
}) {
return Err(REFUSED);
}
// 6-7.
@@ -223,17 +369,27 @@ pub(super) fn check(id: &str, url: &Url, doc: &Map<String, Json>) -> Result<Take
// 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,
"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)) {
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())) {
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.
@@ -244,7 +400,11 @@ pub(super) fn check(id: &str, url: &Url, doc: &Map<String, Json>) -> Result<Take
// 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::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)),
};
@@ -326,7 +486,14 @@ mod tests {
#[test]
fn local_names() {
for n in ["harness", "a.test", "a.LOCAL", "a.localhost", "a.invalid", "a.example"] {
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"] {
crates/pds-server/src/oauth/clients/fetch.rs+69−14
@@ -27,7 +27,9 @@ impl ClientFetch {
/// 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(v) if !v.trim().is_empty() => ClientFetch::parse(&v)
.map(Some)
.map_err(|e| format!("{VAR}: {e}")),
_ => Ok(None),
}
}
@@ -36,19 +38,37 @@ impl ClientFetch {
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 (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")),
_ => {
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"));
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 /"));
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()));
}
@@ -91,18 +111,43 @@ impl Fetcher {
/// takes it; else why not. An origin the development fetch lists is
/// fetched from its base URL instead; any other only over https. Either
/// goes out through `outbound`, and its SSRF protection.
pub async fn get(&self, outbound: &Outbound, url: &Url, kind: Kind) -> Result<Map<String, Json>, String> {
pub async fn get(
&self,
outbound: &Outbound,
url: &Url,
kind: Kind,
) -> Result<Map<String, Json>, String> {
let target = match self.dev.as_ref().and_then(|d| d.target(url)) {
Some(mapped) => mapped,
None if url.scheme() != "https" => return Err(format!("{url} is not https")),
None => url.to_string(),
};
let got = outbound.fetch_limited(crate::ops::Target::Client, outbound.client().get(&target).header("accept", "application/json"), MAX_BODY, self.timeout).await?;
let got = outbound
.fetch_limited(
crate::ops::Target::Client,
outbound
.client()
.get(&target)
.header("accept", "application/json"),
MAX_BODY,
self.timeout,
)
.await?;
if got.status != 200 {
return Err(format!("{url} answered {}", got.status));
}
let essence = got.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");
let essence = got.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"));
}
@@ -121,9 +166,19 @@ mod tests {
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);
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",
crates/pds-server/src/oauth/clients/silent.rs+46−11
crates/pds-server/src/oauth/clients/tests.rs+1424−264
A large diff, not shown.
crates/pds-server/src/oauth/client.rs+62−12
crates/pds-server/src/oauth/clients.rs+34−8
crates/pds-server/src/oauth/dpop.rs+95−25
crates/pds-server/src/oauth/page.rs+475−99
574 lines changed: not loaded until asked for.
crates/pds-server/src/oauth/scope.rs+99−16
crates/pds-server/src/oauth/tests.rs+2037−359
A large diff, not shown.
crates/pds-server/src/ops/metrics.rs+142−28
crates/pds-server/src/ops/trace.rs+209−41
crates/pds-server/src/scopes/tests.rs+692−107
799 lines changed: not loaded until asked for.
crates/pds-server/src/space_credentials/attestation.rs+119−26
crates/pds-server/src/space_credentials/jwt.rs+167−46
crates/pds-server/src/space_credentials/tests.rs+1072−204
1276 lines changed: not loaded until asked for.
crates/pds-server/src/space_notify/tests.rs+880−174
1054 lines changed: not loaded until asked for.
crates/pds-server/src/blobs.rs+1059−226
A large diff, not shown.
crates/pds-server/src/checkpoint.rs+814−166
980 lines changed: not loaded until asked for.
crates/pds-server/src/compact.rs+430−72
502 lines changed: not loaded until asked for.
crates/pds-server/src/email.rs+1184−239
A large diff, not shown.
crates/pds-server/src/events.rs+227−46
crates/pds-server/src/federation.rs+415−80
495 lines changed: not loaded until asked for.
crates/pds-server/src/identity.rs+574−122
696 lines changed: not loaded until asked for.
crates/pds-server/src/invites.rs+332−71
403 lines changed: not loaded until asked for.
crates/pds-server/src/lib.rs+331−77
408 lines changed: not loaded until asked for.
crates/pds-server/src/lifecycle.rs+297−80
crates/pds-server/src/limits.rs+691−164
855 lines changed: not loaded until asked for.
crates/pds-server/src/log.rs+1605−306
A large diff, not shown.
crates/pds-server/src/mcp.rs+294−58
crates/pds-server/src/oauth.rs+601−129
730 lines changed: not loaded until asked for.
crates/pds-server/src/ops.rs+120−24
crates/pds-server/src/outbound.rs+412−83
495 lines changed: not loaded until asked for.
crates/pds-server/src/plc.rs+270−64
crates/pds-server/src/preferences.rs+130−28
crates/pds-server/src/proxy.rs+1444−256
A large diff, not shown.
crates/pds-server/src/read_after_write.rs+228−51
crates/pds-server/src/replay.rs+26−6
crates/pds-server/src/repo.rs+414−85
499 lines changed: not loaded until asked for.
crates/pds-server/src/scopes.rs+289−69
crates/pds-server/src/server.rs+473−95
568 lines changed: not loaded until asked for.
crates/pds-server/src/sessions.rs+736−157
893 lines changed: not loaded until asked for.
crates/pds-server/src/single_use.rs+37−10
crates/pds-server/src/space_authority.rs+1545−277
A large diff, not shown.
crates/pds-server/src/space_authz.rs+447−93
540 lines changed: not loaded until asked for.
crates/pds-server/src/space_credentials.rs+196−52
crates/pds-server/src/space_notify.rs+437−87
524 lines changed: not loaded until asked for.
crates/pds-server/src/space_repo.rs+2619−445
A large diff, not shown.
crates/pds-server/src/store.rs+72−15
crates/pds-server/src/sync.rs+71−14
crates/pds-server/src/validation.rs+451−82
533 lines changed: not loaded until asked for.
crates/pds-server/Cargo.toml+1−1
crates/pds-space/src/commit.rs+5−1
crates/pds-space/src/key.rs+39−15
crates/pds-space/src/lib.rs+2−0
crates/pds-space/src/lthash.rs+6−3
crates/pds-space/src/sf.rs+54−10
crates/pds-space/src/signature.rs+38−12
crates/pds-space/src/space_ref.rs+30−5
crates/pds-space/src/star.rs+69−18
crates/pds-space/tests/vectors.rs+120−24
crates/pds-store/src/generations.rs+297−67
crates/pds-store/src/lib.rs+124−24
harness/gates.mjs+14−5
Cargo.lock+238−73
Cargo.toml+3−3
deny.toml+1−0
Justfile+4−7
README.md+9−9