chadtmiller.com/monolith
An atproto PDS
0
0
Spaces: export, import and space blobs; write notifications, the writer set and syncers
crates/pds-lexicon/src/lib.rs+20−5
| @@ -28,8 +28,9 @@ pub enum Type { | ||
Integer, | ||
Boolean, | ||
Array, | ||
/// An `object`, `ref` or `union`, or another type whose JSON is an object. | ||
/// An `object`, `ref` or `union`. | ||
Object, | ||
/// `unknown`, `bytes`, `cid-link` or `blob`: JSON with no constraint. | ||
Unknown, | ||
} | ||
| ||
| @@ -452,7 +453,7 @@ fn type_of(p: &Json) -> Type { | ||
Some("integer") => Type::Integer, | ||
Some("boolean") => Type::Boolean, | ||
Some("array") => Type::Array, | ||
Some("unknown") => Type::Unknown, | ||
Some("unknown" | "bytes" | "cid-link" | "blob") => Type::Unknown, | ||
_ => Type::Object, | ||
} | ||
} | ||
| @@ -528,17 +529,29 @@ mod tests { | ||
let delete = method("com.atproto.server.deleteSession").unwrap(); | ||
assert_eq!((delete.tool().as_deref(), delete.output.as_deref(), delete.input.as_deref()), (Some("server_delete_session"), None, None)); | ||
let tools: Vec<String> = methods().iter().filter_map(Method::tool).collect(); | ||
assert_eq!(tools.len(), 47, "{tools:?}"); | ||
assert_eq!(tools.len(), 52, "{tools:?}"); | ||
assert!(tools.contains(&"space_list_blobs".to_string())); | ||
assert!(tools.contains(&"space_notify_write".to_string()) && tools.contains(&"space_list_repos".to_string())); | ||
assert!(tools.contains(&"sync_list_repos".to_string()) && tools.contains(&"sync_get_repo_status".to_string())); | ||
assert!(tools.contains(&"space_create_space".to_string()) && tools.contains(&"memberspace_put_member".to_string())); | ||
// uploadBlob's input and getBlob's answer are bytes: neither has a tool, both a command; | ||
// nor have a space meta archive's export and import. | ||
for nsid in ["com.atproto.repo.uploadBlob", "com.atproto.sync.getBlob", "com.atproto.space.exportSpaceMeta", "com.atproto.space.importSpaceMeta"] { | ||
// nor have a space meta archive's export and import, a space repo's archive and import, | ||
// or a space blob. | ||
for nsid in [ | ||
"com.atproto.repo.uploadBlob", | ||
"com.atproto.sync.getBlob", | ||
"com.atproto.space.exportSpaceMeta", | ||
"com.atproto.space.importSpaceMeta", | ||
"com.atproto.space.getRepo", | ||
"com.atproto.space.getBlob", | ||
"com.atproto.space.importRepo", | ||
] { | ||
let m = method(nsid).unwrap(); | ||
assert_eq!((m.tool(), m.command().is_some()), (None, true), "{nsid}"); | ||
} | ||
assert!(method("com.atproto.repo.uploadBlob").unwrap().raw_input()); | ||
assert!(method("com.atproto.space.importSpaceMeta").unwrap().raw_input()); | ||
assert!(method("com.atproto.space.importRepo").unwrap().raw_input()); | ||
assert!(!method("com.atproto.repo.createRecord").unwrap().raw_input()); | ||
assert_eq!(groups(), ["identity", "memberspace", "repo", "server", "space", "sync"]); | ||
assert!(method("com.atproto.repo.defs").is_none()); | ||
| @@ -577,6 +590,8 @@ mod tests { | ||
// `createAccount`'s optional `did` does not. | ||
assert_eq!(p["required"], json!(["collection", "record", "rkey"])); | ||
assert_eq!(method("com.atproto.sync.getRepo").unwrap().input_schema()["required"], json!([])); | ||
let n = method("com.atproto.space.notifyWrite").unwrap().input_schema(); | ||
assert!(n["properties"]["data"].get("type").is_none()); | ||
let create = method("com.atproto.server.createAccount").unwrap(); | ||
assert!(!create.arg("did").unwrap().names_account()); | ||
assert_eq!(create.input_schema()["required"], json!(["handle"])); | ||
crates/pds-server/src/space_credentials/tests.rs+3−2
| @@ -74,7 +74,7 @@ fn k256_key(key: &k256::ecdsa::SigningKey) -> impl FnOnce(&[u8]) -> Vec<u8> + '_ | ||
} | ||
| ||
/// The same signature with `s` in the upper half. | ||
fn high_s(sig: Vec<u8>) -> Vec<u8> { | ||
pub(crate) fn high_s(sig: Vec<u8>) -> Vec<u8> { | ||
let (r, s) = k256::ecdsa::Signature::from_slice(&sig).unwrap().split_scalars(); | ||
k256::ecdsa::Signature::from_scalars(k256::FieldBytes::from(r), k256::FieldBytes::from(-s)).unwrap().to_bytes().to_vec() | ||
} | ||
| @@ -113,7 +113,7 @@ fn headers_of(pairs: &[(&str, &str)]) -> HeaderMap { | ||
} | ||
| ||
/// A request presenting `credential`, signed by `c` for `audience`. | ||
fn signed(c: &Client, credential: &str, audience: &str) -> HeaderMap { | ||
pub(crate) fn signed(c: &Client, credential: &str, audience: &str) -> HeaderMap { | ||
signed_with(c, &format!("Atproto-Space-Credential {credential}"), audience, PARAMS) | ||
} | ||
| ||
| @@ -619,6 +619,7 @@ async fn revocations_take_service_auth() { | ||
let other_key = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap(); | ||
let mut rows: Vec<(String, Option<String>, &str)> = vec![ | ||
("none".into(), None, "401 MissingJwt"), | ||
("an empty header".into(), Some(String::new()), "401 MissingJwt"), | ||
("Basic".into(), Some(format!("Basic {}", STANDARD.encode("a:b"))), "401 MissingJwt"), | ||
("DPoP".into(), Some("DPoP x".into()), "401 MissingJwt"), | ||
("a credential".into(), Some("atproto-space-credential x".into()), "401 MissingJwt"), | ||
crates/pds-server/src/space_notify/tests.rsnew+858−0
858 lines changed: not loaded until asked for.
crates/pds-server/src/blobs.rs+59−16
| @@ -8,7 +8,9 @@ | ||
//! one for each upload it stopped holding for want of a reference in time | ||
//! (`blobGone`). Which records reference a blob is not logged apart: the | ||
//! records say, so the commits that write them carry it, and replaying the | ||
//! log counts the references again. | ||
//! log counts the references again. A space record's refs hold a blob as a | ||
//! public record's do (`space_repo` counts them), but the public `getBlob` | ||
//! and `listBlobs` serve and list only blobs public records reference. | ||
//! | ||
//! An upload is written to a temporary file in that directory, synced, and | ||
//! renamed into place, and the directory synced, before its entry is logged: | ||
| @@ -88,8 +90,12 @@ struct Undo { | ||
pub(crate) struct Blobs { | ||
/// The blobs it holds, by CID. | ||
held: BTreeMap<String, Held>, | ||
/// How many records reference each CID, for those some record does. | ||
/// How many public records reference each CID, for those some record does. | ||
refs: HashMap<String, u32>, | ||
/// How many records of the account's space repos reference each CID, | ||
/// for those some such record does (`space_repo`): these hold a blob as | ||
/// public records do, but the public methods neither serve nor list it. | ||
space_refs: HashMap<String, u32>, | ||
/// Each record with blob refs, by path: the rev of the commit that last | ||
/// wrote it, and the CIDs it references, each once, in order. | ||
records: HashMap<String, (String, Vec<String>)>, | ||
| @@ -110,7 +116,7 @@ pub(crate) struct Blobs { | ||
} | ||
| ||
/// A blob ref in a record. | ||
struct BlobRef { | ||
pub(crate) struct BlobRef { | ||
cid: Vec<u8>, | ||
mime: String, | ||
size: i64, | ||
| @@ -132,7 +138,7 @@ fn blob_ref(m: &[(String, V)]) -> Option<BlobRef> { | ||
} | ||
| ||
/// Every blob ref in a value, at any depth. | ||
fn refs_in(v: &V, out: &mut Vec<BlobRef>) { | ||
pub(crate) fn refs_in(v: &V, out: &mut Vec<BlobRef>) { | ||
match v { | ||
V::Map(m) => match blob_ref(m) { | ||
Some(r) => out.push(r), | ||
| @@ -144,7 +150,7 @@ fn refs_in(v: &V, out: &mut Vec<BlobRef>) { | ||
} | ||
| ||
/// The CIDs a record's blob refs name, each once, in order. | ||
fn cids_in(v: &V) -> Vec<String> { | ||
pub(crate) fn cids_in(v: &V) -> Vec<String> { | ||
let mut refs = Vec::new(); | ||
refs_in(v, &mut refs); | ||
let set: BTreeSet<String> = refs.iter().map(|r| cid_string(&r.cid)).collect(); | ||
| @@ -201,9 +207,14 @@ impl Blobs { | ||
(self.now, self.ttl) = (now, ttl); | ||
} | ||
| ||
/// Whether some record references `cid`, public or in a space repo. | ||
fn referenced(&self, cid: &str) -> bool { | ||
self.refs.contains_key(cid) || self.space_refs.contains_key(cid) | ||
} | ||
| ||
/// Whether a blob held is unreferenced and past its time. | ||
fn expired(&self, cid: &str) -> bool { | ||
!self.refs.contains_key(cid) && self.held.get(cid).is_some_and(|h| h.at.saturating_add(self.ttl) <= self.now) | ||
!self.referenced(cid) && self.held.get(cid).is_some_and(|h| h.at.saturating_add(self.ttl) <= self.now) | ||
} | ||
| ||
/// The unreferenced uploads past their time. | ||
| @@ -223,13 +234,14 @@ impl Blobs { | ||
self.held.get(cid).filter(|_| self.refs.contains_key(cid)) | ||
} | ||
| ||
/// Check a write's blob refs against the blobs as they were before it. | ||
fn check(&self, refs: &[BlobRef]) -> Result<(), XrpcError> { | ||
/// Check a write's blob refs against the blobs as they were before it: | ||
/// a public write's, or a space write's (`space_repo`). | ||
pub(crate) fn check(&self, refs: &[BlobRef]) -> Result<(), XrpcError> { | ||
for r in refs { | ||
let cid = cid_string(&r.cid); | ||
let Some(h) = self.held.get(&cid).filter(|_| !self.expired(&cid)) else { return err(400, "BlobNotFound", format!("Could not find blob: {cid}")) }; | ||
// One some record references already is taken as it is. | ||
if self.refs.contains_key(&cid) { | ||
// One some record, public or in a space, references already is taken as it is. | ||
if self.referenced(&cid) { | ||
continue; | ||
} | ||
if h.mime != r.mime { | ||
| @@ -249,7 +261,7 @@ impl Blobs { | ||
self.bytes -= old.size; | ||
} | ||
if let Some(h) = h { | ||
if !self.refs.contains_key(cid) { | ||
if !self.referenced(cid) { | ||
self.unreferenced.insert((h.at, cid.to_string())); | ||
} | ||
self.bytes += h.size; | ||
| @@ -293,7 +305,7 @@ impl Blobs { | ||
continue; | ||
} | ||
self.refs.remove(&cid); | ||
if d < 0 && held.is_some() { | ||
if d < 0 && held.is_some() && !self.space_refs.contains_key(&cid) { | ||
self.set_held(&cid, None); | ||
self.doomed.push(cid); | ||
} | ||
| @@ -301,6 +313,36 @@ impl Blobs { | ||
self.undo = Some(undo); | ||
} | ||
| ||
/// Count the references a space repo's commit changed, given each CID's | ||
/// change in the number of its records referencing it: a blob no record | ||
/// references any more, public or in a space, is no longer held, and its | ||
/// file is doomed. Made only once the commit is in the log. | ||
pub(crate) fn space_counted(&mut self, delta: BTreeMap<String, i64>) { | ||
for (cid, d) in delta { | ||
let n = i64::from(self.space_refs.get(&cid).copied().unwrap_or(0)) + d; | ||
if n > 0 { | ||
self.space_refs.insert(cid.clone(), n as u32); | ||
if let Some(h) = self.held.get(&cid) { | ||
self.unreferenced.remove(&(h.at, cid)); | ||
} | ||
continue; | ||
} | ||
self.space_refs.remove(&cid); | ||
if d < 0 && self.held.contains_key(&cid) && !self.refs.contains_key(&cid) { | ||
self.set_held(&cid, None); | ||
self.doomed.push(cid); | ||
} | ||
} | ||
} | ||
| ||
/// A blob a space repo's records reference, as its `getBlob` serves it: | ||
/// `400 InvalidRequest` if the account does not hold its bytes. | ||
pub(crate) fn serve_space(&self, dir: &Path, did: &str, cid: &str) -> Result<Resp, XrpcError> { | ||
let Some(h) = self.held.get(cid) else { return invalid(format!("Blob not held: {cid}")) }; | ||
let Ok(file) = File::open(blob_dir(dir, did).join(cid)) else { return internal() }; | ||
Ok(Resp::Blob(Served { file, mime: h.mime.clone(), size: h.size, cid: cid.to_string() })) | ||
} | ||
| ||
/// Put the blobs back as they were before the last commit. | ||
pub(crate) fn undo(&mut self) { | ||
let Some(u) = self.undo.take() else { return }; | ||
| @@ -320,7 +362,7 @@ impl Blobs { | ||
self.held.remove(&cid); | ||
self.unreferenced.retain(|(_, c)| *c != cid); | ||
if let Some(h) = h { | ||
if !self.refs.contains_key(&cid) { | ||
if !self.referenced(&cid) { | ||
self.unreferenced.insert((h.at, cid.clone())); | ||
} | ||
self.held.insert(cid, h); | ||
| @@ -334,7 +376,7 @@ impl Blobs { | ||
fn upload_of(&self, cid: &str) -> Upload { | ||
match self.held.get(cid) { | ||
None => Upload::New, | ||
Some(_) if self.refs.contains_key(cid) => Upload::Kept, | ||
Some(_) if self.referenced(cid) => Upload::Kept, | ||
Some(_) if self.expired(cid) => Upload::Afresh, | ||
Some(_) => Upload::Again, | ||
} | ||
| @@ -357,7 +399,7 @@ impl Blobs { | ||
pub(crate) fn replay(&mut self, e: &Json) -> Result<(), String> { | ||
let Some(cid) = e["cid"].as_str() else { return Err(format!("a blob entry with no cid: {e}")) }; | ||
if e["t"] == "blobGone" { | ||
if !self.held.contains_key(cid) || self.refs.contains_key(cid) { | ||
if !self.held.contains_key(cid) || self.referenced(cid) { | ||
return Err(format!("an upload gone that was not held, or is referenced: {e}")); | ||
} | ||
self.set_held(cid, None); | ||
| @@ -403,8 +445,9 @@ impl Blobs { | ||
#[cfg(test)] | ||
pub(crate) fn snapshot(&self) -> String { | ||
let refs: BTreeMap<_, _> = self.refs.iter().collect(); | ||
let space_refs: BTreeMap<_, _> = self.space_refs.iter().collect(); | ||
let records: BTreeMap<_, _> = self.records.iter().collect(); | ||
format!("{:?}", (&self.held, refs, records, &self.unreferenced, self.bytes)) | ||
format!("{:?}", (&self.held, refs, space_refs, records, &self.unreferenced, self.bytes)) | ||
} | ||
} | ||
| ||
crates/pds-server/src/events.rs+5−1
| @@ -156,7 +156,11 @@ pub fn renumber(frame: &[u8], seq: u64) -> Result<Vec<u8>, String> { | ||
| ||
/// The current time as an atproto datetime, in UTC to the millisecond. | ||
pub fn timestamp() -> String { | ||
let ms = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as i64; | ||
datetime(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as i64) | ||
} | ||
| ||
/// A time, in milliseconds since the epoch, as an atproto datetime, in UTC to the millisecond. | ||
pub fn datetime(ms: i64) -> String { | ||
let (days, rem) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000)); | ||
// Civil date from days since 1970-01-01. | ||
let z = days + 719_468; | ||
crates/pds-server/src/federation.rs+1−1
| @@ -137,7 +137,7 @@ mod tests { | ||
Ok(Resp::Json(j) | Resp::Headed(j, _)) => panic!("{nsid} answered JSON: {j}"), | ||
Ok(Resp::Nothing) => panic!("{nsid} answered nothing"), | ||
Ok(Resp::Blob(_)) => panic!("{nsid} answered a blob"), | ||
Ok(Resp::Octets(_)) => panic!("{nsid} answered an archive"), | ||
Ok(Resp::Octets(_) | Resp::HeadedOctets(..)) => panic!("{nsid} answered an archive"), | ||
Err(e) => Err(e.name.to_string()), | ||
} | ||
} | ||
crates/pds-server/src/lib.rs+41−19
| @@ -8,14 +8,17 @@ | ||
//! `federation` (what a relay reads, and the crawlers the server tells), | ||
//! `identity` (handles), `blobs`, `invites`, `space_repo` (each account's | ||
//! space repos), `space_credentials` (spaces' delegation tokens, credentials | ||
//! and revocations) and `space_authority` (the spaces each account is the | ||
//! authority of, with who their policies authorize in `space_authz`); the | ||
//! firehose is `events`, the MCP endpoint `mcp`, the PLC directory `plc`, | ||
//! OAuth's authorization server `oauth`, OAuth access tokens on every method | ||
//! and what their scopes allow `scopes`, the single-use values OAuth spends | ||
//! `replay`, single-use values the spaces spend `single_use`, what keeps the | ||
//! server up when anyone may call it `limits`, and what the server keeps, how | ||
//! it starts again from it, and how it compacts it, `log` and `compact`. | ||
//! and revocations), `space_authority` (the spaces each account is the | ||
//! authority of, with who their policies authorize in `space_authz`) and | ||
//! `space_notify` (write notifications, the writer set, syncers' | ||
//! registrations and deletion notices); the firehose is `events`, the MCP | ||
//! endpoint `mcp`, the PLC directory `plc`, requests to URLs others name | ||
//! `outbound`, OAuth's authorization server `oauth`, OAuth access tokens on | ||
//! every method and what their scopes allow `scopes`, the single-use values | ||
//! OAuth spends `replay`, single-use values the spaces spend `single_use`, | ||
//! what keeps the server up when anyone may call it `limits`, and what the | ||
//! server keeps, how it starts again from it, and how it compacts it, `log` | ||
//! and `compact`. | ||
| ||
mod blobs; | ||
mod compact; | ||
| @@ -27,6 +30,7 @@ mod limits; | ||
mod log; | ||
mod mcp; | ||
mod oauth; | ||
mod outbound; | ||
mod plc; | ||
mod replay; | ||
mod repo; | ||
| @@ -38,6 +42,7 @@ mod single_use; | ||
mod space_credentials; | ||
mod space_authority; | ||
mod space_authz; | ||
mod space_notify; | ||
mod sync; | ||
| ||
use axum::{ | ||
| @@ -91,6 +96,8 @@ pub(crate) struct Config { | ||
pub did_cache: u64, | ||
/// How long after its input is checked `createSession` answers, at the soonest. | ||
pub login_floor: std::time::Duration, | ||
/// Whether requests to URLs others name are SSRF-protected (`PDS_DISABLE_SSRF_PROTECTION`). | ||
pub ssrf_protection: bool, | ||
} | ||
| ||
impl Config { | ||
| @@ -118,6 +125,7 @@ impl Config { | ||
min_free: limits::env_u64("PDS_MIN_FREE_BYTES", 256 << 20)?, | ||
did_cache: limits::env_u64("PDS_DID_CACHE_SECS", 3600)?, | ||
login_floor: std::time::Duration::from_millis(350), | ||
ssrf_protection: outbound::protection(std::env::var(outbound::DISABLE_VAR).ok().as_deref())?, | ||
}) | ||
} | ||
} | ||
| @@ -159,6 +167,9 @@ pub(crate) struct Store { | ||
pub spaces: space_repo::Spaces, | ||
/// The spaces it is the authority of (`spec/SPACES-POLICIES.md`), kept in the same log. | ||
pub authority: space_authority::Authority, | ||
/// Its write notifications waiting to be sent again, and the | ||
/// registrations and deletion notices of its spaces (`space_notify`). | ||
pub notify: space_notify::Kept, | ||
} | ||
| ||
/// Every account, by DID, handle and email. | ||
| @@ -220,6 +231,8 @@ pub(crate) struct Service { | ||
limits: limits::Limits, | ||
/// When `accounts.log` is next compacted. | ||
compaction: compact::Compaction, | ||
/// Write notifications and deletion notices being sent, and when next. | ||
space_notify: space_notify::Notify, | ||
} | ||
| ||
type Shared = Arc<Service>; | ||
| @@ -328,6 +341,9 @@ enum Resp { | ||
Headed(Json, Vec<(&'static str, String)>), | ||
/// Bytes as `application/octet-stream`, as a space meta archive. | ||
Octets(Vec<u8>), | ||
/// Bytes as `application/octet-stream`, with headers of their own, as a | ||
/// space repo's archive with its MAC. | ||
HeadedOctets(Vec<u8>, Vec<(&'static str, String)>), | ||
} | ||
| ||
/// An error as XRPC answers it: an HTTP status, a name and a message. | ||
| @@ -425,7 +441,7 @@ enum Handler { | ||
| ||
/// Each area's methods: what answers a method, by its NSID, if the area has it. | ||
const AREAS: &[fn(&str) -> Option<Handler>] = | ||
&[server::handler, sessions::handler, repo::handler, sync::handler, federation::handler, identity::handler, blobs::handler, invites::handler, space_repo::handler, space_credentials::handler, space_authority::handler]; | ||
&[server::handler, sessions::handler, repo::handler, sync::handler, federation::handler, identity::handler, blobs::handler, invites::handler, space_repo::handler, space_credentials::handler, space_authority::handler, space_notify::handler]; | ||
| ||
fn handler(nsid: &str) -> Option<Handler> { | ||
AREAS.iter().find_map(|area| area(nsid)) | ||
| @@ -449,6 +465,8 @@ pub fn run() { | ||
// Handle changes in flight when the server stopped are settled while it serves. | ||
identity::settle_unfinished(&svc); | ||
blobs::sweep_every(&svc); | ||
// Notifications kept when the server stopped are sent again when due. | ||
space_notify::start(&svc); | ||
limits::serve(listener, app).await; | ||
}); | ||
} | ||
| @@ -505,16 +523,9 @@ fn respond(answer: Result<Resp, XrpcError>, charged: Option<&limits::Charged>) - | ||
Ok(Resp::Car(b)) => (StatusCode::OK, [(header::CONTENT_TYPE, "application/vnd.ipld.car")], b).into_response(), | ||
Ok(Resp::Nothing) => StatusCode::OK.into_response(), | ||
Ok(Resp::Blob(b)) => blobs::response(b), | ||
Ok(Resp::Headed(j, headers)) => { | ||
let mut r = (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], j.to_string()).into_response(); | ||
for (name, value) in headers { | ||
if let Ok(v) = header::HeaderValue::from_str(&value) { | ||
r.headers_mut().append(header::HeaderName::from_static(name), v); | ||
} | ||
} | ||
r | ||
} | ||
Ok(Resp::Headed(j, headers)) => with_headers((StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], j.to_string()).into_response(), headers), | ||
Ok(Resp::Octets(b)) => (StatusCode::OK, [(header::CONTENT_TYPE, "application/octet-stream")], b).into_response(), | ||
Ok(Resp::HeadedOctets(b, headers)) => with_headers((StatusCode::OK, [(header::CONTENT_TYPE, "application/octet-stream")], b).into_response(), headers), | ||
Err(e) => ( | ||
StatusCode::from_u16(e.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), | ||
[(header::CONTENT_TYPE, "application/json")], | ||
| @@ -528,6 +539,16 @@ fn respond(answer: Result<Resp, XrpcError>, charged: Option<&limits::Charged>) - | ||
res | ||
} | ||
| ||
/// An answer with headers of its own added. | ||
fn with_headers(mut r: Response, headers: Vec<(&'static str, String)>) -> Response { | ||
for (name, value) in headers { | ||
if let Ok(v) = header::HeaderValue::from_str(&value) { | ||
r.headers_mut().append(header::HeaderName::from_static(name), v); | ||
} | ||
} | ||
r | ||
} | ||
| ||
/// Whether an error is a token's, which costs a call nothing of the rate limits. | ||
fn token_error(e: &XrpcError) -> bool { | ||
matches!(e.name, "AuthMissing" | "InvalidToken" | "ExpiredToken") | ||
| @@ -765,6 +786,7 @@ mod testing { | ||
min_free: 0, | ||
did_cache: 0, | ||
login_floor: std::time::Duration::ZERO, | ||
ssrf_protection: false, | ||
} | ||
} | ||
| ||
| @@ -801,7 +823,7 @@ mod testing { | ||
match answer(s, &call).await { | ||
Ok(Resp::Json(j) | Resp::Headed(j, _)) => Ok(j), | ||
Ok(Resp::Car(_)) => Err("a CAR file".into()), | ||
Ok(Resp::Octets(_)) => Err("bytes".into()), | ||
Ok(Resp::Octets(_) | Resp::HeadedOctets(..)) => Err("bytes".into()), | ||
Ok(Resp::Nothing) => Ok(Json::Null), | ||
Ok(Resp::Blob(_)) => Err("a blob".into()), | ||
Err(e) => Err(e.name.to_string()), | ||
crates/pds-server/src/limits.rs+7−0
| @@ -23,6 +23,8 @@ pub(crate) const MAX_RECORD_BODY: usize = 1_000_000; | ||
pub(crate) const MAX_BODY: usize = 153_600; | ||
/// The longest space meta archive `importSpaceMeta` reads. | ||
pub(crate) const MAX_ARCHIVE_BODY: usize = 16 * 1024 * 1024; | ||
/// The longest space repo archive `importRepo` reads, as an upload's. | ||
pub(crate) const MAX_REPO_ARCHIVE_BODY: usize = 5 * 1024 * 1024; | ||
/// The longest body `POST /mcp` takes. | ||
pub(crate) const MAX_MCP_BODY: usize = 1_048_576; | ||
/// The most writes one `applyWrites` may make. | ||
| @@ -68,6 +70,10 @@ const WRITES: &[&str] = &[ | ||
"com.atproto.space.deleteSpace", | ||
"com.atproto.space.removeWriter", | ||
"com.atproto.space.importSpaceMeta", | ||
"com.atproto.space.importRepo", | ||
"com.atproto.space.notifyWrite", | ||
"com.atproto.space.registerNotify", | ||
"com.atproto.space.unregisterNotify", | ||
"com.atproto.memberspace.putMember", | ||
"com.atproto.memberspace.removeMember", | ||
"com.atproto.space.getSpaceCredential", | ||
| @@ -80,6 +86,7 @@ pub(crate) fn body_limit(nsid: &str) -> usize { | ||
"com.atproto.repo.createRecord" | "com.atproto.repo.putRecord" | "com.atproto.repo.applyWrites" => MAX_RECORD_BODY, | ||
"com.atproto.space.createRecord" | "com.atproto.space.putRecord" | "com.atproto.space.applyWrites" => MAX_RECORD_BODY, | ||
"com.atproto.space.importSpaceMeta" => MAX_ARCHIVE_BODY, | ||
"com.atproto.space.importRepo" => MAX_REPO_ARCHIVE_BODY, | ||
_ => MAX_BODY, | ||
} | ||
} | ||
crates/pds-server/src/log.rs+136−13
| @@ -15,10 +15,12 @@ | ||
//! one frame with its firehose events, the blobs it stored and stopped | ||
//! holding, its handle changes: each recorded before its operation goes | ||
//! to the PLC directory, then settled, in one frame with its `#identity` | ||
//! event if it landed; its space repos' commits, each one frame | ||
//! (`space_repo`); and each change to the spaces it is the authority of, | ||
//! event if it landed; its space repos' commits and imports, each one | ||
//! frame (`space_repo`); each change to the spaces it is the authority of, | ||
//! one frame each (`space_authority::ENTRIES`), with the commits of the | ||
//! records it publishes and the repo it drops (`space_repo::DROP`); | ||
//! records it publishes and the repo it drops (`space_repo::DROP`); and its | ||
//! write notifications waiting to be sent again, and the registrations and | ||
//! deletion notices of its spaces (`space_notify::ENTRIES`); | ||
//! - `repos/<did>/blobs/<cid>`, the bytes of each blob it holds (`blobs`). | ||
//! | ||
//! An account's log, with its repository's first commit, is on disk before | ||
| @@ -226,6 +228,7 @@ fn open_repo(dir: &FsPath, a: &AccountEntry, files: &Arc<Files>) -> Result<Recov | ||
let mut blobs = Blobs::default(); | ||
let mut spaces = crate::space_repo::Spaces::default(); | ||
let mut authority = crate::space_authority::Authority::default(); | ||
let mut notify = crate::space_notify::Kept::default(); | ||
let mut have_commit = false; | ||
let mut handle = None; | ||
let mut pending: Option<crate::identity::Pending> = None; | ||
| @@ -279,9 +282,11 @@ fn open_repo(dir: &FsPath, a: &AccountEntry, files: &Arc<Files>) -> Result<Recov | ||
} | ||
} | ||
Some(t) if crate::blobs::ENTRIES.contains(&t) => blobs.replay(e).map_err(at)?, | ||
Some(crate::space_repo::ENTRY) => spaces.replay(e, &mut repo.tids).map_err(at)?, | ||
Some(crate::space_repo::DROP) => spaces.replay_drop(e).map_err(at)?, | ||
Some(crate::space_repo::ENTRY) => spaces.replay(e, &mut repo.tids, &mut blobs).map_err(at)?, | ||
Some(crate::space_repo::IMPORT) => spaces.replay_import(e, &mut repo.tids, &mut blobs).map_err(at)?, | ||
Some(crate::space_repo::DROP) => spaces.replay_drop(e, &mut blobs).map_err(at)?, | ||
Some(t) if crate::space_authority::ENTRIES.contains(&t) => authority.replay(e).map_err(at)?, | ||
Some(t) if crate::space_notify::ENTRIES.contains(&t) => notify.replay(e).map_err(at)?, | ||
t => return Err(at(format!("a log entry of no known type: {t:?}"))), | ||
} | ||
} | ||
| @@ -290,7 +295,7 @@ fn open_repo(dir: &FsPath, a: &AccountEntry, files: &Arc<Files>) -> Result<Recov | ||
} | ||
blobs.recover(&blob_dir(dir, &a.did))?; | ||
Ok(Recovered { | ||
store: Store { repo, wal: Arc::new(wal), blobs, spaces, authority }, | ||
store: Store { repo, wal: Arc::new(wal), blobs, spaces, authority, notify }, | ||
events, | ||
fresh: !have_commit, | ||
handle, | ||
| @@ -418,6 +423,7 @@ impl Service { | ||
let limits = crate::limits::Limits::new(dir, &config); | ||
sessions.prune(sessions.now()); | ||
let svc = Service { | ||
space_notify: crate::space_notify::Notify::new(config.ssrf_protection).map_err(|e| format!("an HTTP client: {e}"))?, | ||
config, | ||
dir: dir.to_path_buf(), | ||
log: Arc::new(log), | ||
| @@ -456,6 +462,7 @@ impl Service { | ||
d.insert(Arc::new(a.account(r.store, None))); | ||
} | ||
drop(d); | ||
crate::space_notify::resume(&svc); | ||
Ok(svc) | ||
} | ||
} | ||
| @@ -941,6 +948,15 @@ mod tests { | ||
drop(s); | ||
let accounts_log = PathBuf::from(ACCOUNTS_LOG); | ||
let work = scratch("torn-space-credentials-work"); | ||
// What a recovered server holds against what it should, at its own | ||
// time: a delegation token's value is held only a minute past its | ||
// issue, and a slow run may recover after that, rightly without it. | ||
let recovers_to = |want: &Held, why: String| { | ||
let s = open(&work, &plc); | ||
let now = s.sessions.now(); | ||
let live = |m: &BTreeMap<[u8; 32], u64>| m.iter().filter(|(_, t)| **t > now).map(|(k, t)| (*k, *t)).collect::<BTreeMap<_, _>>(); | ||
assert_eq!((s.single_use.snapshot(now), s.space_credentials.snapshot(now)), (live(&want.0), live(&want.1)), "{why}"); | ||
}; | ||
let mut kinds = Vec::new(); | ||
for w in steps.windows(2) { | ||
let changed: Vec<&PathBuf> = w[1].0.keys().filter(|p| w[0].0.get(*p) != w[1].0.get(*p)).collect(); | ||
| @@ -953,14 +969,13 @@ mod tests { | ||
let mut files = w[1].0.clone(); | ||
files.insert(accounts_log.clone(), whole[..cut].to_vec()); | ||
put_files(&work, &files); | ||
let want = if cut == to { &w[1].1 } else { &w[0].1 }; | ||
assert_eq!(&held(&open(&work, &plc)), want, "cut at {cut} of {from}..{to}"); | ||
recovers_to(if cut == to { &w[1].1 } else { &w[0].1 }, format!("cut at {cut} of {from}..{to}")); | ||
} | ||
for at in (from..to).step_by(3) { | ||
let mut files = w[1].0.clone(); | ||
files.get_mut(&accounts_log).unwrap()[at] ^= 0x55; | ||
put_files(&work, &files); | ||
assert_eq!(&held(&open(&work, &plc)), &w[0].1, "flip at {at} of {from}..{to}"); | ||
recovers_to(&w[0].1, format!("flip at {at} of {from}..{to}")); | ||
} | ||
} | ||
assert_eq!(kinds, [crate::single_use::ENTRY, crate::space_credentials::ENTRY]); | ||
| @@ -1074,6 +1089,87 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// Cut an account's `repo.log` at every byte of each frame the write | ||
/// notifications' part wrote (and flip a byte in it): recovery gives | ||
/// what it keeps (its retry queue, registrations and deletion notices) | ||
/// as before the frame or after it, and the log takes changes after. | ||
/// Each kind of entry is cut, and a malformed one is refused. | ||
#[tokio::test] | ||
async fn torn_space_notify_writes() { | ||
use crate::space_notify::{ENTRIES, tests as notify}; | ||
let plc = plc().await; | ||
let dir = scratch("torn-notify"); | ||
let s = open(&dir, &plc); | ||
let (alice, _) = create(&s, "alice").await; | ||
let log = repo_log(Path::new(""), &alice); | ||
let kept = |s: &Service| crate::read(&s.account(&alice).unwrap().store).notify.clone(); | ||
let (q, m) = ("at://did:plc:elsewhere/space/com.example.forum/q".to_string(), format!("at://{alice}/space/com.example.forum/m")); | ||
let mut steps = vec![(files(&dir), kept(&s))]; | ||
for frame in notify::frames_of_each_kind(&q, &m) { | ||
notify::keep(&s, &alice, &frame); | ||
steps.push((files(&dir), kept(&s))); | ||
} | ||
drop(s); | ||
let work = scratch("torn-notify-work"); | ||
let mut kinds = Vec::new(); | ||
for w in steps.windows(2) { | ||
let ((before_files, before), (after_files, after)) = (&w[0], &w[1]); | ||
let changed: Vec<&PathBuf> = after_files.keys().filter(|p| before_files.get(*p) != after_files.get(*p)).collect(); | ||
assert_eq!(changed, [&log]); | ||
assert_ne!(before, after); | ||
let whole = &after_files[&log]; | ||
let (from, to) = (before_files[&log].len(), whole.len()); | ||
kinds.extend(store::scan(&whole[from..]).0.iter().flatten().map(|e| e["t"].as_str().unwrap().to_string())); | ||
for cut in from..=to { | ||
let mut files = after_files.clone(); | ||
files.insert(log.clone(), whole[..cut].to_vec()); | ||
put_files(&work, &files); | ||
let want = if cut == to { after } else { before }; | ||
assert_eq!(&kept(&open(&work, &plc)), want, "cut at {cut} of {from}..{to}"); | ||
} | ||
for at in (from..to).step_by(3) { | ||
let mut files = after_files.clone(); | ||
files.get_mut(&log).unwrap()[at] ^= 0x55; | ||
put_files(&work, &files); | ||
assert_eq!(&kept(&open(&work, &plc)), before, "flip at {at} of {from}..{to}"); | ||
} | ||
} | ||
kinds.sort(); | ||
kinds.dedup(); | ||
let mut want: Vec<&str> = ENTRIES.to_vec(); | ||
want.sort(); | ||
assert_eq!(kinds.iter().map(String::as_str).collect::<Vec<_>>(), want); | ||
// After recovery from the last cut, the log takes changes, and replays them. | ||
let last = &steps.last().unwrap(); | ||
put_files(&work, &last.0); | ||
let s = open(&work, &plc); | ||
assert_eq!(&kept(&s), &last.1); | ||
notify::keep(&s, &alice, ¬ify::frames_of_each_kind(&q, &m)[0]); | ||
assert_eq!(kept(&open(&work, &plc)), kept(&s)); | ||
assert_ne!(kept(&s), last.1); | ||
drop(s); | ||
// A malformed entry of each kind is refused with a reason. | ||
let space = json!(q); | ||
for bad in [ | ||
json!({ "t": "notifyQueued", "space": space, "rev": "x", "data": "00", "n": 1, "due": 1, "until": 2 }), | ||
json!({ "t": "notifyQueued", "space": space, "rev": "3jzfcijpj2z2a", "data": "zz", "n": 1, "due": 1, "until": 2 }), | ||
json!({ "t": "notifyQueued", "space": space, "rev": "3jzfcijpj2z2a", "data": "00", "n": 1, "due": 1 }), | ||
json!({ "t": "notifyUnqueued", "space": "nope", "rev": "3jzfcijpj2z2a" }), | ||
json!({ "t": "notifyRegistered", "space": space, "service": "did:plc:x" }), | ||
json!({ "t": "notifyOwed", "space": space, "service": "did:plc:x", "n": -1, "due": 1, "until": 2 }), | ||
json!({ "t": "notifyPaid", "space": space }), | ||
] { | ||
let mut frames = store::scan(&last.0[&log]).0; | ||
frames.push(vec![bad.clone()]); | ||
let mut files = last.0.clone(); | ||
files.insert(log.clone(), frames.iter().flat_map(|f| store::frame(f)).collect()); | ||
put_files(&work, &files); | ||
assert!(try_open(&work, &plc).is_err(), "{bad}"); | ||
} | ||
let _ = std::fs::remove_dir_all(&dir); | ||
let _ = std::fs::remove_dir_all(&work); | ||
} | ||
| ||
/// An account's blobs, and the files of its blob directory. | ||
fn blob_state(s: &Service, dir: &Path, did: &str) -> (String, Vec<String>) { | ||
let held = crate::read(&s.account(did).unwrap().store).blobs.snapshot(); | ||
| @@ -1145,9 +1241,12 @@ mod tests { | ||
/// Cut the account's log at every byte of each space commit's frame (and | ||
/// flip a byte in it): recovery gives the space repos as before that | ||
/// commit or after it, the repository and the events as they were, and | ||
/// takes new space writes, which replay. | ||
/// takes new space writes, which replay. Each commit's notification goes | ||
/// to a space host that cannot be reached: the frames after the commit's | ||
/// keep it in the retry queue (`space_notify`), which this does not cut. | ||
#[tokio::test] | ||
async fn torn_space_writes_recover_to_before_or_after() { | ||
use crate::space_notify::tests::idle; | ||
use crate::space_repo::tests::{SPACE, w}; | ||
let plc = plc().await; | ||
let dir = scratch("torn-space-src"); | ||
| @@ -1155,6 +1254,14 @@ mod tests { | ||
let (a, ta) = create(&s, "alice").await; | ||
let (b, tb) = create(&s, "bob").await; | ||
let snap = |s: &Service| (files(&dir), with_spaces(s)); | ||
let w = |s: &crate::Shared, nsid: &'static str, token: &str, body: Json| { | ||
let (s, token) = (s.clone(), token.to_string()); | ||
async move { | ||
let got = w(&s, nsid, &token, body).await; | ||
idle(&s).await; | ||
got | ||
} | ||
}; | ||
let mut steps = vec![snap(&s)]; | ||
let rec = |did: &str, rkey: &str, n: i64| json!({ "space": SPACE, "repo": did, "collection": "a.b.c", "rkey": rkey, "record": record(n) }); | ||
w(&s, "createRecord", &ta, rec(&a, "one", 1)).await.unwrap(); | ||
| @@ -1172,6 +1279,19 @@ mod tests { | ||
steps.push(snap(&s)); | ||
w(&s, "clearRecords", &tb, json!({ "space": SPACE, "repo": b })).await.unwrap(); | ||
steps.push(snap(&s)); | ||
// An import of alice's own archive back: one frame, of one entry. | ||
let params = [("space".to_string(), SPACE.to_string()), ("repo".to_string(), a.clone())]; | ||
let archive = { | ||
let none = axum::http::HeaderMap::new(); | ||
let get = crate::Call { nsid: "com.atproto.space.getRepo", method: &axum::http::Method::GET, params: ¶ms, body: b"", bearer: sessions::Bearer::Token(&ta), headers: &none, client: "127.0.0.1".into(), charged: Default::default() }; | ||
let Ok(crate::Resp::HeadedOctets(archive, _)) = crate::answer(&s, &get).await else { panic!("getRepo answered no archive") }; | ||
archive | ||
}; | ||
let mut headers = axum::http::HeaderMap::new(); | ||
headers.insert(axum::http::header::CONTENT_TYPE, axum::http::HeaderValue::from_static("application/octet-stream")); | ||
let import = crate::Call { nsid: "com.atproto.space.importRepo", method: &axum::http::Method::POST, params: &[], body: &archive, bearer: sessions::Bearer::Token(&ta), headers: &headers, client: "127.0.0.1".into(), charged: Default::default() }; | ||
assert!(matches!(crate::answer(&s, &import).await, Ok(crate::Resp::Nothing))); | ||
steps.push(snap(&s)); | ||
// A refused write, or one making no commit, logs nothing. | ||
assert!(w(&s, "createRecord", &ta, rec(&a, "two", 6)).await.is_err()); | ||
w(&s, "deleteRecord", &ta, json!({ "space": SPACE, "repo": a, "collection": "a.b.c", "rkey": "none" })).await.unwrap(); | ||
| @@ -1187,10 +1307,12 @@ mod tests { | ||
// The repository and the events are as they were. | ||
assert_eq!(before.0, after.0); | ||
let whole = &after_files[path]; | ||
let (from, to) = (before_files[path].len(), whole.len()); | ||
let from = before_files[path].len(); | ||
let frames = store::scan(&whole[from..]).0; | ||
assert_eq!(frames.len(), 1); | ||
assert_eq!(frames[0].iter().map(|e| e["t"].as_str().unwrap()).collect::<Vec<_>>(), [crate::space_repo::ENTRY]); | ||
let kinds: Vec<&str> = frames[0].iter().map(|e| e["t"].as_str().unwrap()).collect(); | ||
assert!(kinds == [crate::space_repo::ENTRY] || kinds == [crate::space_repo::IMPORT], "{kinds:?}"); | ||
assert!(frames[1..].iter().flatten().all(|e| crate::space_notify::ENTRIES.contains(&e["t"].as_str().unwrap()))); | ||
let to = from + store::frame(&frames[0]).len(); | ||
for cut in from..=to { | ||
let mut files = after_files.clone(); | ||
files.insert(path.clone(), whole[..cut].to_vec()); | ||
| @@ -1202,6 +1324,7 @@ mod tests { | ||
if cut % 97 == 0 || cut == from + 1 || cut == to { | ||
let got = w(&s, "putRecord", &tb, rec(&b, "after", 9)).await.unwrap(); | ||
assert!(got["cid"].is_string()); | ||
idle(&s).await; | ||
assert_eq!(with_spaces(&open(&work, &plc)), with_spaces(&s), "step {i}: cut at {cut}"); | ||
} | ||
} | ||
crates/pds-server/src/mcp.rs+1−1
| @@ -278,7 +278,7 @@ async fn call_tool(st: &Shared, name: &str, arguments: Option<&Json>, authorizat | ||
Ok(_) if m.output.is_none() => (json!({}), false), | ||
Ok(Resp::Json(j) | Resp::Headed(j, _)) => (j, false), | ||
// No other method with a tool answers anything but JSON. | ||
Ok(Resp::Car(_) | Resp::Blob(_) | Resp::Nothing | Resp::Octets(_)) => (json!({ "error": "InternalServerError", "message": "a tool's method answered no JSON" }), true), | ||
Ok(Resp::Car(_) | Resp::Blob(_) | Resp::Nothing | Resp::Octets(_) | Resp::HeadedOctets(..)) => (json!({ "error": "InternalServerError", "message": "a tool's method answered no JSON" }), true), | ||
Err(e) => (json!({ "error": e.name, "message": e.message }), true), | ||
}; | ||
Ok(json!({ | ||
crates/pds-server/src/outbound.rsnew+189−0
| @@ -0,0 +1,189 @@ | ||
//! Requests the server sends to URLs others name, with SSRF protection | ||
//! (`spec/PROXY.md`, "SSRF protection"): unless `PDS_DISABLE_SSRF_PROTECTION` | ||
//! turns it off, only to an `https` URL whose host is no IP address outside | ||
//! unicast and resolves only to unicast addresses. Names are resolved, and | ||
//! checked, by the client's own resolver, as the connection is made, so a | ||
//! name cannot be checked as one address and reached at another. Redirects | ||
//! are not followed. | ||
| ||
use reqwest::dns::{Addrs, Name, Resolve, Resolving}; | ||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; | ||
use std::sync::Arc; | ||
use std::time::Duration; | ||
| ||
/// The variable that turns SSRF protection off. | ||
pub(crate) const DISABLE_VAR: &str = "PDS_DISABLE_SSRF_PROTECTION"; | ||
| ||
/// Whether SSRF protection is on, as the variable's value says: `true` or | ||
/// `1` turn it off; `false`, `0`, empty or unset leave it on; any other | ||
/// value is an error, which makes `pds serve` exit 1. | ||
pub(crate) fn protection(value: Option<&str>) -> Result<bool, String> { | ||
match value { | ||
None | Some("" | "false" | "0") => Ok(true), | ||
Some("true" | "1") => Ok(false), | ||
Some(v) => Err(format!("{DISABLE_VAR} must be true, false, 1, 0 or empty, not {v:?}")), | ||
} | ||
} | ||
| ||
/// An HTTP client for URLs others name, and whether it is SSRF-protected. | ||
pub(crate) struct Outbound { | ||
client: reqwest::Client, | ||
protect: bool, | ||
} | ||
| ||
impl Outbound { | ||
pub fn new(protect: bool) -> reqwest::Result<Outbound> { | ||
let mut b = reqwest::Client::builder() | ||
.no_proxy() | ||
.pool_max_idle_per_host(0) | ||
.redirect(reqwest::redirect::Policy::none()) | ||
.connect_timeout(Duration::from_secs(5)) | ||
.timeout(Duration::from_secs(15)); | ||
if protect { | ||
b = b.https_only(true).dns_resolver(Arc::new(UnicastOnly)); | ||
} | ||
Ok(Outbound { client: b.build()?, protect }) | ||
} | ||
| ||
pub fn protects(&self) -> bool { | ||
self.protect | ||
} | ||
| ||
/// `url`, parsed, if a request may be sent to it: any `http` or `https` | ||
/// URL without protection; with it, only `https`, and not to a host | ||
/// that is an IP address outside unicast (a name's addresses are | ||
/// checked as it is resolved). | ||
pub fn permits(&self, url: &str) -> Option<reqwest::Url> { | ||
let u = reqwest::Url::parse(url).ok()?; | ||
let allowed = match (u.scheme(), u.host_str()) { | ||
(_, None) => false, | ||
("http", Some(_)) => !self.protect, | ||
("https", Some(host)) => !self.protect || host.trim_start_matches('[').trim_end_matches(']').parse::<IpAddr>().map_or(true, unicast), | ||
_ => false, | ||
}; | ||
allowed.then_some(u) | ||
} | ||
| ||
/// The client: requests through it are checked as they connect. | ||
pub fn client(&self) -> &reqwest::Client { | ||
&self.client | ||
} | ||
} | ||
| ||
/// Resolves a name only if every address it has is unicast. | ||
struct UnicastOnly; | ||
| ||
impl Resolve for UnicastOnly { | ||
fn resolve(&self, name: Name) -> Resolving { | ||
Box::pin(async move { | ||
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((name.as_str(), 0)).await?.collect(); | ||
if addrs.is_empty() || addrs.iter().any(|a| !unicast(a.ip())) { | ||
return Err(format!("{} resolves to an address SSRF protection refuses", name.as_str()).into()); | ||
} | ||
Ok(Box::new(addrs.into_iter()) as Addrs) | ||
}) | ||
} | ||
} | ||
| ||
/// Whether an address is a public unicast one: not unspecified, loopback, | ||
/// private, shared, link-local, multicast, broadcast, reserved or for | ||
/// documentation. | ||
pub(crate) fn unicast(ip: IpAddr) -> bool { | ||
match ip { | ||
IpAddr::V4(v4) => unicast_v4(v4), | ||
IpAddr::V6(v6) => match v6.to_ipv4_mapped() { | ||
Some(v4) => unicast_v4(v4), | ||
None => unicast_v6(v6), | ||
}, | ||
} | ||
} | ||
| ||
fn unicast_v4(ip: Ipv4Addr) -> bool { | ||
let [a, b, ..] = ip.octets(); | ||
!(ip.is_unspecified() | ||
|| ip.is_loopback() | ||
|| ip.is_private() | ||
|| ip.is_link_local() | ||
|| ip.is_multicast() | ||
|| ip.is_broadcast() | ||
|| ip.is_documentation() | ||
|| a == 0 | ||
|| a >= 240 | ||
|| (a == 100 && (64..128).contains(&b)) | ||
|| (a == 192 && b == 0 && ip.octets()[2] == 0) | ||
|| (a == 198 && (b == 18 || b == 19))) | ||
} | ||
| ||
fn unicast_v6(ip: Ipv6Addr) -> bool { | ||
let [first, second, ..] = ip.segments(); | ||
!(ip.is_unspecified() | ||
|| ip.is_loopback() | ||
|| ip.is_multicast() | ||
|| (first & 0xfe00) == 0xfc00 | ||
|| (first & 0xffc0) == 0xfe80 | ||
|| (first & 0xffc0) == 0xfec0 | ||
|| (first == 0x2001 && second == 0x0db8)) | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
#[test] | ||
fn the_variable() { | ||
for (v, want) in [(None, Ok(true)), (Some(""), Ok(true)), (Some("false"), Ok(true)), (Some("0"), Ok(true)), (Some("true"), Ok(false)), (Some("1"), Ok(false))] { | ||
assert_eq!(protection(v), want, "{v:?}"); | ||
} | ||
for v in ["yes", "TRUE", "False", " true", "2", "off"] { | ||
assert!(protection(Some(v)).is_err(), "{v}"); | ||
} | ||
} | ||
| ||
#[test] | ||
fn addresses() { | ||
for ok in ["93.184.216.34", "8.8.8.8", "2606:4700::1111", "::ffff:8.8.8.8"] { | ||
assert!(unicast(ok.parse().unwrap()), "{ok}"); | ||
} | ||
for bad in [ | ||
"127.0.0.1", "0.0.0.0", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "224.0.0.1", | ||
"255.255.255.255", "240.0.0.1", "192.0.2.1", "198.18.0.1", "::1", "::", "fc00::1", "fd12::1", "fe80::1", "ff02::1", | ||
"::ffff:127.0.0.1", "::ffff:10.0.0.1", "2001:db8::1", | ||
] { | ||
assert!(!unicast(bad.parse().unwrap()), "{bad}"); | ||
} | ||
} | ||
| ||
#[test] | ||
fn urls() { | ||
let on = Outbound::new(true).unwrap(); | ||
let off = Outbound::new(false).unwrap(); | ||
for url in ["https://example.com/x", "https://8.8.8.8/", "https://[2606:4700::1111]/"] { | ||
assert!(on.permits(url).is_some() && off.permits(url).is_some(), "{url}"); | ||
} | ||
for url in ["http://example.com/", "https://127.0.0.1/", "https://[::1]:8080/", "https://10.0.0.1/", "http://localhost:2583/"] { | ||
assert!(on.permits(url).is_none(), "{url}"); | ||
} | ||
for url in ["http://localhost:2583/", "http://127.0.0.1/"] { | ||
assert!(off.permits(url).is_some(), "{url}"); | ||
} | ||
for url in ["ftp://example.com/", "not a url", "file:///etc/passwd"] { | ||
assert!(on.permits(url).is_none() && off.permits(url).is_none(), "{url}"); | ||
} | ||
} | ||
| ||
/// With protection, a name that resolves to loopback is refused as the | ||
/// request connects; without, it is reached. | ||
#[tokio::test] | ||
async fn names_are_checked_as_they_resolve() { | ||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); | ||
let port = listener.local_addr().unwrap().port(); | ||
let app = axum::Router::new().route("/", axum::routing::get(|| async { "ok" })); | ||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); | ||
let off = Outbound::new(false).unwrap(); | ||
assert_eq!(off.client().get(format!("http://localhost:{port}/")).send().await.unwrap().status(), 200); | ||
let resolved = UnicastOnly.resolve("localhost".parse().unwrap()).await; | ||
assert!(resolved.is_err()); | ||
let on = Outbound::new(true).unwrap(); | ||
assert!(on.client().get(format!("https://localhost:{port}/")).send().await.is_err()); | ||
} | ||
} | ||
crates/pds-server/src/scopes.rs+8−0
crates/pds-server/src/server.rs+8−1
crates/pds-server/src/space_authority.rs+21−9
crates/pds-server/src/space_authz.rs+33−28
crates/pds-server/src/space_credentials.rs+3−2
crates/pds-server/src/space_notify.rsnew+784−0
784 lines changed: not loaded until asked for.
crates/pds-server/src/space_repo.rs+652−59
711 lines changed: not loaded until asked for.
crates/pds-space/src/star.rs+31−16
harness/spaces/compare.mjs+14−3
harness/spaces/export.mjsnew+571−0
571 lines changed: not loaded until asked for.
harness/spaces/repo.mjs+42−17
harness/spaces/sync.mjsnew+660−0
660 lines changed: not loaded until asked for.