chadtmiller.com/monolith
An atproto PDS
0
0
Proxying to the AppView and other services, service auth, preferences, and records checked against their lexicons
crates/pds-lexicon/src/format.rsnew+300−0
| @@ -0,0 +1,300 @@ | ||
//! The lexicon string formats (`atproto/lexicon.md`), as `spec/VALIDATION.md` | ||
//! 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}; | ||
| ||
/// 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 { | ||
match format { | ||
"at-identifier" => valid_at_identifier(s), | ||
"did" => valid_did(s), | ||
"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" => valid_at_uri(s), | ||
"uri" => valid_uri(s), | ||
"datetime" => valid_datetime(s), | ||
"language" => valid_language(s), | ||
_ => true, | ||
} | ||
} | ||
| ||
/// An AT URI as lexicons use them: `at://`, a DID or handle, then | ||
/// 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 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()) | ||
}) | ||
} | ||
| ||
/// 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}') | ||
} | ||
| ||
/// 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) { | ||
return false; | ||
} | ||
// `[^\s/]` after the scheme, or after a `//` that follows it. | ||
let after = |r: &str| r.chars().next().is_some_and(|c| c != '/'); | ||
after(rest) || rest.strip_prefix("//").is_some_and(after) | ||
} | ||
| ||
/// The days from 1970-01-01 to the first of `month` in `year`, proleptic Gregorian. | ||
fn days_from_civil(year: i64, month: i64) -> i64 { | ||
let y = if month <= 2 { year - 1 } else { year }; | ||
let era = y.div_euclid(400); | ||
let yoe = y - era * 400; | ||
let mp = (month + 9) % 12; | ||
let doy = (153 * mp + 2) / 5; | ||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; | ||
era * 146_097 + doe - 719_468 | ||
} | ||
| ||
/// The year of the day `days` after 1970-01-01, proleptic Gregorian. | ||
fn year_of(days: i64) -> i64 { | ||
let z = days + 719_468; | ||
let era = z.div_euclid(146_097); | ||
let doe = z - era * 146_097; | ||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; | ||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); | ||
let mp = (5 * doy + 2) / 153; | ||
let month = if mp < 10 { mp + 3 } else { mp - 9 }; | ||
yoe + era * 400 + i64::from(month <= 2) | ||
} | ||
| ||
/// A datetime: `YYYY-MM-DDTHH:MM:SS`, an optional fraction, then `Z` or an | ||
/// offset `±HH:MM` other than `-00:00`; at most 64 characters, no leap | ||
/// second, the day held to 01–31 but not to its month, and its instant in | ||
/// UTC in the years 0000 to 9999. | ||
pub fn valid_datetime(s: &str) -> bool { | ||
let b = s.as_bytes(); | ||
if b.len() > 64 || b.len() < 20 || s.ends_with("-00:00") { | ||
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'))) | ||
}; | ||
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 { | ||
return false; | ||
}; | ||
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 59 { | ||
return false; | ||
} | ||
let mut rest = &b[19..]; | ||
if let Some(frac) = rest.strip_prefix(b".") { | ||
let digits = frac.iter().take_while(|c| c.is_ascii_digit()).count(); | ||
if digits == 0 { | ||
return false; | ||
} | ||
rest = &frac[digits..]; | ||
} | ||
let offset = match *rest { | ||
[b'Z'] => 0, | ||
[sign @ (b'+' | b'-'), h1, h2, b':', m1, m2] => { | ||
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')); | ||
if h > 23 || m > 59 { | ||
return false; | ||
} | ||
if sign == b'+' { h * 60 + m } else { -(h * 60 + m) } | ||
} | ||
_ => return false, | ||
}; | ||
// The instant, in minutes since the epoch; a day past its month's end runs on into the next. | ||
let minutes = (days_from_civil(year, month) + day - 1) * 1440 + hour * 60 + minute - offset; | ||
(0..=9999).contains(&year_of(minutes.div_euclid(1440))) | ||
} | ||
| ||
/// 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", | ||
]; | ||
| ||
/// A `Language-Tag` of RFC 5646 §2.1's grammar, with no variant or | ||
/// extension singleton repeated, compared in any case (§4.1), as | ||
/// `spec/VALIDATION.md` says: a primary language subtag of exactly 2 or 3 | ||
/// lower-case letters, later subtags in any case, private use alone from | ||
/// `x` or `X`, and the irregular grandfathered tags exactly as written. | ||
pub fn valid_language(s: &str) -> bool { | ||
if IRREGULAR.contains(&s) { | ||
return true; | ||
} | ||
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()); | ||
// 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)); | ||
if private(0) { | ||
return true; | ||
} | ||
if !((2..=3).contains(&tags[0].len()) && tags[0].bytes().all(|c| c.is_ascii_lowercase())) { | ||
return false; | ||
} | ||
let mut i = 1; | ||
while i < n && i <= 3 && alpha(tags[i], 3..=3) { | ||
i += 1; | ||
} | ||
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()))) { | ||
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))) { | ||
let v = tags[i].to_ascii_lowercase(); | ||
if variants.contains(&v) { | ||
return false; | ||
} | ||
variants.push(v); | ||
i += 1; | ||
} | ||
let mut singletons: Vec<u8> = Vec::new(); | ||
while i < n && alnum(tags[i], 1..=1) && !tags[i].eq_ignore_ascii_case("x") { | ||
let c = tags[i].as_bytes()[0].to_ascii_lowercase(); | ||
if singletons.contains(&c) { | ||
return false; | ||
} | ||
singletons.push(c); | ||
i += 1; | ||
let start = i; | ||
while i < n && alnum(tags[i], 2..=8) { | ||
i += 1; | ||
} | ||
if i == start { | ||
return false; | ||
} | ||
} | ||
i == n || private(i) | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
/// Each `<format>_syntax_valid.txt` string is valid, and each | ||
/// `*_syntax_invalid.txt` and `*_parse_invalid.txt` one is not, but where | ||
/// `spec/VALIDATION.md` says the reference differs. | ||
#[test] | ||
fn interop_syntax_vectors() { | ||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/syntax"); | ||
// The reference takes a CIDv0, refuses a CIDv1 in any base but | ||
// base32, and takes a URI of any length matching its pattern. | ||
let differs = [ | ||
("cid", "QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR"), | ||
("cid", "zdj7WWeQ43G6JJvLWQWZpyHuAMq6uYWRjkBXFad11vE2LHhQ7"), | ||
("cid", "mBcDxtdWx0aWhhc2g+"), | ||
("cid", "z7x3CtScH765HvShXT"), | ||
("cid", "zdj7WhuEjrB52m1BisYCtmjH1hSKa7yZ3jEZ9JcXaFRD51wVz"), | ||
("cid", "7134036155352661643226414134664076"), | ||
("cid", "f017012202c5f688262e0ece8569aa6f94d60aad55ca8d9d83734e4a7430d0cff6588ec2b"), | ||
("uri", "content-type:text/plan"), | ||
("uri", "microsoft.windows.camera:thing"), | ||
]; | ||
let formats = [ | ||
("atidentifier", "at-identifier"), | ||
("aturi", "at-uri"), | ||
("cid", "cid"), | ||
("datetime", "datetime"), | ||
("did", "did"), | ||
("handle", "handle"), | ||
("language", "language"), | ||
("nsid", "nsid"), | ||
("recordkey", "record-key"), | ||
("tid", "tid"), | ||
("uri", "uri"), | ||
]; | ||
let (mut seen, mut wrong) = (0, Vec::new()); | ||
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 want = kind == "syntax_valid"; | ||
for line in std::fs::read_to_string(&path).unwrap().lines() { | ||
if line.is_empty() || line.starts_with('#') { | ||
continue; | ||
} | ||
// 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 }; | ||
if valid(format, line) != expect { | ||
wrong.push(format!("{name}: {line:?}")); | ||
} | ||
seen += 1; | ||
} | ||
} | ||
assert!(wrong.is_empty(), "{wrong:#?}"); | ||
assert!(seen > 500, "{seen} vectors"); | ||
} | ||
| ||
#[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"] { | ||
assert!(valid_datetime(ok), "{ok}"); | ||
} | ||
for bad in [ | ||
"1985-04-12T23:20:60Z", | ||
"0000-01-01T00:00:00+01:00", | ||
"9999-12-31T23:30:00-01:00", | ||
"1985-04-12T23:20:50-00:00", | ||
&format!("1985-04-12T23:20:50.{}Z", "1".repeat(44)), | ||
"1985-04-12T23:20:50+24:00", | ||
] { | ||
assert!(!valid_datetime(bad), "{bad}"); | ||
} | ||
assert!(valid_datetime(&format!("1985-04-12T23:20:50.{}Z", "1".repeat(43)))); | ||
} | ||
| ||
#[test] | ||
fn uris() { | ||
for ok in ["a:b", "at://x", "a_1://b", "x:a/b", "a:b:/c"] { | ||
assert!(valid_uri(ok), "{ok}"); | ||
} | ||
for bad in ["a:", "a:/b", "a:///b", "a://", "a-b:c", "a:b\u{feff}", ":b"] { | ||
assert!(!valid_uri(bad), "{bad}"); | ||
} | ||
assert!(valid_uri("a:b\u{85}"), "U+0085 is no JavaScript space"); | ||
} | ||
| ||
#[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", | ||
] { | ||
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-", "", | ||
] { | ||
assert!(!valid_language(bad), "{bad}"); | ||
} | ||
} | ||
} | ||
crates/pds-lexicon/src/lib.rs+380−29
409 lines changed: not loaded until asked for.
crates/pds-lexicon/Cargo.toml+1−0
| @@ -8,3 +8,4 @@ publish.workspace = true | ||
pds-repo.workspace = true | ||
pds-space.workspace = true | ||
serde_json.workspace = true | ||
unicode-segmentation.workspace = true | ||
crates/pds-repo/src/data.rs+163−16
| @@ -89,12 +89,12 @@ pub fn parse_cid(s: &str) -> Option<Vec<u8>> { | ||
} | ||
} | ||
| ||
/// Whether `s` is a CID as text: version 0 in base58, or version 1 in base32 | ||
/// whose multihash is as long as it says. | ||
/// Whether `s` is a CID as text that, parsed, is written the same way | ||
/// again: version 0 in base58btc, a sha-256 multihash, or version 1 in | ||
/// lower-case base32 whose multihash is as long as it says. | ||
pub fn valid_cid_string(s: &str) -> bool { | ||
const B58: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; | ||
if s.len() == 46 && s.starts_with("Qm") { | ||
return s.bytes().all(|c| B58.contains(&c)); | ||
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]); | ||
} | ||
fn varint(rest: &mut &[u8]) -> Option<u64> { | ||
let mut n = 0; | ||
| @@ -271,11 +271,6 @@ pub fn from_json(j: &Json) -> Result<V, String> { | ||
let bytes = b.as_str().and_then(|s| B64.decode(s).ok()).ok_or("invalid $bytes")?; | ||
return Ok(V::Bytes(bytes)); | ||
} | ||
if let Some(t) = o.get("$type") { | ||
if t.as_str().is_none_or(str::is_empty) { | ||
return Err("$type must be a non-empty string".into()); | ||
} | ||
} | ||
let mut m = Vec::new(); | ||
for (k, x) in o { | ||
m.push((k.clone(), from_json(x)?)); | ||
| @@ -285,6 +280,17 @@ pub fn from_json(j: &Json) -> Result<V, String> { | ||
}) | ||
} | ||
| ||
/// A record, from JSON: an object in the data model whose own `$type`, if it | ||
/// 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)) { | ||
return Err("$type must be a non-empty string".into()); | ||
} | ||
from_json(j) | ||
} | ||
| ||
pub fn to_json(v: &V) -> Json { | ||
match v { | ||
V::Null => Json::Null, | ||
| @@ -300,6 +306,8 @@ pub fn to_json(v: &V) -> Json { | ||
| ||
// ---- Syntax --------------------------------------------------------------- | ||
| ||
/// Whether `s` is an NSID (`atproto/nsid.md`). As atproto's vectors have it, | ||
/// only the whole is held to 317 characters, not the domain authority to 253. | ||
pub fn valid_nsid(s: &str) -> bool { | ||
if !s.is_ascii() || s.len() > 317 { | ||
return false; | ||
| @@ -309,9 +317,6 @@ pub fn valid_nsid(s: &str) -> bool { | ||
return false; | ||
} | ||
let (name, domain) = segs.split_last().unwrap(); | ||
if domain.join(".").len() > 253 { | ||
return false; | ||
} | ||
for (i, seg) in domain.iter().enumerate() { | ||
let b = seg.as_bytes(); | ||
if b.is_empty() || b.len() > 63 || b[0] == b'-' || b[b.len() - 1] == b'-' { | ||
| @@ -365,6 +370,94 @@ pub fn valid_at_identifier(s: &str) -> bool { | ||
valid_did(s) || valid_handle(s) | ||
} | ||
| ||
// ---- Datetimes -------------------------------------------------------------- | ||
| ||
/// Days since 1970-01-01 of a proleptic Gregorian date. | ||
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { | ||
let y = if m <= 2 { y - 1 } else { y }; | ||
let era = y.div_euclid(400); | ||
let yoe = y.rem_euclid(400); | ||
let mp = (m + 9) % 12; | ||
let doy = (153 * mp + 2) / 5 + d - 1; | ||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; | ||
era * 146_097 + doe - 719_468 | ||
} | ||
| ||
/// The proleptic Gregorian date `(year, month, day)` of days since 1970-01-01. | ||
pub fn civil_from_days(days: i64) -> (i64, i64, i64) { | ||
let z = days + 719_468; | ||
let era = z.div_euclid(146_097); | ||
let doe = z.rem_euclid(146_097); | ||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; | ||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); | ||
let mp = (5 * doy + 2) / 153; | ||
let day = doy - (153 * mp + 2) / 5 + 1; | ||
let month = if mp < 10 { mp + 3 } else { mp - 9 }; | ||
(yoe + era * 400 + i64::from(month <= 2), month, day) | ||
} | ||
| ||
/// Milliseconds since the epoch as an atproto datetime, in UTC to the millisecond. | ||
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) | ||
} | ||
| ||
/// A datetime as `atproto/lexicon.md` defines the format, as milliseconds | ||
/// since the epoch in UTC: `YYYY-MM-DDTHH:MM:SS`, optional fractional | ||
/// seconds, then `Z` or `±HH:MM` (not `-00:00`), naming a real date and | ||
/// time no earlier than year 0. None if it is not one. | ||
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'))) | ||
}; | ||
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)?); | ||
let (hour, minute, second) = (digits(11..13)?, digits(14..16)?, digits(17..19)?); | ||
let mut i = 19; | ||
let mut millis = 0; | ||
if b[i] == b'.' { | ||
let start = i + 1; | ||
i = start; | ||
while i < b.len() && b[i].is_ascii_digit() { | ||
i += 1; | ||
} | ||
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); | ||
} | ||
let offset = match &b[i..] { | ||
b"Z" => 0, | ||
[sign @ (b'+' | b'-'), _, _, b':', _, _] => { | ||
let (h, m) = (digits(i + 1..i + 3)?, digits(i + 4..i + 6)?); | ||
if h > 23 || m > 59 || (*sign == b'-' && h == 0 && m == 0) { | ||
return None; | ||
} | ||
(h * 60 + m) * if *sign == b'+' { 1 } else { -1 } | ||
} | ||
_ => 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 { | ||
return None; | ||
} | ||
let local = ((days_from_civil(year, month, day) * 24 + hour) * 60 + minute) * 60 + second; | ||
let utc = (local - offset * 60) * 1000 + millis; | ||
// Year 0 begins 719528 days before the epoch; nothing may come before it. | ||
(utc >= -719_528 * 86_400_000).then_some(utc) | ||
} | ||
| ||
/// Whether `s` is a datetime as `atproto/lexicon.md` defines the format. | ||
pub fn valid_datetime(s: &str) -> bool { | ||
datetime_millis(s).is_some() | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| @@ -394,6 +487,52 @@ mod tests { | ||
assert!(!valid_cid_string(&cid[..cid.len() - 2]) && !valid_cid_string("bafy") && !valid_cid_string("not a cid")); | ||
} | ||
| ||
#[test] | ||
fn datetimes() { | ||
let valid = [ | ||
"1985-04-12T23:20:50.123Z", | ||
"1985-04-12T23:20:50.123456Z", | ||
"0001-01-01T00:00:00.000Z", | ||
"0000-01-01T00:00:00.000Z", | ||
"1985-04-12T23:20:50.12345678912345Z", | ||
"1985-04-12T23:20:50Z", | ||
"1985-04-12T23:20:50.0Z", | ||
"1985-04-12T23:20:50.123+00:00", | ||
"1985-04-12T23:20:50.123-07:00", | ||
"2024-02-29T00:00:00Z", | ||
]; | ||
for s in valid { | ||
assert!(valid_datetime(s), "{s}"); | ||
} | ||
let invalid = [ | ||
"1985-04-12", | ||
"1985-04-12T23:20Z", | ||
"1985-04-12T23:20:5Z", | ||
"1985-04-12T23:20:50.123", | ||
"+001985-04-12T23:20:50.123Z", | ||
"23:20:50.123Z", | ||
"-1985-04-12T23:20:50.123Z", | ||
"1985-4-12T23:20:50.123Z", | ||
"01985-04-12T23:20:50.123Z", | ||
"1985-04-12T23:20:50.123+00", | ||
"1985-04-12T23:20:50.123+0000", | ||
"1985-04-12t23:20:50.123Z", | ||
"1985-04-12T23:20:50.123z", | ||
"1985-04-12T23:20:50.123-00:00", | ||
"1985-04-12 23:20:50.123Z", | ||
"1985-04-12T23:99:50.123Z", | ||
"1985-00-12T23:20:50.123Z", | ||
"0000-01-01T00:00:00+01:00", | ||
"2023-02-29T00:00:00Z", | ||
"1985-04-12T23:20:50.Z", | ||
]; | ||
for s in invalid { | ||
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"); | ||
} | ||
| ||
/// 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] | ||
| @@ -403,16 +542,24 @@ mod tests { | ||
let kept = ["blob with string size", "blob with missing key", "link with extra fields"]; | ||
for c in cases { | ||
let j = &c["json"]; | ||
let Some(x) = j.get("rcrd").or(j.get("blb")).or(j.get("lnk")) else { continue }; | ||
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"))) { | ||
(Some(r), _) => (r, record_from_json), | ||
(None, Some(x)) => (x, from_json), | ||
(None, None) => continue, | ||
}; | ||
if kept.contains(¬e) { | ||
let v = from_json(x).unwrap(); | ||
let v = parse(x).unwrap(); | ||
assert!(matches!(v, V::Map(_)), "{note}"); | ||
assert_eq!(&to_json(&v), x, "{note}"); | ||
} else { | ||
assert!(from_json(x).is_err(), "{note}"); | ||
assert!(parse(x).is_err(), "{note}"); | ||
} | ||
} | ||
// Within a record, an object's `$type` is any value. | ||
let nested = serde_json::json!({ "$type": "a.b.c", "x": { "$type": { "a": 1 } }, "y": [{ "$type": 5 }, { "$type": "" }] }); | ||
assert_eq!(to_json(&record_from_json(&nested).unwrap()), nested); | ||
assert!(record_from_json(&serde_json::json!([])).is_err()); | ||
for kept in [ | ||
serde_json::json!({ "$type": "blob", "ref": "bafkrei", "mimeType": "", "size": null }), | ||
serde_json::json!({ "$type": "blob", "ref": { "a": 1 }, "mimeType": 5, "size": -2, "x": 1 }), | ||
crates/pds-repo/src/lib.rs+29−2
| @@ -130,6 +130,8 @@ pub struct Undo { | ||
head_bytes: Vec<u8>, | ||
tree: mst::Node, | ||
held: HashMap<Vec<u8>, Held>, | ||
/// What `written` held of each record the commit wrote or deleted. | ||
written: Vec<(String, Option<String>)>, | ||
} | ||
| ||
/// A commit made and not yet put in place. | ||
| @@ -146,6 +148,8 @@ pub struct Repo { | ||
pub did: String, | ||
key: SigningKey, | ||
pub records: BTreeMap<String, Record>, | ||
/// The rev of the commit that last wrote each record it holds, by path. | ||
pub written: HashMap<String, String>, | ||
/// Empty until the first commit. | ||
pub rev: String, | ||
pub head: Vec<u8>, | ||
| @@ -169,6 +173,7 @@ impl Repo { | ||
did, | ||
key, | ||
records: BTreeMap::new(), | ||
written: HashMap::new(), | ||
rev: String::new(), | ||
head: vec![], | ||
head_bytes: vec![], | ||
| @@ -191,6 +196,11 @@ impl Repo { | ||
self.key.verifying_key() | ||
} | ||
| ||
/// The key that signs its commits, which is its account's signing key. | ||
pub fn signing_key(&self) -> &SigningKey { | ||
&self.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] { | ||
| @@ -288,6 +298,7 @@ impl Repo { | ||
head_bytes: std::mem::replace(&mut self.head_bytes, m.head_bytes), | ||
tree: std::mem::replace(&mut self.tree, m.tree), | ||
held: std::mem::replace(&mut self.held, m.held), | ||
written: Vec::new(), | ||
}); | ||
change | ||
} | ||
| @@ -305,6 +316,12 @@ impl Repo { | ||
self.head_bytes = u.head_bytes; | ||
self.tree = u.tree; | ||
self.held = u.held; | ||
for (k, rev) in u.written { | ||
match rev { | ||
Some(r) => self.written.insert(k, r), | ||
None => self.written.remove(&k), | ||
}; | ||
} | ||
self.change = None; | ||
} | ||
| ||
| @@ -312,9 +329,11 @@ impl Repo { | ||
pub fn load(&mut self, c: &Change) -> Result<(), String> { | ||
for (path, j) in &c.puts { | ||
self.records.insert(path.clone(), make_record(from_json(j).map_err(|e| format!("record {path}: {e}"))?)); | ||
self.written.insert(path.clone(), c.rev.clone()); | ||
} | ||
for path in &c.dels { | ||
self.records.remove(path); | ||
self.written.remove(path); | ||
} | ||
self.rev = c.rev.clone(); | ||
for cid in &c.added { | ||
| @@ -397,9 +416,17 @@ impl Repo { | ||
} | ||
return Err(e); | ||
} | ||
let puts = originals.keys().filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value)))).collect(); | ||
let dels = originals.keys().filter(|k| !self.records.contains_key(*k)).cloned().collect(); | ||
let puts: Vec<(String, serde_json::Value)> = originals.keys().filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value)))).collect(); | ||
let dels: Vec<String> = originals.keys().filter(|k| !self.records.contains_key(*k)).cloned().collect(); | ||
let mut change = self.install(made.expect("a commit made"), originals); | ||
let rev = change.rev.clone(); | ||
let was = change.undo.as_mut().map(|u| &mut u.written).expect("an undo installed"); | ||
for (k, _) in &puts { | ||
was.push((k.clone(), self.written.insert(k.clone(), rev.clone()))); | ||
} | ||
for k in &dels { | ||
was.push((k.clone(), self.written.remove(k))); | ||
} | ||
change.puts = puts; | ||
change.dels = dels; | ||
self.change = Some(change); | ||
crates/pds-repo/Cargo.toml+1−0
| @@ -6,6 +6,7 @@ publish.workspace = true | ||
| ||
[dependencies] | ||
base64.workspace = true | ||
bs58.workspace = true | ||
k256.workspace = true | ||
rand.workspace = true | ||
serde_json.workspace = true | ||
crates/pds-server/src/oauth/clients/fetch.rs+24−141
| @@ -1,13 +1,12 @@ | ||
//! Fetching a client's document or JWKS, as `spec/OAUTH-CLIENTS.md` says | ||
//! under "The document": one `GET`, no redirect followed, `200`, JSON of at | ||
//! most 512 KiB, within 10 seconds, over https from public unicast | ||
//! addresses only; or, for an origin `PDS_OAUTH_CLIENT_FETCH` lists, from | ||
//! the base URL it names instead ("The development fetch"). | ||
//! most 512 KiB, within 10 seconds, over https; or, for an origin | ||
//! `PDS_OAUTH_CLIENT_FETCH` lists, from the base URL it names instead ("The | ||
//! development fetch"). Every fetch goes out through `outbound`, from public | ||
//! unicast addresses only unless `PDS_DISABLE_SSRF_PROTECTION` says otherwise. | ||
| ||
use reqwest::dns::{Addrs, Name, Resolve, Resolving}; | ||
use crate::outbound::Outbound; | ||
use serde_json::{Map, Value as Json}; | ||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; | ||
use std::sync::Arc; | ||
use std::time::Duration; | ||
use url::{Host, Url}; | ||
| ||
| @@ -72,138 +71,42 @@ pub(super) enum Kind { | ||
Jwks, | ||
} | ||
| ||
/// Whether an address is a public unicast one: none of the loopback, | ||
/// private, link-local, shared, documentation, multicast, reserved and | ||
/// other special ranges, nor an IPv6 form of one of those IPv4 addresses. | ||
pub(super) fn public(ip: IpAddr) -> bool { | ||
match ip { | ||
IpAddr::V4(a) => public_v4(a), | ||
IpAddr::V6(a) => public_v6(a), | ||
} | ||
} | ||
| ||
fn public_v4(a: Ipv4Addr) -> bool { | ||
let [x, y, z, _] = a.octets(); | ||
!(x == 0 | ||
|| x == 10 | ||
|| x == 127 | ||
|| (x == 100 && (64..128).contains(&y)) | ||
|| (x == 169 && y == 254) | ||
|| (x == 172 && (16..32).contains(&y)) | ||
|| (x == 192 && y == 0 && (z == 0 || z == 2)) | ||
|| (x == 192 && y == 88 && z == 99) | ||
|| (x == 192 && y == 168) | ||
|| (x == 198 && (18..20).contains(&y)) | ||
|| (x == 198 && y == 51 && z == 100) | ||
|| (x == 203 && y == 0 && z == 113) | ||
|| x >= 224) | ||
} | ||
| ||
fn public_v6(a: Ipv6Addr) -> bool { | ||
let s = a.segments(); | ||
let embedded = |hi: usize| Ipv4Addr::new((s[hi] >> 8) as u8, s[hi] as u8, (s[hi + 1] >> 8) as u8, s[hi + 1] as u8); | ||
if let Some(v4) = a.to_ipv4_mapped() { | ||
return public_v4(v4); | ||
} | ||
// NAT64's well-known prefix, and 6to4, carry an IPv4 address. | ||
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] { | ||
return public_v4(embedded(6)); | ||
} | ||
if s[0] == 0x2002 { | ||
return public_v4(embedded(1)); | ||
} | ||
// Global unicast only, less Teredo, ORCHID and documentation. | ||
(s[0] & 0xe000) == 0x2000 && !(s[0] == 0x2001 && (s[1] == 0 || (0x10..0x30).contains(&s[1]) || s[1] == 0x0db8)) && s[0] != 0x3fff | ||
} | ||
| ||
/// A resolver that answers a name's addresses only if every one is public: | ||
/// a name that resolves to a private address is refused, not half-taken. | ||
struct PublicOnly; | ||
| ||
impl Resolve for PublicOnly { | ||
fn resolve(&self, name: Name) -> Resolving { | ||
let host = name.as_str().to_string(); | ||
Box::pin(async move { | ||
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host.as_str(), 0)).await?.collect(); | ||
if addrs.is_empty() { | ||
return Err(format!("{host} has no address").into()); | ||
} | ||
if let Some(a) = addrs.iter().find(|a| !public(a.ip())) { | ||
return Err(format!("{host} resolves to {}, which is not a public address", a.ip()).into()); | ||
} | ||
Ok(Box::new(addrs.into_iter()) as Addrs) | ||
}) | ||
} | ||
} | ||
| ||
/// The clients documents and JWKS are fetched with. | ||
/// How clients' documents and JWKS are fetched: through `Outbound`, as every | ||
/// request to another service is, with the development fetch's mapping. | ||
pub(super) struct Fetcher { | ||
/// For the internet: https only, public addresses only. | ||
public: reqwest::Client, | ||
/// The development fetch, and its client, which goes wherever it is told. | ||
dev: Option<(ClientFetch, reqwest::Client)>, | ||
} | ||
| ||
fn builder(timeout: Duration) -> reqwest::ClientBuilder { | ||
reqwest::Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none()).timeout(timeout) | ||
dev: Option<ClientFetch>, | ||
timeout: Duration, | ||
} | ||
| ||
impl Fetcher { | ||
pub fn new(dev: Option<ClientFetch>) -> Result<Fetcher, String> { | ||
pub fn new(dev: Option<ClientFetch>) -> Fetcher { | ||
Fetcher::with_timeout(dev, TIMEOUT) | ||
} | ||
| ||
pub fn with_timeout(dev: Option<ClientFetch>, timeout: Duration) -> Result<Fetcher, String> { | ||
let public = builder(timeout).https_only(true).dns_resolver(Arc::new(PublicOnly)).build().map_err(|e| format!("an HTTP client: {e}"))?; | ||
let dev = match dev { | ||
Some(d) => Some((d, builder(timeout).build().map_err(|e| format!("an HTTP client: {e}"))?)), | ||
None => None, | ||
}; | ||
Ok(Fetcher { public, dev }) | ||
pub fn with_timeout(dev: Option<ClientFetch>, timeout: Duration) -> Fetcher { | ||
Fetcher { dev, timeout } | ||
} | ||
| ||
/// The JSON object at `url`, if it is answered as `spec/OAUTH-CLIENTS.md` | ||
/// takes it; else why not. | ||
pub async fn get(&self, url: &Url, kind: Kind) -> Result<Map<String, Json>, String> { | ||
let (http, target) = match self.dev.as_ref().and_then(|(d, http)| Some((http, d.target(url)?))) { | ||
/// 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> { | ||
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")); | ||
} | ||
// The resolver checks names; an address given as one is checked here. | ||
let literal = match url.host() { | ||
Some(Host::Ipv4(a)) => Some(IpAddr::V4(a)), | ||
Some(Host::Ipv6(a)) => Some(IpAddr::V6(a)), | ||
Some(Host::Domain(_)) => None, | ||
None => return Err(format!("{url} has no host")), | ||
}; | ||
if literal.is_some_and(|a| !public(a)) { | ||
return Err(format!("{url} is not on a public address")); | ||
} | ||
(&self.public, url.to_string()) | ||
} | ||
None if url.scheme() != "https" => return Err(format!("{url} is not https")), | ||
None => url.to_string(), | ||
}; | ||
let mut res = http.get(&target).header("accept", "application/json").send().await.map_err(|e| format!("fetching {url}: {e}"))?; | ||
if res.status().as_u16() != 200 { | ||
return Err(format!("{url} answered {}", res.status())); | ||
let got = outbound.fetch_limited(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 = res.headers().get("content-type").map(|v| v.to_str().unwrap_or_default().split(';').next().unwrap_or_default().trim().to_ascii_lowercase()); | ||
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")); | ||
} | ||
if res.content_length().is_some_and(|n| n > MAX_BODY as u64) { | ||
return Err(format!("{url} is over {MAX_BODY} bytes")); | ||
} | ||
let mut body = Vec::new(); | ||
while let Some(chunk) = res.chunk().await.map_err(|e| format!("reading {url}: {e}"))? { | ||
if body.len() + chunk.len() > MAX_BODY { | ||
return Err(format!("{url} is over {MAX_BODY} bytes")); | ||
} | ||
body.extend_from_slice(&chunk); | ||
} | ||
match serde_json::from_slice(&body) { | ||
match serde_json::from_slice(&got.body) { | ||
Ok(Json::Object(m)) => Ok(m), | ||
_ => Err(format!("{url} is not a JSON object")), | ||
} | ||
| @@ -214,26 +117,6 @@ impl Fetcher { | ||
mod tests { | ||
use super::*; | ||
| ||
#[test] | ||
fn public_addresses() { | ||
for a in ["8.8.8.8", "1.2.3.4", "2606:4700::1111", "::ffff:8.8.8.8", "64:ff9b::808:808", "2002:808:808::1"] { | ||
assert!(public(a.parse().unwrap()), "{a}"); | ||
} | ||
for a in [ | ||
"0.0.0.0", "127.0.0.1", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1", "169.254.169.254", "100.64.0.1", "192.0.2.1", "198.18.0.1", | ||
"203.0.113.9", "224.0.0.1", "255.255.255.255", "::", "::1", "fe80::1", "fc00::1", "fd12::1", "ff02::1", "2001:db8::1", "2001::1", | ||
"::ffff:127.0.0.1", "::ffff:10.0.0.1", "64:ff9b::7f00:1", "2002:7f00:1::1", "::127.0.0.1", | ||
] { | ||
assert!(!public(a.parse().unwrap()), "{a}"); | ||
} | ||
} | ||
| ||
#[tokio::test] | ||
async fn names_of_private_addresses_are_refused() { | ||
let r = PublicOnly.resolve("localhost".parse().unwrap()).await; | ||
assert!(r.is_err()); | ||
} | ||
| ||
#[test] | ||
fn the_development_fetch() { | ||
let f = ClientFetch::parse("https://app.example-client.net=http://127.0.0.1:4100/server/app,https://b.example-client.net=https://x.net").unwrap(); | ||
crates/pds-server/src/oauth/clients/tests.rs+19−12
| @@ -458,7 +458,7 @@ async fn documents_and_jwks_are_kept() { | ||
| ||
#[tokio::test] | ||
async fn fetches_stay_off_private_addresses() { | ||
let fetcher = Fetcher::new(None).unwrap(); | ||
let (fetcher, guarded) = (Fetcher::new(None), crate::outbound::Outbound::new(true).unwrap()); | ||
for url in [ | ||
"https://10.0.0.1/jwks.json", | ||
"https://127.0.0.1/c.json", | ||
| @@ -469,22 +469,29 @@ async fn fetches_stay_off_private_addresses() { | ||
"http://example.net/c.json", | ||
] { | ||
let u = url::Url::parse(url).unwrap(); | ||
assert!(fetcher.get(&u, Kind::Jwks).await.is_err(), "{url}"); | ||
assert!(fetcher.get(&guarded, &u, Kind::Jwks).await.is_err(), "{url}"); | ||
} | ||
// Through the server: a JWKS on a private address, on no listed origin, is never had. | ||
let (dir, srv, web, _) = setup("oauth-clients-ssrf").await; | ||
let k = ClientKey::new("k1"); | ||
// Through a server with SSRF protection: the development fetch goes out | ||
// through the same guard, so a document on this machine is never had. | ||
let web = Web::start().await; | ||
let plc = plc().await; | ||
let dir = scratch("oauth-clients-ssrf"); | ||
let mut config = Config { oauth_client_fetch: Some(web.fetch()), ..crate::testing::config(&plc) }; | ||
config.ssrf_protection = true; | ||
let srv = serve(Arc::new(Service::open(&dir, config).unwrap())).await; | ||
let id = fresh("ssrf"); | ||
let doc = with(web_doc(&id), json!({ "token_endpoint_auth_method": "private_key_jwt", "token_endpoint_auth_signing_alg": "ES256", "jwks_uri": "https://10.0.0.1/jwks.json" })); | ||
web.serve(&id, Answer::Json(doc)); | ||
let a = good(&srv, &id, &k); | ||
let (g, _) = app(&srv, &id, "atproto").par(&[("client_assertion_type", Some(ASSERTION_TYPE)), ("client_assertion", Some(&a))]).await; | ||
assert_eq!(refused(&g), (400, META.into())); | ||
web.serve(&id, Answer::Json(web_doc(&id))); | ||
assert_eq!(refused(&app(&srv, &id, "atproto").par(&[]).await.0), (400, META.into())); | ||
assert_eq!(web.hits(&id), 0); | ||
// An answer that takes too long is none. | ||
let slow = Fetcher::with_timeout(Some(web.fetch()), Duration::from_millis(300)).unwrap(); | ||
let (slow, open) = (Fetcher::with_timeout(Some(web.fetch()), Duration::from_millis(300)), crate::outbound::Outbound::new(false).unwrap()); | ||
let url = format!("{APP}/slow.json"); | ||
web.serve(&url, Answer::Hang); | ||
assert!(slow.get(&url::Url::parse(&url).unwrap(), Kind::Document).await.is_err()); | ||
assert!(slow.get(&open, &url::Url::parse(&url).unwrap(), Kind::Document).await.is_err()); | ||
// So is one too long. | ||
let big = format!("{APP}/big.json"); | ||
web.serve(&big, Answer::Json(json!({ "x": "y".repeat(512 * 1024) }))); | ||
assert!(Fetcher::new(Some(web.fetch())).get(&open, &url::Url::parse(&big).unwrap(), Kind::Document).await.is_err()); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
crates/pds-server/src/oauth/clients.rs+4−4
| @@ -98,8 +98,8 @@ pub(crate) struct Clients { | ||
} | ||
| ||
impl Clients { | ||
pub fn new(dev: Option<ClientFetch>) -> Result<Clients, String> { | ||
Ok(Clients { fetcher: fetch::Fetcher::new(dev)?, documents: Cache::new(), jwks: Cache::new() }) | ||
pub fn new(dev: Option<ClientFetch>) -> Clients { | ||
Clients { fetcher: fetch::Fetcher::new(dev), documents: Cache::new(), jwks: Cache::new() } | ||
} | ||
} | ||
| ||
| @@ -120,7 +120,7 @@ pub(super) async fn load_why(svc: &Service, id: &str) -> Result<Client, Failure> | ||
let taken = match clients.documents.get(id, svc.sessions.now()) { | ||
Some(t) => t, | ||
None => { | ||
let doc = clients.fetcher.get(&url, fetch::Kind::Document).await.map_err(|_| Failure::Unusable)?; | ||
let doc = clients.fetcher.get(&svc.outbound, &url, fetch::Kind::Document).await.map_err(|_| Failure::Unusable)?; | ||
let t = Arc::new(document::check(id, &url, &doc)?); | ||
clients.documents.put(id, svc.sessions.now(), t.clone()); | ||
t | ||
| @@ -148,7 +148,7 @@ async fn jwks(svc: &Service, url: &url::Url) -> Result<Arc<Vec<Map<String, Json> | ||
if let Some(k) = clients.jwks.get(url.as_str(), svc.sessions.now()) { | ||
return Ok(k); | ||
} | ||
let set = clients.fetcher.get(url, fetch::Kind::Jwks).await.map_err(|_| Failure::Unusable)?; | ||
let set = clients.fetcher.get(&svc.outbound, url, fetch::Kind::Jwks).await.map_err(|_| Failure::Unusable)?; | ||
let Some(Json::Array(keys)) = set.get("keys") else { return Err(Failure::Unusable) }; | ||
let keys = Arc::new(assertion::client_keys(keys)); | ||
clients.jwks.put(url.as_str(), svc.sessions.now(), keys.clone()); | ||
crates/pds-server/src/oauth/page.rs+9−6
| @@ -161,12 +161,15 @@ fn account_json(svc: &Service, a: &Account) -> Json { | ||
if let Some(e) = &a.email { | ||
out["email"] = json!(e); | ||
} | ||
let name = crate::read(&a.store).repo.records.get("app.bsky.actor.profile/self").and_then(|r| { | ||
let profile = pds_repo::data::to_json(&r.value); | ||
profile["displayName"].as_str().map(str::to_string) | ||
}); | ||
if let Some(n) = name { | ||
out["name"] = json!(n); | ||
let profile = crate::read(&a.store).repo.records.get("app.bsky.actor.profile/self").map(|r| pds_repo::data::to_json(&r.value)); | ||
if let Some(p) = profile { | ||
if let Some(n) = p["displayName"].as_str() { | ||
out["name"] = json!(n); | ||
} | ||
// A blob ref, or a legacy one of a bare `cid`. | ||
if let Some(cid) = p["avatar"]["ref"]["$link"].as_str().or_else(|| p["avatar"]["cid"].as_str()) { | ||
out["picture"] = json!(crate::read_after_write::image_url(svc, "avatar", &a.did, cid)); | ||
} | ||
} | ||
out | ||
} | ||
crates/pds-server/src/oauth/tests.rs+1−1
| @@ -25,7 +25,7 @@ impl Drop for Server { | ||
pub(crate) async fn serve(svc: Shared) -> Server { | ||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); | ||
let base = format!("http://{}", listener.local_addr().unwrap()); | ||
let app = crate::router(&svc); | ||
let app = crate::router(svc.clone()); | ||
let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); | ||
let http = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).build().unwrap(); | ||
Server { svc, base, task, http } | ||
crates/pds-server/src/scopes/tests.rs+30−2
crates/pds-server/src/space_credentials/tests.rs+1−1
crates/pds-server/src/space_notify/tests.rs+3−3
crates/pds-server/src/blobs.rs+6−6
crates/pds-server/src/compact.rs+18−3
crates/pds-server/src/events.rs+2−23
crates/pds-server/src/federation.rs+2−1
crates/pds-server/src/lib.rs+170−33
crates/pds-server/src/limits.rs+31−12
crates/pds-server/src/log.rs+85−6
crates/pds-server/src/mcp.rs+7−1
crates/pds-server/src/oauth.rs+1−1
crates/pds-server/src/outbound.rs+259−96
crates/pds-server/src/preferences.rsnew+221−0
crates/pds-server/src/proxy.rsnew+1426−0
1426 lines changed: not loaded until asked for.
crates/pds-server/src/read_after_write.rsnew+412−0
412 lines changed: not loaded until asked for.
crates/pds-server/src/repo.rs+58−33
crates/pds-server/src/scopes.rs+74−24
crates/pds-server/src/sessions.rs+1−1
crates/pds-server/src/space_authority.rs+1−1
crates/pds-server/src/space_notify.rs+9−12
crates/pds-server/src/space_repo.rs+2−2
crates/pds-server/src/validation.rsnew+424−0
424 lines changed: not loaded until asked for.
harness/checks/blobs.mjs+27−5
harness/checks/commands.mjs+3−2
harness/checks/crashes.mjs+2−0
harness/checks/limits.mjs+25−3
harness/checks/proxy.mjsnew+777−0
777 lines changed: not loaded until asked for.
harness/checks/validation.mjsnew+562−0
562 lines changed: not loaded until asked for.
harness/lib/env.mjs+17−8
harness/lib/processes.mjs+6−2
harness/lib/services.mjsnew+142−0
harness/compare.mjs+8−0
spec/interop/syntax/atidentifier_syntax_invalid.txtnew+28−0
spec/interop/syntax/atidentifier_syntax_valid.txtnew+15−0
spec/interop/syntax/aturi_syntax_invalid.txtnew+89−0
spec/interop/syntax/aturi_syntax_valid.txtnew+35−0
spec/interop/syntax/cid_syntax_invalid.txtnew+16−0
spec/interop/syntax/cid_syntax_valid.txtnew+14−0
spec/interop/syntax/datetime_parse_invalid.txtnew+10−0
spec/interop/syntax/datetime_syntax_invalid.txtnew+66−0
spec/interop/syntax/datetime_syntax_valid.txtnew+42−0
spec/interop/syntax/did_syntax_invalid.txtnew+19−0
spec/interop/syntax/did_syntax_valid.txtnew+26−0
spec/interop/syntax/handle_syntax_invalid.txtnew+61−0
spec/interop/syntax/handle_syntax_valid.txtnew+90−0
spec/interop/syntax/language_parse_invalid.txtnew+14−0
spec/interop/syntax/language_syntax_invalid.txtnew+10−0
spec/interop/syntax/language_syntax_valid.txtnew+26−0
spec/interop/syntax/nsid_syntax_invalid.txtnew+30−0
spec/interop/syntax/nsid_syntax_valid.txtnew+32−0
spec/interop/syntax/recordkey_syntax_invalid.txtnew+15−0
spec/interop/syntax/recordkey_syntax_valid.txtnew+21−0
spec/interop/syntax/tid_syntax_invalid.txtnew+19−0
spec/interop/syntax/tid_syntax_valid.txtnew+7−0
spec/interop/syntax/uri_syntax_invalid.txtnew+17−0
spec/interop/syntax/uri_syntax_valid.txtnew+14−0
spec/lexicons/app/bsky/actor/contentVisibilityDeclaration.jsonnew+21−0
spec/lexicons/app/bsky/actor/defs.jsonnew+777−0
777 lines changed: not loaded until asked for.
spec/lexicons/app/bsky/actor/getPreferences.jsonnew+27−0
spec/lexicons/app/bsky/actor/getProfile.jsonnew+28−0
spec/lexicons/app/bsky/actor/getProfiles.jsonnew+37−0
spec/lexicons/app/bsky/actor/link.jsonnew+40−0
spec/lexicons/app/bsky/actor/profile.jsonnew+70−0
spec/lexicons/app/bsky/actor/putPreferences.jsonnew+23−0
spec/lexicons/app/bsky/actor/status.jsonnew+37−0
spec/lexicons/app/bsky/embed/defs.jsonnew+15−0
spec/lexicons/app/bsky/embed/external.jsonnew+358−0
spec/lexicons/app/bsky/embed/gallery.jsonnew+79−0
spec/lexicons/app/bsky/embed/images.jsonnew+73−0
spec/lexicons/app/bsky/embed/record.jsonnew+105−0
spec/lexicons/app/bsky/embed/recordWithMedia.jsonnew+45−0
spec/lexicons/app/bsky/embed/video.jsonnew+73−0
spec/lexicons/app/bsky/feed/defs.jsonnew+362−0
spec/lexicons/app/bsky/feed/generator.jsonnew+54−0
spec/lexicons/app/bsky/feed/getActorLikes.jsonnew+42−0
spec/lexicons/app/bsky/feed/getAuthorFeed.jsonnew+58−0
spec/lexicons/app/bsky/feed/getFeed.jsonnew+42−0
spec/lexicons/app/bsky/feed/getPostThread.jsonnew+57−0
spec/lexicons/app/bsky/feed/getTimeline.jsonnew+51−0
spec/lexicons/app/bsky/feed/like.jsonnew+20−0
spec/lexicons/app/bsky/feed/post.jsonnew+97−0
spec/lexicons/app/bsky/feed/postgate.jsonnew+46−0
spec/lexicons/app/bsky/feed/repost.jsonnew+20−0
spec/lexicons/app/bsky/feed/threadgate.jsonnew+69−0
spec/lexicons/app/bsky/graph/block.jsonnew+23−0
spec/lexicons/app/bsky/graph/defs.jsonnew+196−0
spec/lexicons/app/bsky/graph/follow.jsonnew+20−0
spec/lexicons/app/bsky/graph/list.jsonnew+47−0
spec/lexicons/app/bsky/graph/listblock.jsonnew+23−0
spec/lexicons/app/bsky/graph/listitem.jsonnew+28−0
spec/lexicons/app/bsky/graph/referencelistoptout.jsonnew+23−0
spec/lexicons/app/bsky/graph/starterpack.jsonnew+51−0
spec/lexicons/app/bsky/graph/verification.jsonnew+36−0
spec/lexicons/app/bsky/labeler/defs.jsonnew+91−0
spec/lexicons/app/bsky/labeler/service.jsonnew+47−0
spec/lexicons/app/bsky/notification/declaration.jsonnew+22−0
spec/lexicons/app/bsky/notification/defs.jsonnew+93−0
spec/lexicons/app/bsky/notification/registerPush.jsonnew+30−0
spec/lexicons/app/bsky/notification/unregisterPush.jsonnew+26−0
spec/lexicons/app/bsky/richtext/facet.jsonnew+51−0
spec/lexicons/chat/bsky/actor/declaration.jsonnew+26−0
spec/lexicons/com/atproto/label/defs.jsonnew+153−0
spec/lexicons/com/atproto/label/record.jsonnew+42−0
spec/lexicons/com/atproto/lexicon/schema.jsonnew+21−0
spec/lexicons/com/atproto/moderation/defs.jsonnew+99−0
spec/lexicons/com/atproto/server/getServiceAuth.jsonnew+48−0
spec/lexicons/com/germnetwork/declaration.jsonnew+64−0
spec/lexicons/place/stream/badge/defs.jsonnew+136−0
spec/lexicons/place/stream/chat/defs.jsonnew+49−0
spec/lexicons/place/stream/chat/pinnedRecord.jsonnew+38−0
spec/lexicons/place/stream/chat/profile.jsonnew+78−0
spec/lexicons/place/stream/defs.jsonnew+71−0
spec/lexicons/place/stream/livestream.jsonnew+184−0
spec/lexicons/site/standard/graph/recommend.jsonnew+24−0
spec/lexicons/site/standard/graph/subscription.jsonnew+24−0
spec/lexicons/site/standard/theme/basic.jsonnew+38−0
spec/lexicons/site/standard/theme/color.jsonnew+26−0
spec/lexicons/site/standard/document.jsonnew+106−0
spec/lexicons/site/standard/publication.jsonnew+66−0
spec/lexicons/social/grain/gallery/item.jsonnew+21−0
spec/lexicons/social/grain/defs.jsonnew+16−0
spec/lexicons/social/grain/favorite.jsonnew+19−0
spec/lexicons/social/grain/gallery.jsonnew+25−0
spec/lexicons/social/grain/photo.jsonnew+31−0
spec/COMMANDS.md+2−1
spec/LIMITS.md+43−31
spec/OAUTH-CLIENTS.md+15−7
spec/OAUTH-SCOPES.md+46−7
spec/OAUTH.md+5−2
spec/PDS.md+12−4
spec/PROXY.mdnew+601−0
601 lines changed: not loaded until asked for.