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

Hardening, second pass: SSRF everywhere, OAuth sign-in limits and 2FA, bounded OAuth and outbound state, account state on OAuth and spaces

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:harden2-s
crates/pds-server/src/oauth/clients/silent.rs+9−3
@@ -24,7 +24,11 @@ pub(in super::super) type SentBack = (Vec<Json>, Vec<(&'static str, String)>);
/// What the page does with request `id`, `r`, of a confidential client,
/// loaded on `device`, whose `login_hint` names the account `hinted`, if
/// any here: None to show the page.
/// any here: None to show the page. `deactivated` says of each account
/// signed in on the device whether it is deactivated, or None if the page
/// does not list it (taken down, or gone): only those it lists count, and
/// a deactivated one is not a hinted one (`spec/LIFECYCLE.md`).
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn decide(
st: &State,
issuer: &str,
@@ -32,10 +36,12 @@ pub(in super::super) fn decide(
r: &Request,
device: &str,
hinted: Option<&str>,
deactivated: &dyn Fn(&str) -> Option<bool>,
now: u64,
) -> Option<SentBack> {
let signed_in = st.signed_in(device);
let hinted: Vec<&(String, u64)> = signed_in.iter().filter(|(d, _)| Some(d.as_str()) == hinted).collect();
let listed: Vec<(String, u64)> = st.signed_in(device).iter().filter(|(d, _)| deactivated(d).is_some()).cloned().collect();
let signed_in = &listed;
let hinted: Vec<&(String, u64)> = signed_in.iter().filter(|(d, _)| Some(d.as_str()) == hinted && deactivated(d) == Some(false)).collect();
let refuse = |error: &str, description: &str| {
let params = vec![("iss", issuer.to_string()), ("state", r.state.clone()), ("error", error.to_string()), ("error_description", description.to_string())];
Some((vec![json!({ "t": "oauthEndRequest", "id": id })], params))
crates/pds-server/src/oauth/clients/tests.rs+71−0
@@ -964,3 +964,74 @@ async fn restarts_keep_bindings_and_approvals_but_no_documents() {
drop(srv);
let _ = std::fs::remove_dir_all(&dir);
}
/// Silent sign-in looks only at the accounts the page lists: a taken-down
/// one is never approved without asking, nor counted; a deactivated one is
/// listed but not hinted. A deactivation with an OAuth token forgets the
/// clients the account approved, after a restart too (`spec/LIFECYCLE.md`).
#[tokio::test]
async fn silent_sign_in_and_account_states() {
use crate::oauth::tests::admin_status;
use crate::testing::call;
let (dir, srv, web, plc) = setup("oauth-clients-states").await;
let alice = srv.svc.account("alice.test").unwrap().did.clone();
let token = crate::testing::session(&srv.svc, "alice").await;
let k = ClientKey::new("k1");
let full = "atproto account:status?action=manage";
let id = confidential(&web, &[&k], json!({ "scope": full }));
let mut browser = Browser::new(&srv);
let push = async |prompt: Option<&str>, hint: Option<&str>, scope: &str| {
let mut a = app(&srv, &id, scope);
let assertion = good(&srv, &id, &k);
let (g, p) = a.par(&[("client_assertion_type", Some(ASSERTION_TYPE)), ("client_assertion", Some(&assertion)), ("prompt", prompt), ("login_hint", hint)]).await;
assert_eq!(g.status, 201, "{}", g.body);
(a, p)
};
// Alice signs in on this device, remembered, and approves the client: an OAuth session.
let consented = async |browser: &mut Browser<'_>, sign_in: bool| {
let (mut a, p) = push(None, None, full).await;
assert_eq!(browser.page(&id, &p.request_uri).await.status, 200);
if sign_in {
browser.api(&id, &p.request_uri, "sign-in", json!({ "locale": "en", "identifier": "alice.test", "password": "alice-pw", "remember": true }), None).await;
}
let consent = browser.api(&id, &p.request_uri, "consent", json!({ "did": alice }), None).await;
let url = url::Url::parse(consent.json()["url"].as_str().unwrap()).unwrap();
let code = url.query_pairs().find(|(k, _)| k == "code").map(|(_, v)| v.into_owned()).expect("a code");
let t = exchange(&srv, &mut a, &p, &code, Some(&k)).await.json();
(a, t)
};
let silent = async |browser: &mut Browser<'_>, prompt: Option<&str>| {
let (_, p) = push(prompt, Some("alice.test"), "atproto").await;
browser.page(&id, &p.request_uri).await
};
consented(&mut browser, true).await;
assert!(sent_back(&silent(&mut browser, Some("none")).await).contains_key("code"));
// Deactivated: listed, but not hinted.
call(&srv.svc, "com.atproto.server.deactivateAccount", Some(&token), json!({})).await.unwrap();
assert_eq!(sent_back(&silent(&mut browser, Some("none")).await)["error"], "login_required");
let page = silent(&mut browser, None).await;
assert_eq!((page.status, page.page("__sessions").unwrap().as_array().unwrap().len()), (200, 1));
call(&srv.svc, "com.atproto.server.activateAccount", Some(&token), Json::Null).await.unwrap();
assert!(sent_back(&silent(&mut browser, Some("none")).await).contains_key("code"));
// Taken down: neither approved nor counted.
admin_status(&srv.svc, &alice, json!({ "takedown": { "applied": true } })).await.unwrap();
assert_eq!(sent_back(&silent(&mut browser, Some("none")).await)["error"], "login_required");
assert_eq!(silent(&mut browser, None).await.status, 200);
let (_, p) = push(Some("select_account"), None, "atproto").await;
assert_eq!(sent_back(&browser.page(&id, &p.request_uri).await)["error"], "account_selection_required");
admin_status(&srv.svc, &alice, json!({ "takedown": { "applied": false } })).await.unwrap();
assert!(sent_back(&silent(&mut browser, Some("none")).await).contains_key("code"));
// A deactivation with an OAuth token forgets the clients she approved.
let (mut a, t) = consented(&mut browser, false).await;
assert!(srv.svc.oauth.snapshot().approved.contains_key(&alice));
assert_eq!(a.post("com.atproto.server.deactivateAccount", &t["access_token"].as_str().unwrap().to_string(), json!({})).await.status, 200);
assert!(!srv.svc.oauth.snapshot().approved.contains_key(&alice));
call(&srv.svc, "com.atproto.server.activateAccount", Some(&token), Json::Null).await.unwrap();
assert_eq!(sent_back(&silent(&mut browser, Some("none")).await)["error"], "consent_required");
let kept = srv.svc.oauth.snapshot();
drop(srv);
let srv = serve(open(&dir, &plc, &web)).await;
assert_eq!(srv.svc.oauth.snapshot(), kept);
assert!(!kept.approved.contains_key(&alice));
let _ = std::fs::remove_dir_all(&dir);
}
crates/pds-server/src/oauth/dpop.rs+92−9
@@ -15,6 +15,10 @@ pub(crate) const ALGS: &[&str] = &["ES256", "ES256K"];
/// How long a proof's `jti` is held: longer than any `iat` it may carry is taken.
const JTI_LIFE: u64 = 200;
/// The namespace of the single-use values proofs' `jti`s are kept in.
const NS: &str = "dpop";
/// The most proofs held in memory alone; past that the oldest are forgotten.
pub(crate) const MEMORY_MAX: usize = 1_000_000;
/// How far before the server's clock a proof's `iat` may be, and after.
const IAT_BEFORE: f64 = 190.0;
const IAT_AFTER: f64 = 180.0;
@@ -45,9 +49,83 @@ impl Refusal {
}
}
/// A proof that passed: its key's thumbprint.
/// A proof that passed: its key's thumbprint, and its `jti`, spent in
/// memory and to be kept (`keep`) once its request passes its token or grant.
pub(crate) struct Proof {
pub jkt: String,
jti: String,
until: u64,
}
/// The entry that keeps a proof's `jti` durably, once its request passed the
/// check of its token or grant; None if it is kept already, by a request
/// that carried the same proof while it was forgotten in memory: then it is
/// replayed.
pub(crate) fn keep(svc: &Service, proof: &Proof, now: u64) -> Option<Json> {
svc.replay.claim(NS, &proof.jti, now, proof.until)
}
/// Proofs spent, held in memory: every proof that passes checks 1 to 4, from
/// when it is spent until its time passes, at most `max` of them, the oldest
/// forgotten first. Those whose requests passed are kept durably too
/// (`keep`); the others are held here alone, and not across a restart.
/// A `jti` is held by the first 16 bytes of its SHA-256.
pub(crate) struct Spent {
until: std::collections::HashMap<[u8; 16], u64>,
/// The same, in the order they were spent; an entry whose time is not
/// the one `until` holds for it is stale, and passed over.
order: std::collections::VecDeque<([u8; 16], u64)>,
max: usize,
}
impl Default for Spent {
fn default() -> Spent {
Spent::new(MEMORY_MAX)
}
}
impl Spent {
pub fn new(max: usize) -> Spent {
Spent { until: Default::default(), order: Default::default(), max }
}
fn key(jti: &str) -> [u8; 16] {
let d = Sha256::digest(jti.as_bytes());
let mut k = [0; 16];
k.copy_from_slice(&d[..16]);
k
}
/// Spend `jti` at `now` until `until`: false if it is held already.
pub fn spend(&mut self, jti: &str, now: u64, until: u64) -> bool {
let k = Spent::key(jti);
while let Some(&(old, t)) = self.order.front()
&& t <= now
{
self.order.pop_front();
if self.until.get(&old) == Some(&t) {
self.until.remove(&old);
}
}
if self.until.get(&k).is_some_and(|t| *t > now) {
return false;
}
while self.until.len() >= self.max {
let Some((old, t)) = self.order.pop_front() else { break };
if self.until.get(&old) == Some(&t) {
self.until.remove(&old);
}
}
self.until.insert(k, until);
self.order.push_back((k, until));
true
}
/// How many proofs are held.
#[cfg(test)]
pub fn len(&self) -> usize {
self.until.len()
}
}
/// A public key a proof, or a client assertion, is signed with.
@@ -123,14 +201,19 @@ impl OAuth {
let n = now / NONCE_PERIOD;
[n.saturating_sub(1), n, n + 1].iter().any(|p| self.nonce_of(*p) == nonce)
}
/// Spend a proof's `jti` in memory: false if it is held there already.
fn spend_proof(&self, jti: &str, now: u64, until: u64) -> bool {
self.proofs.lock().unwrap_or_else(std::sync::PoisonError::into_inner).spend(jti, now, until)
}
}
/// Check a request's DPoP proof, as `spec/OAUTH.md` orders the checks: None
/// if it has no `DPoP` header. `path` is the request's; `ath`, at XRPC, the
/// access token the proof must name, and at the OAuth endpoints none. A
/// proof that passes all but its `jti` is spent: the entry that keeps it is
/// pushed to `spent`, to log.
pub(crate) fn check(svc: &Service, headers: &HeaderMap, method: &str, path: &str, ath_of: Option<&str>, spent: &mut Vec<Json>) -> Result<Option<Proof>, Refusal> {
/// proof that passes all but its `jti` is spent, in memory: the caller
/// keeps it durably (`keep`) once its request passes its token or grant.
pub(crate) fn check(svc: &Service, headers: &HeaderMap, method: &str, path: &str, ath_of: Option<&str>) -> Result<Option<Proof>, Refusal> {
let invalid = |why: &str| Err(Refusal::Invalid(why.to_string()));
let mut all = headers.get_all("dpop").iter();
let Some(value) = all.next() else { return Ok(None) };
@@ -202,10 +285,10 @@ pub(crate) fn check(svc: &Service, headers: &HeaderMap, method: &str, path: &str
if !right {
return invalid("DPoP proof ath is not the access token's");
}
// 5. Never used before.
match svc.replay.claim("dpop", jti, now, now + JTI_LIFE) {
Some(e) => spent.push(e),
None => return invalid("DPoP proof jti was used before"),
// 5. Never used before: kept durably, or held in memory.
let until = now + JTI_LIFE;
if svc.replay.holds(NS, jti, now) || !svc.oauth.spend_proof(jti, now, until) {
return invalid("DPoP proof jti was used before");
}
Ok(Some(Proof { jkt: thumbprint(jwk) }))
Ok(Some(Proof { jkt: thumbprint(jwk), jti: jti.to_string(), until }))
}
crates/pds-server/src/oauth/page.rs+223−59
@@ -7,9 +7,11 @@
use super::{
EPHEMERAL_LIFE, REQUEST_LIFE, REQUEST_URI, Request, State, Tx, client, clients, finish, json_response, new_id, scope, set,
};
use crate::email::Purpose::AuthFactor;
use crate::{Account, Service, Shared};
use axum::{
body::Bytes,
Extension,
body::Body,
extract::{Path, State as AxState},
http::{HeaderMap, Method, StatusCode, Uri, header},
response::{IntoResponse, Response},
@@ -20,6 +22,9 @@ const DEVICE_COOKIE: &str = "device-id";
const CSRF_COOKIE: &str = "csrf-token";
/// How long a device cookie lasts in the browser.
const DEVICE_COOKIE_LIFE: u64 = 365 * 24 * 60 * 60;
/// How long after a device was last given new cookies a browser sending
/// old ones is still that device.
const DEVICE_GRACE: u64 = 30;
/// A header's value as text, if it has one.
fn header_text<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> {
@@ -41,23 +46,46 @@ fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
cookies(headers).into_iter().find(|(k, _)| k == name).map(|(_, v)| v)
}
/// The device a request is from, and whether it is new: one whose cookie
/// the server did not seal is.
fn device(svc: &Service, headers: &HeaderMap) -> (String, bool) {
let sealed = cookie(headers, DEVICE_COOKIE).and_then(|c| svc.oauth.unseal("device", &c));
match sealed.and_then(|d| d["id"].as_str().map(str::to_string)) {
Some(id) => (id, false),
None => (new_id(16), true),
/// The device a request is from, and the key of the cookies to give it, if
/// it is to be given any.
struct Device {
id: String,
give: Option<String>,
}
impl Device {
fn new() -> Device {
Device { id: new_id(16), give: Some(new_id(16)) }
}
}
/// The device a request is from (`spec/OAUTH.md`, "Devices"). A browser
/// sending no cookie the server sealed is a new one; one sending its
/// device's current cookies is that device, and so is one sending old ones
/// within `DEVICE_GRACE` of the device's last new ones, given those. One
/// sending old ones after that ends the device, every account signed out of
/// it, logged in `tx`, and is a new one.
fn device(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap) -> Device {
let sealed = cookie(headers, DEVICE_COOKIE).and_then(|c| svc.oauth.unseal("device", &c));
let Some((id, key)) = sealed.and_then(|d| Some((d["id"].as_str()?.to_string(), d["key"].as_str().unwrap_or_default().to_string()))) else {
return Device::new();
};
tx.change(|st, now| match st.device_keys.get(&id) {
None => (vec![], Device { id, give: None }),
Some((current, _)) if *current == key => (vec![], Device { id, give: None }),
Some((current, at)) if now.saturating_sub(*at) <= DEVICE_GRACE => (vec![], Device { give: Some(current.clone()), id }),
Some(_) => (vec![json!({ "t": "oauthDeviceEnd", "device": id })], Device::new()),
})
}
fn secure(svc: &Service) -> &'static str {
if svc.oauth.issuer.starts_with("https:") { "; Secure" } else { "" }
}
/// Give a new device its cookie.
fn device_cookie(svc: &Service, r: &mut Response, id: &str) {
let value = svc.oauth.seal("device", &json!({ "id": id }));
/// Give a device the cookies it is to be given.
fn device_cookie(svc: &Service, r: &mut Response, device: &Device) {
let Some(key) = &device.give else { return };
let value = svc.oauth.seal("device", &json!({ "id": device.id, "key": key }));
let c = format!("{DEVICE_COOKIE}={value}; Path=/; Max-Age={DEVICE_COOKIE_LIFE}; HttpOnly; SameSite=Lax{}", secure(svc));
if let Ok(v) = c.parse() {
r.headers_mut().append(header::SET_COOKIE, v);
@@ -218,40 +246,53 @@ pub(super) async fn authorize(AxState(svc): AxState<Shared>, method: Method, hea
Ok(c) => c,
Err(e) => return error_page(400, e, "Invalid client_id"),
};
let (device, new_device) = device(&svc, &headers);
let mut tx = Tx::new(&svc);
let device = device(&svc, &mut tx, &headers);
let device_id = device.id.clone();
// The account a confidential client's request hints, if it is one here.
let hinted = client.keys.as_ref().and_then(|_| {
let hint = svc.oauth.lock().requests.get(id)?.login_hint.clone()?;
svc.account(&hint).map(|a| a.did.clone())
});
let mut tx = Tx::new(&svc);
let loaded = tx.change(|st, now| {
let load = |st: &State, now: u64| {
let Some(r) = st.requests.get(id) else { return (vec![], Err(None)) };
if r.approval.is_some() || now >= r.expires || r.client_id != client_id || r.device.as_ref().is_some_and(|d| *d != device) {
if r.approval.is_some() || now >= r.expires || r.client_id != client_id || r.device.as_ref().is_some_and(|d| *d != device_id) {
let back = error_params(&svc, r, "access_denied", "This request can no longer be used");
return (vec![json!({ "t": "oauthEndRequest", "id": id })], Err(Some((r.clone(), back))));
}
// A confidential client's request may be answered at once (`spec/OAUTH-CLIENTS.md`).
// A confidential client's request may be answered at once
// (`spec/OAUTH-CLIENTS.md`), by an account the page lists: its
// state read under OAuth's lock, which a change of it takes first.
let deactivated = |did: &str| {
let a = svc.account(did)?;
let state = crate::read(&a.state);
state.takedown.is_none().then_some(state.deactivated)
};
if client.keys.is_some()
&& let Some((entries, back)) = clients::silent::decide(st, &svc.oauth.issuer, id, r, &device, hinted.as_deref(), now)
&& let Some((entries, back)) = clients::silent::decide(st, &svc.oauth.issuer, id, r, &device_id, hinted.as_deref(), &deactivated, now)
{
return (entries, Err(Some((r.clone(), back))));
}
let load = json!({ "t": "oauthLoad", "id": id, "device": device, "expires": now + REQUEST_LIFE });
(vec![load], Ok(Loaded { request: r.clone(), signed_in: st.signed_in(&device).to_vec() }))
let load = json!({ "t": "oauthLoad", "id": id, "device": device_id, "expires": now + REQUEST_LIFE });
(vec![load], Ok(Loaded { request: r.clone(), signed_in: st.signed_in(&device_id).to_vec() }))
};
let low = super::low(&svc);
// Below the free-space floor, a load that would keep something is refused (None).
let loaded = tx.change(|st, now| {
let (entries, loaded) = load(st, now);
if low && !entries.is_empty() { (vec![], None) } else { (entries, Some(loaded)) }
});
if !tx.done().await {
return error_page(500, "server_error", "Internal server error");
}
let Some(loaded) = loaded else { return error_page(507, "temporarily_unavailable", "Not enough free space to store this") };
let loaded = match loaded {
Ok(l) => l,
Err(None) => return bad_page("Unknown or ended request"),
Err(Some((r, back))) => return redirect_to(&r.response_mode, &r.redirect_uri, &back),
};
let mut r = authorization_page(&svc, request_uri, &client, &loaded);
if new_device {
device_cookie(&svc, &mut r, &device);
}
device_cookie(&svc, &mut r, &device);
let csrf = format!("{CSRF_COOKIE}={}; Path=/; SameSite=Lax{}", hex::encode(rand::random::<[u8; 16]>()), secure(&svc));
if let Ok(v) = csrf.parse() {
r.headers_mut().append(header::SET_COOKIE, v);
@@ -445,7 +486,14 @@ fn body_of(fields: &[(&str, Field, bool)], body: &[u8]) -> Result<Map<String, Js
}
/// `POST /@atproto/oauth-provider/~api/<endpoint>`.
pub(super) async fn api(AxState(svc): AxState<Shared>, Path(endpoint): Path<String>, method: Method, headers: HeaderMap, body: Bytes) -> Response {
pub(super) async fn api(
AxState(svc): AxState<Shared>,
Path(endpoint): Path<String>,
method: Method,
headers: HeaderMap,
peer: Option<Extension<crate::limits::Peer>>,
body: Body,
) -> Response {
let Some(fields) = fields(&endpoint).filter(|_| method == Method::POST) else {
return json_response(404, &json!({ "error": "invalid_request", "error_description": "Not found" }));
};
@@ -464,30 +512,45 @@ pub(super) async fn api(AxState(svc): AxState<Shared>, Path(endpoint): Path<Stri
if essence.as_deref() != Some("application/json") {
return api_error(415, "Content-Type must be application/json");
}
let body = match super::read_body(&headers, body, super::BODY_MAX).await {
Ok(body) => body,
Err(413) => return api_error(413, "Request body too large"),
Err(status) => return api_error(status, "The body could not be read"),
};
let b = match body_of(fields, &body) {
Ok(b) => b,
Err(why) => return api_error(400, &why),
};
// A sign-in answers no sooner than this, whatever it answers.
let floor = (endpoint == "sign-in").then(|| tokio::time::Instant::now() + svc.config.sign_in_floor);
let client = crate::limits::client(&svc.config.trusted_proxies, &headers, peer.map(|Extension(p)| p.0));
finish(async move {
let (device, new_device) = device(&svc, &headers);
let mut tx = Tx::new(&svc);
let mut device = device(&svc, &mut tx, &headers);
let answer = match endpoint.as_str() {
"sign-in" => sign_in(&svc, &mut tx, &device, &request_id, &b).await,
"consent" => consent(&svc, &mut tx, &headers, &device, &request_id, &b).await,
"sign-in" => sign_in(&svc, &mut tx, &mut device, &request_id, &client, &b).await,
"consent" => consent(&svc, &mut tx, &headers, &device.id, &request_id, &b).await,
"reject" => reject(&svc, &mut tx, &request_id),
_ => sign_out(&mut tx, &device, &b),
_ => sign_out(&mut tx, &device.id, &b).map_err(Refusal::from),
};
if let Some(floor) = floor {
tokio::time::sleep_until(floor).await;
}
if !tx.done().await {
return json_response(500, &json!({ "error": "server_error", "error_description": "Internal server error" }));
}
let mut r = match answer {
Ok(j) => json_response(200, &j),
Err(why) => json_response(400, &json!({ "error": "invalid_request", "error_description": why })),
Err(no) => {
let mut r = json_response(no.status, &json!({ "error": no.error, "error_description": no.description }));
if let Some(secs) = no.retry_after {
set(&mut r, "retry-after", &secs.to_string());
}
r
}
};
set(&mut r, "cache-control", "no-store");
if new_device {
device_cookie(&svc, &mut r, &device);
}
device_cookie(&svc, &mut r, &device);
r
})
.await
@@ -497,38 +560,119 @@ fn text<'b>(b: &'b Map<String, Json>, k: &str) -> &'b str {
b.get(k).and_then(Json::as_str).unwrap_or_default()
}
/// `sign-in`: the account's own password, not an app password.
async fn sign_in(svc: &Shared, tx: &mut Tx<'_>, device: &str, request_id: &str, b: &Map<String, Json>) -> Result<Json, String> {
let refused = || Err("Invalid identifier or password".to_string());
let Some(account) = crate::server::login(svc, text(b, "identifier")) else { return refused() };
let Some(hash) = crate::email::lock(&account.mail).password.clone() else { return refused() };
let pw = text(b, "password").to_string();
if !tokio::task::spawn_blocking(move || crate::server::password::verify(&pw, &hash)).await.unwrap_or(false) {
return refused();
/// How long a device the account signed in on, remembered, needs no code of
/// its email factor.
const FACTOR_TRUST: u64 = 30 * 24 * 60 * 60;
/// What the API answers in place of what was asked: its status, `error`
/// and description, and for a rate limit, the seconds to wait.
struct Refusal {
status: u16,
error: &'static str,
description: String,
retry_after: Option<u64>,
}
impl From<String> for Refusal {
/// The usual refusal: `400 invalid_request`.
fn from(description: String) -> Refusal {
Refusal { status: 400, error: "invalid_request", description, retry_after: None }
}
}
impl From<crate::XrpcError> for Refusal {
/// An XRPC method's error, in the API's terms: `500 server_error`, or else `400 invalid_request`.
fn from(e: crate::XrpcError) -> Refusal {
if e.status >= 500 {
Refusal { status: 500, error: "server_error", description: "Internal server error".into(), retry_after: None }
} else {
Refusal::from(e.message)
}
}
}
/// `sign-in`: the login limits paid, the account's own password, not an app
/// password, then the code its email factor asks for, as `createSession`
/// checks them (`spec/OAUTH.md`, "The API").
async fn sign_in(svc: &Shared, tx: &mut Tx<'_>, device: &mut Device, request_id: &str, client: &str, b: &Map<String, Json>) -> Result<Json, Refusal> {
let id = text(b, "identifier");
if let Err(secs) = crate::limits::charge_sign_in(svc, id, client) {
return Err(Refusal { status: 429, error: "invalid_request", description: "Too many sign-in attempts".into(), retry_after: Some(secs) });
}
let refused = || Err(Refusal::from("Invalid identifier or password".to_string()));
let account = crate::server::login(svc, id);
let (own, _) = crate::server::check_password(svc, account.as_deref(), text(b, "password")).await;
let (Some(account), Some(own)) = (account, own) else { return refused() };
if crate::read(&account.state).takedown.is_some() {
return Err("Account was taken down".into());
return Err("Account was taken down".to_string().into());
}
// The empty code is none.
let code = b.get("emailOtp").and_then(Json::as_str).filter(|c| !c.is_empty());
let remember = b.get("remember").and_then(Json::as_bool);
let did = account.did.clone();
// Remembered, or left out for an account already signed in here, it is
// signed in here from now; otherwise not, and it gets an ephemeral token.
let now = svc.sessions.now();
// A device it signed in on, remembered, lately, needs no code.
let trusted = svc.oauth.lock().signed_in(&device.id).iter().any(|(d, at)| *d == did && now.saturating_sub(*at) <= FACTOR_TRUST);
let (mail, remembered) = {
let mut m = crate::email::lock(&account.mail);
// A password changed since it was checked makes it wrong.
if m.password.as_ref() != Some(&own) {
return refused();
}
if let Some(code) = code {
m.check(AuthFactor, code, now)?;
}
// Its checks passed, below the free space nothing is kept, a code
// made or used up, or the sign-in.
if super::low(svc) {
return Err(Refusal { status: 507, error: "temporarily_unavailable", description: "Not enough free space to store this".into(), retry_after: None });
}
match code {
Some(_) => {
let used = crate::email::use_entry(&did, AuthFactor);
let remembered = sign_in_here(tx, device, &did, remember, Some(&used));
if !tx.failed {
crate::email::apply(svc, &did, &mut m, &[used]);
}
(None, remembered)
}
None if m.auth_factor && !trusted => (Some(crate::email::make(svc, &did, &mut m, AuthFactor)?), false),
None => (None, sign_in_here(tx, device, &did, remember, None)),
}
};
if let Some(mail) = mail {
crate::email::deliver(svc, mail).await?;
let description = "A sign in code has been sent to your email address".to_string();
return Err(Refusal { status: 401, error: "second_authentication_factor_required", description, retry_after: None });
}
let mut out = json!({ "account": account_json(svc, &account) });
if !remembered {
let exp = svc.sessions.now() + EPHEMERAL_LIFE;
out["ephemeralToken"] = json!(svc.oauth.seal("ephemeral", &json!({ "did": did, "device": device.id, "request": request_id, "exp": exp })));
}
Ok(out)
}
/// Sign `did` in on `device`, with a code it used up (`used`), in one frame:
/// remembered, or with `remember` left out when it is signed in here
/// already, it is signed in here from now; otherwise it is not, or no
/// longer. Either way the device is given new cookies, and those it had
/// are old (`spec/OAUTH.md`, "Devices"). Answers whether it is remembered.
fn sign_in_here(tx: &mut Tx<'_>, device: &mut Device, did: &str, remember: Option<bool>, used: Option<&Json>) -> bool {
let (id, key) = (device.id.as_str(), new_id(16));
let remembered = tx.change(|st, now| {
let signed = st.signed_in(device).iter().any(|(d, _)| *d == did);
let signed = st.signed_in(id).iter().any(|(d, _)| d == did);
let remembered = remember.unwrap_or(signed);
let entry = if remembered {
Some(json!({ "t": "oauthSignIn", "device": device, "did": did, "at": now }))
Some(json!({ "t": "oauthSignIn", "device": id, "did": did, "at": now }))
} else {
signed.then(|| json!({ "t": "oauthSignOut", "device": device, "did": did }))
signed.then(|| json!({ "t": "oauthSignOut", "device": id, "did": did }))
};
(entry.into_iter().collect(), remembered)
let renewed = json!({ "t": "oauthDeviceKey", "device": id, "key": key, "at": now });
(used.cloned().into_iter().chain(entry).chain([renewed]).collect(), remembered)
});
let mut out = json!({ "account": account_json(svc, &account) });
if !remembered {
let exp = svc.sessions.now() + EPHEMERAL_LIFE;
out["ephemeralToken"] = json!(svc.oauth.seal("ephemeral", &json!({ "did": did, "device": device, "request": request_id, "exp": exp })));
}
Ok(out)
device.give = Some(key);
remembered
}
/// Whether `Authorization: Bearer` holds an ephemeral token of a sign-in of `did`, on this device, for this request.
@@ -591,19 +735,23 @@ fn consent_checks<'s>(svc: &Service, st: &'s State, now: u64, id: &str, device:
/// `consent`: checks 1 to 3, then the request's client loaded
/// (`spec/OAUTH-CLIENTS.md`, "At `consent`"), with no lock held while it is
/// fetched, then checks 1 to 3 again, as the request may have moved on, and 4.
async fn consent(svc: &Shared, tx: &mut Tx<'_>, headers: &HeaderMap, device: &str, id: &str, b: &Map<String, Json>) -> Result<Json, String> {
async fn consent(svc: &Shared, tx: &mut Tx<'_>, headers: &HeaderMap, device: &str, id: &str, b: &Map<String, Json>) -> Result<Json, Refusal> {
let did = text(b, "did");
let signed_by_token = ephemeral(svc, headers, did, device, id);
let low = super::low(svc);
let first = tx.change(|st: &State, now| match consent_checks(svc, st, now, id, device, did, signed_by_token) {
Ok(r) => (vec![], Ok(r.client_id.clone())),
Err((entries, answer)) => (entries, Err(answer)),
Err(unapproved) => {
let (entries, answer) = unless_low(low, unapproved);
(entries, Err(answer))
}
});
let client_id = match first {
Ok(c) => c,
Err(answer) => return answer,
};
let loaded = clients::load_why(svc, &client_id).await;
tx.change(|st: &State, now| {
tx.change(changing(low, |st: &State, now| {
let r = match consent_checks(svc, st, now, id, device, did, signed_by_token) {
Ok(r) => r,
Err(unapproved) => return unapproved,
@@ -631,14 +779,30 @@ async fn consent(svc: &Shared, tx: &mut Tx<'_>, headers: &HeaderMap, device: &st
entries.push(json!({ "t": "oauthApprove", "id": id, "code": code, "did": did, "scope": scope, "at": now }));
let url = redirect_url(svc, r, &[("iss", svc.oauth.issuer.clone()), ("state", r.state.clone()), ("code", code)]);
(entries, Ok(json!({ "url": url })))
})
}))
}
fn reject(svc: &Shared, tx: &mut Tx, id: &str) -> Result<Json, String> {
tx.change(|st: &State, _| {
/// A change of the API's that would keep something, below the free-space
/// floor (`low`): refused with `507`, changing nothing (`spec/OAUTH.md`,
/// "Free space").
fn unless_low(low: bool, (entries, answer): Unapproved) -> (Vec<Json>, Result<Json, Refusal>) {
if low && !entries.is_empty() {
let description = "Not enough free space to store this".to_string();
return (vec![], Err(Refusal { status: 507, error: "temporarily_unavailable", description, retry_after: None }));
}
(entries, answer.map_err(Refusal::from))
}
/// A change `f` of the API's, held to the free-space floor (`unless_low`).
fn changing<'f>(low: bool, f: impl FnOnce(&State, u64) -> Unapproved + 'f) -> impl FnOnce(&State, u64) -> (Vec<Json>, Result<Json, Refusal>) + 'f {
move |st: &State, now: u64| unless_low(low, f(st, now))
}
fn reject(svc: &Shared, tx: &mut Tx, id: &str) -> Result<Json, Refusal> {
tx.change(changing(super::low(svc), |st: &State, _| {
let Some(r) = st.requests.get(id) else { return (vec![], Err("Unknown or ended request".into())) };
end_with(svc, id, r, "access_denied", "The user denied the request")
})
}))
}
fn sign_out(tx: &mut Tx, device: &str, b: &Map<String, Json>) -> Result<Json, String> {
crates/pds-server/src/oauth/tests.rs+750−6
756 lines changed: not loaded until asked for.
crates/pds-server/src/scopes/tests.rs+6−0
@@ -112,6 +112,12 @@ fn identity_account_and_rpc_permissions() {
assert!(scope("atproto transition:generic").allows(&any) && !scope("atproto transition:chat.bsky").allows(&any));
assert!(scope("atproto transition:generic transition:chat.bsky").allows(&chat) && scope("atproto transition:chat.bsky").allows(&chat));
assert!(scope("atproto transition:chat.bsky").allows(&chat_elsewhere) && !scope("atproto transition:chat.bsky").allows(&report));
// The prefix in any case: a service may read a method's name so.
for lxm in ["Chat.Bsky.convo.sendMessage", "CHAT.BSKY.convo.getLog"] {
let need = Need::Rpc { lxm, aud: "did:web:api.bsky.chat#bsky_chat" };
assert!(!scope("atproto transition:generic").allows(&need), "{lxm}");
assert!(scope("atproto transition:chat.bsky").allows(&need), "{lxm}");
}
// transition:generic allows nothing of identity or account.
let generic = scope("atproto transition:generic");
assert!(!generic.allows(&read) && !generic.allows(&Need::Account { attr: "repo", manage: true }));
crates/pds-server/src/space_credentials/attestation.rs+94−36
@@ -1,24 +1,27 @@
//! Client attestations (`spec/SPACES-CREDENTIALS.md`, "Verifying a client
//! attestation"): a `private_key_jwt` client assertion addressed to the
//! space host, verified against the keys of the client's metadata.
//! space host, verified against the keys of the client's metadata, which is
//! fetched through the guard (`outbound`).
use super::jwt::{Jwt, Key};
use crate::Service;
use crate::outbound::{self, Outbound};
use crate::single_use::SingleUse;
use serde_json::{Map, Value as Json};
/// An attestation's `typ`.
const TYP: &str = "atproto-client-attestation+jwt";
/// The most of a client's metadata, or of its key set, read.
const MAX_DOCUMENT: usize = 64 * 1024;
/// The furthest ahead of now an attestation's `exp` may be, in seconds.
const MAX_AHEAD: f64 = 3600.0;
/// The client an attestation addressed to the space host of `authority`
/// attests, by its `client_id`; None if it fails. It is spent if it passes.
/// Nothing is fetched for one that fails step 1.
pub(super) async fn verify(s: &Service, token: &str, authority: &str) -> Option<String> {
let jwt = well_formed(token)?;
let jwt = well_formed(token, s.sessions.now())?;
let client_id = jwt.claim("iss")?.to_string();
let keys = client_keys(&client_id).await?;
let keys = client_keys(&s.outbound, &client_id).await?;
let now = s.sessions.now();
if !verifies(&jwt, &keys, authority, now) {
return None;
@@ -28,14 +31,15 @@ pub(super) async fn verify(s: &Service, token: &str, authority: &str) -> Option<
}
/// Step 1: three parts; its `typ` and `alg`; `iss`, `sub` and `aud`, a
/// number `exp`, a non-empty `jti`, and `iss` its `sub`.
fn well_formed(token: &str) -> Option<Jwt> {
/// number `exp` not more than an hour after `now`, a non-empty `jti`, and
/// `iss` its `sub`.
fn well_formed(token: &str, now: u64) -> Option<Jwt> {
let jwt = Jwt::parse(token)?;
let present = |k: &str| jwt.payload.get(k).is_some_and(|v| !v.is_null());
let ok = jwt.header("typ") == Some(TYP)
&& jwt.alg().is_some()
&& ["iss", "sub", "aud"].iter().all(|k| present(k))
&& jwt.number("exp").is_some()
&& jwt.number("exp").is_some_and(|exp| exp - now as f64 <= MAX_AHEAD)
&& jwt.claim("jti").is_some_and(|j| !j.is_empty())
&& jwt.claim("iss").is_some()
&& jwt.payload.get("iss") == jwt.payload.get("sub");
@@ -56,42 +60,35 @@ fn verifies(jwt: &Jwt, keys: &[Json], authority: &str, now: u64) -> bool {
}
/// Step 2: the keys of the client's metadata, fetched from its
/// `client_id`: its `jwks`, or the set its `jwks_uri` answers.
async fn client_keys(client_id: &str) -> Option<Vec<Json>> {
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(std::time::Duration::from_secs(5))
.timeout(std::time::Duration::from_secs(10))
.build()
.ok()?;
let metadata = fetch(&http, client_id).await?;
/// `client_id`, an `https` URL: its `jwks`, or the set its `jwks_uri`, an
/// `https` URL too, answers.
async fn client_keys(out: &Outbound, client_id: &str) -> Option<Vec<Json>> {
let metadata = fetch(out, https(client_id)?).await?;
if metadata.get("client_id").and_then(Json::as_str) != Some(client_id) {
return None;
}
let jwks = match (metadata.get("jwks"), metadata.get("jwks_uri").and_then(Json::as_str)) {
(Some(Json::Object(set)), _) => set.clone(),
(None, Some(uri)) => fetch(&http, uri).await?,
(None, Some(uri)) => fetch(out, https(uri)?).await?,
_ => return None,
};
jwks.get("keys")?.as_array().cloned()
}
/// The JSON object an `https` URL answers `200` with, to `GET` with
/// `Accept: application/json`, following no redirect.
async fn fetch(http: &reqwest::Client, url: &str) -> Option<Map<String, Json>> {
let url = reqwest::Url::parse(url).ok().filter(|u| u.scheme() == "https" && u.host_str().is_some())?;
let mut res = http.get(url).header(reqwest::header::ACCEPT, "application/json").send().await.ok()?;
if res.status() != reqwest::StatusCode::OK {
fn https(url: &str) -> Option<reqwest::Url> {
reqwest::Url::parse(url).ok().filter(|u| u.scheme() == "https" && u.host_str().is_some())
}
/// The JSON object `url` answers `200` with, to `GET` with `Accept:
/// application/json`, through the guard: no redirect followed (a `3xx` is
/// none), at most `JSON_DOC_MAX` bytes, within `WAIT`.
async fn fetch(out: &Outbound, url: reqwest::Url) -> Option<Map<String, Json>> {
let request = out.client().get(url).header(reqwest::header::ACCEPT, "application/json");
let got = out.fetch_limited(request, outbound::JSON_DOC_MAX, outbound::WAIT).await.ok()?;
if got.status != 200 {
return None;
}
let mut body = Vec::new();
while let Some(chunk) = res.chunk().await.ok()? {
body.extend_from_slice(&chunk);
if body.len() > MAX_DOCUMENT {
return None;
}
}
match serde_json::from_slice(&body).ok()? {
match serde_json::from_slice(&got.body).ok()? {
Json::Object(m) => Some(m),
_ => None,
}
@@ -100,10 +97,16 @@ async fn fetch(http: &reqwest::Client, url: &str) -> Option<Map<String, Json>> {
#[cfg(test)]
mod tests {
use super::*;
use crate::space_credentials::tests::counting;
use axum::Router;
use axum::http::{StatusCode, header};
use axum::response::IntoResponse;
use axum::routing::get;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use p256::ecdsa::signature::Signer;
use serde_json::json;
use std::sync::atomic::Ordering;
fn token(header: Json, payload: Json, key: &p256::ecdsa::SigningKey) -> String {
let signed = format!("{}.{}", B64.encode(header.to_string()), B64.encode(payload.to_string()));
@@ -122,7 +125,7 @@ mod tests {
let payload = json!({ "iss": client, "sub": client, "aud": "did:plc:auth#atproto_pds", "exp": 1000, "jti": "j" });
let ok = |h: &Json, p: &Json| {
let t = token(h.clone(), p.clone(), &key);
well_formed(&t).is_some_and(|jwt| verifies(&jwt, &keys, "did:plc:auth", 900))
well_formed(&t, 900).is_some_and(|jwt| verifies(&jwt, &keys, "did:plc:auth", 900))
};
assert!(ok(&header, &payload));
// Step 1, each part.
@@ -150,20 +153,75 @@ mod tests {
let mut p = payload.clone();
p["exp"] = json!(900);
assert!(ok(&header, &p), "valid until its exp");
// An `exp` at most an hour ahead: one more is refused at step 1.
p["exp"] = json!(900 + 3600);
assert!(well_formed(&token(header.clone(), p.clone(), &key), 900).is_some());
p["exp"] = json!(900 + 3601);
assert!(well_formed(&token(header.clone(), p.clone(), &key), 900).is_none());
p["exp"] = json!(900.0 + 3600.5);
assert!(well_formed(&token(header.clone(), p.clone(), &key), 900).is_none());
// A key whose own alg is another.
let mut other = jwk.clone();
other["alg"] = json!("ES256K");
let t = token(header.clone(), payload.clone(), &key);
assert!(!verifies(&well_formed(&t).unwrap(), &[other], "did:plc:auth", 900));
assert!(!verifies(&well_formed(&t, 900).unwrap(), &[other], "did:plc:auth", 900));
// Signed by another key.
let wrong = p256::ecdsa::SigningKey::from_slice(&[4u8; 32]).unwrap();
assert!(!verifies(&well_formed(&token(header.clone(), payload.clone(), &wrong)).unwrap(), &keys, "did:plc:auth", 900));
assert!(!verifies(&well_formed(&token(header.clone(), payload.clone(), &wrong), 900).unwrap(), &keys, "did:plc:auth", 900));
}
/// Only `https` client ids; and with SSRF protection, none at an IP
/// address or `localhost`, with no connection made.
#[tokio::test]
async fn metadata_is_had_only_from_https() {
let open = Outbound::new(false).unwrap();
for id in ["http://127.0.0.1:1/client.json", "not a url", "https://"] {
assert_eq!(client_keys(id).await, None, "{id}");
assert_eq!(client_keys(&open, id).await, None, "{id}");
}
let (port, connections) = counting().await;
let guarded = Outbound::new(true).unwrap();
for id in [format!("https://localhost:{port}/c.json"), format!("https://127.0.0.1:{port}/c.json"), format!("https://[::ffff:127.0.0.1]:{port}/c.json")] {
assert_eq!(client_keys(&guarded, &id).await, None, "{id}");
}
assert_eq!(connections.load(Ordering::SeqCst), 0);
// Without protection, the same is tried (and fails, no TLS there).
assert_eq!(client_keys(&open, &format!("https://127.0.0.1:{port}/c.json")).await, None);
for _ in 0..100 {
if connections.load(Ordering::SeqCst) > 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(connections.load(Ordering::SeqCst), 1);
}
/// A document is a `200` with a JSON object, followed through no
/// redirect, of at most `JSON_DOC_MAX` bytes.
#[tokio::test]
async fn documents_are_fetched_whole_and_unredirected() {
let max = outbound::JSON_DOC_MAX;
// A JSON object of exactly `n` bytes.
let of = |n: usize| format!("{{\"p\":\"{}\"}}", "x".repeat(n - 8));
let (edge, over) = (of(max), of(max + 1));
assert_eq!(edge.len(), max);
let app = Router::new()
.route("/ok", get(|| async { ([(header::CONTENT_TYPE, "application/json")], r#"{"a":1}"#) }))
.route("/moved", get(|| async { (StatusCode::FOUND, [(header::LOCATION, "/ok")]).into_response() }))
.route("/edge", get(move || async move { edge }))
.route("/over", get(move || async move { over }))
.route("/list", get(|| async { "[1]" }))
.route("/gone", get(|| async { (StatusCode::NOT_FOUND, r#"{"a":1}"#) }));
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let out = Outbound::new(false).unwrap();
let at = |p: &str| reqwest::Url::parse(&format!("{base}{p}")).unwrap();
assert_eq!(fetch(&out, at("/ok")).await, Some(json!({ "a": 1 }).as_object().unwrap().clone()));
assert!(fetch(&out, at("/edge")).await.is_some());
for refused in ["/moved", "/over", "/list", "/gone"] {
assert_eq!(fetch(&out, at(refused)).await, None, "{refused}");
}
// With protection, not even the `http` URL is asked.
assert_eq!(fetch(&Outbound::new(true).unwrap(), at("/ok")).await, None);
}
}
crates/pds-server/src/space_credentials/jwt.rs+3−32
@@ -164,18 +164,6 @@ impl Key {
}
}
/// Where `did`'s document is: for a `did:plc`, at the directory; for a
/// `did:web`, at its host's `/.well-known/did.json`. None for another.
fn document_url(plc_url: &str, did: &str) -> Option<String> {
if did.starts_with("did:plc:") {
return Some(format!("{}/{did}", plc_url.trim_end_matches('/')));
}
// A `did:web` with a path, its segments after `:`, is none atproto uses.
let id = did.strip_prefix("did:web:").filter(|id| !id.is_empty() && !id.contains(':'))?;
let host = id.replace("%3A", ":").replace("%3a", ":");
(!host.contains(['/', '%', '#', '?', '@'])).then(|| format!("https://{host}/.well-known/did.json"))
}
/// How long a key read from a document is kept before it is read again, in seconds.
const KEY_KEPT: u64 = 300;
/// The most keys kept; past it, all are forgotten.
@@ -222,17 +210,10 @@ fn keys_of(k: &Keys) -> std::sync::MutexGuard<'_, HashMap<String, (Key, u64)>> {
k.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// `did`'s `#atproto` key, from its document as served now.
/// `did`'s `#atproto` key, from its document as served now: a `did:plc`'s
/// from the directory, a `did:web`'s through the guard ("Issuers' keys").
async fn fetch_key(s: &Service, did: &str) -> Option<Key> {
let url = document_url(&s.config.plc_url, did)?;
match crate::plc::document(&s.http, &url).await {
Ok(Some(doc)) => Key::of_document(&doc, did),
Ok(None) => None,
Err(why) => {
eprintln!("pds: {why}");
None
}
}
Key::of_document(&crate::space_authz::document(s, did).await?, did)
}
#[cfg(test)]
@@ -317,14 +298,4 @@ mod tests {
other["kty"] = json!("RSA");
assert_eq!(Key::of_jwk(other.as_object().unwrap()), None);
}
#[test]
fn document_urls() {
assert_eq!(document_url("http://plc/", "did:plc:abc").as_deref(), Some("http://plc/did:plc:abc"));
assert_eq!(document_url("http://plc", "did:web:example.com").as_deref(), Some("https://example.com/.well-known/did.json"));
assert_eq!(document_url("http://plc", "did:web:localhost%3A8080").as_deref(), Some("https://localhost:8080/.well-known/did.json"));
for none in ["did:key:zQ3", "did:web:", "did:web:a.com:path", "did:web:a.com%2Fx"] {
assert_eq!(document_url("http://plc", none), None, "{none}");
}
}
}
crates/pds-server/src/space_credentials/tests.rs+143−4
@@ -37,8 +37,14 @@ impl Directory {
None => StatusCode::NOT_FOUND.into_response(),
}
}
// Its current data, as `activateAccount` reads it.
async fn get_data(State(d): State<Directory>, Path(did): Path<String>) -> Response {
let Some(op) = d.ops.lock().unwrap().get(&did).cloned() else { return StatusCode::NOT_FOUND.into_response() };
let data = json!({ "did": did, "verificationMethods": op["verificationMethods"], "rotationKeys": op["rotationKeys"], "alsoKnownAs": op["alsoKnownAs"], "services": op["services"] });
([(header::CONTENT_TYPE, "application/json")], data.to_string()).into_response()
}
let d = Directory::default();
let app = Router::new().route("/{did}", get(get_doc).post(post)).with_state(d.clone());
let app = Router::new().route("/{did}", get(get_doc).post(post)).route("/{did}/data", get(get_data)).with_state(d.clone());
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
@@ -153,7 +159,25 @@ pub(crate) async fn credential(s: &Shared, body: Json) -> Result<String, String>
}
async fn verify(s: &Service, headers: &HeaderMap, audience: &str) -> Result<SpaceCredential, String> {
verify_space_credential(s, headers, audience).await.map_err(|e| format!("{} {}", e.status, e.name))
let method = Method::GET;
let call = Call { nsid: "com.atproto.space.listRepos", method: &method, params: &[], body: b"", bearer: crate::sessions::Bearer::None, headers, client: "127.0.0.1".into(), charged: Default::default(), http: None };
verify_space_credential(s, &call, audience).await.map_err(|e| format!("{} {}", e.status, e.name))
}
/// A plain TCP listener on `127.0.0.1` that takes each connection, counts
/// it and closes it: its port, and the count.
pub(crate) async fn counting() -> (u16, Arc<std::sync::atomic::AtomicUsize>) {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = n.clone();
tokio::spawn(async move {
while let Ok((socket, _)) = listener.accept().await {
counted.fetch_add(1, Ordering::SeqCst);
drop(socket);
}
});
(port, n)
}
pub(crate) async fn revoke(s: &Shared, authorization: Option<&str>, body: Json) -> Result<Json, String> {
@@ -393,6 +417,9 @@ async fn delegation_tokens_each_with_one_thing_wrong() {
("exp", Json::Null),
("exp", json!(n - 5)),
("exp", json!(n - 100)),
// More than an hour ahead.
("exp", json!(n + 3700)),
("exp", json!(n + 86400)),
("jti", json!("")),
("jti", json!(7)),
("jti", Json::Null),
@@ -427,8 +454,8 @@ async fn delegation_tokens_each_with_one_thing_wrong() {
assert_eq!(trade(t).await, Err("400 InvalidDelegationToken".into()), "{what}");
}
trade(good).await.unwrap();
// Each taken, though unusual: no iat, a long life, an extra claim, `exp` 2 seconds past.
for (k, v) in [("iat", Json::Null), ("exp", json!(n + 86400)), ("lxm", json!("com.example.x")), ("exp", json!(n - 2)), ("iat", json!("then"))] {
// Each taken, though unusual: no iat, an hour's life, an extra claim, `exp` 2 seconds past.
for (k, v) in [("iat", Json::Null), ("exp", json!(n + 3600)), ("lxm", json!("com.example.x")), ("exp", json!(n - 2)), ("iat", json!("then"))] {
let mut p = payload(&fresh());
if v.is_null() {
p.as_object_mut().unwrap().remove(k);
@@ -703,6 +730,118 @@ async fn revocations_and_spent_tokens_survive_a_restart() {
let _ = std::fs::remove_dir_all(&w.dir);
}
/// Take an account down, or lift that, as the admin does.
pub(crate) async fn take_down(s: &Shared, did: &str, on: bool) {
let admin = format!("Basic {}", STANDARD.encode(format!("admin:{ADMIN_PASSWORD}")));
let mut takedown = json!({ "applied": on });
if on {
takedown["ref"] = json!("r1");
}
let body = json!({ "subject": { "$type": "com.atproto.admin.defs#repoRef", "did": did }, "takedown": takedown });
call_raw(s, "com.atproto.admin.updateSubjectStatus", crate::sessions::Bearer::of(Some(&admin)), &[], &body.to_string()).await.unwrap();
}
/// Deactivate an account with its token, or activate it again.
pub(crate) async fn deactivate(s: &Shared, token: &str, on: bool) {
let (nsid, body) = if on { ("com.atproto.server.deactivateAccount", json!({})) } else { ("com.atproto.server.activateAccount", Json::Null) };
call(s, nsid, Some(token), body).await.unwrap();
}
/// `getDelegationToken` of a deactivated or taken-down account, with a
/// token made before: refused after its space and its token are checked.
#[tokio::test]
async fn delegation_tokens_are_refused_to_an_account_not_active() {
let w = world("cred-delegation-state").await;
let s = &w.s;
let (bob, t) = (&w.bob.0, &w.bob.1);
let sess = call(s, "com.atproto.server.createSession", None, json!({ "identifier": "bob.test", "password": "bob-pw" })).await.unwrap();
let refresh = sess["refreshJwt"].as_str().unwrap().to_string();
let app = call(s, "com.atproto.server.createAppPassword", Some(t), json!({ "name": "app" })).await.unwrap();
let app_sess = call(s, "com.atproto.server.createSession", None, json!({ "identifier": "bob.test", "password": app["password"] })).await.unwrap();
let app_token = app_sess["accessJwt"].as_str().unwrap().to_string();
let earlier = |state: &str| {
let state = state.to_string();
let (refresh, app_token, space) = (refresh.clone(), app_token.clone(), w.space.clone());
async move {
let space = space.as_str();
// Its space first, then its token, then the account's state.
assert_eq!(delegation_token(s, t, "at://did:plc:x/space/forum/k").await, Err("400 InvalidRequest".into()), "{state}");
assert_eq!(delegation_token(s, "nonsense", space).await, Err("400 InvalidToken".into()), "{state}");
assert_eq!(delegation_token(s, &refresh, space).await, Err("400 InvalidToken".into()), "{state}");
assert_eq!(delegation_token(s, &app_token, space).await, Err("400 InvalidToken".into()), "{state}");
assert_eq!(delegation_token(s, t, space).await, Err(state.clone()), "{state}");
assert_eq!(delegation_token(s, t, "at://did:plc:nowhere/space/com.example.x/k").await, Err(state.clone()), "{state}");
}
};
deactivate(s, t, true).await;
earlier("401 AccountDeactivated").await;
take_down(s, bob, true).await;
earlier("401 AccountTakedown").await;
take_down(s, bob, false).await;
earlier("401 AccountDeactivated").await;
deactivate(s, t, false).await;
take_down(s, bob, true).await;
earlier("401 AccountTakedown").await;
// A taken-down account's own session is refused with its token.
let down = json!({ "identifier": "bob.test", "password": "bob-pw", "allowTakendown": true });
let down = call(s, "com.atproto.server.createSession", None, down).await.unwrap();
assert_eq!(delegation_token(s, down["accessJwt"].as_str().unwrap(), &w.space).await, Err("400 InvalidToken".into()));
take_down(s, bob, false).await;
delegation_token(s, t, &w.space).await.unwrap();
let _ = std::fs::remove_dir_all(&w.dir);
}
/// `getSpaceCredential` of a space whose authority is deactivated or taken
/// down: refused at step 4, whatever the user and the attestation, after
/// the key and the token are checked; a token taken at step 3 is spent.
#[tokio::test]
async fn credentials_are_refused_for_an_authority_not_active() {
let w = world("cred-authority-state").await;
let s = &w.s;
let (alice, t) = (&w.alice.0, &w.alice.1);
let kid = client(1).kid;
let ask = |body: Json| credential(s, body);
// Tokens made while every account is active: the authority's and another user's.
let mut tokens = Vec::new();
for _ in 0..4 {
tokens.push(delegation_token(s, t, &w.space).await.unwrap());
tokens.push(delegation_token(s, &w.bob.1, &w.space).await.unwrap());
}
let refused = |state: &'static str, alices: String, bobs: String| {
let (kid, space) = (kid.clone(), w.space.clone());
async move {
let space = space.as_str();
// 2. A credentialKid that is no key, and 3. a token that is no JWT, first.
assert_eq!(ask(json!({ "space": space, "credentialKid": "nonsense", "delegationToken": alices })).await, Err("400 InvalidRequest".into()));
assert_eq!(ask(json!({ "space": space, "credentialKid": kid, "delegationToken": "x.y.z" })).await, Err("400 InvalidDelegationToken".into()));
// 4. The authority's state, before the attestation and the perimeter.
assert_eq!(ask(json!({ "space": space, "credentialKid": kid })).await, Err(state.into()));
assert_eq!(ask(json!({ "space": space, "credentialKid": kid, "clientAttestation": "x" })).await, Err(state.into()));
let other = format!("at://{alice}/space/com.example.forum/none");
assert_eq!(ask(json!({ "space": other, "credentialKid": kid })).await, Err(state.into()));
for token in [&alices, &bobs] {
assert_eq!(ask(json!({ "space": space, "credentialKid": kid, "delegationToken": token, "clientAttestation": "x" })).await, Err(state.into()));
// Verified at step 3, it was spent all the same.
assert_eq!(ask(json!({ "space": space, "credentialKid": kid, "delegationToken": token })).await, Err("400 InvalidDelegationToken".into()));
}
}
};
let mut next = || (tokens.pop().unwrap(), tokens.pop().unwrap());
deactivate(s, t, true).await;
let (b, a) = next();
refused("400 RepoDeactivated", a, b).await;
take_down(s, alice, true).await;
let (b, a) = next();
refused("400 RepoTakendown", a, b).await;
take_down(s, alice, false).await;
let (b, a) = next();
refused("400 RepoDeactivated", a, b).await;
deactivate(s, t, false).await;
let (_, a) = next();
ask(json!({ "space": w.space, "credentialKid": kid, "delegationToken": a })).await.unwrap();
let _ = std::fs::remove_dir_all(&w.dir);
}
#[test]
fn the_methods_are_tools() {
for (nsid, tool) in [
crates/pds-server/src/space_notify/tests.rs+310−8
@@ -4,7 +4,7 @@
//! asks; the clock is moved on by `Notify::skew`.
use super::*;
use crate::space_credentials::tests::{account_key, client, credential, delegation_token, high_s, jwt_of, signed};
use crate::space_credentials::tests::{account_key, client, counting, credential, delegation_token, high_s, jwt_of, signed};
use crate::Config;
use crate::testing::*;
use axum::Router;
@@ -289,7 +289,12 @@ fn kept(s: &Service, did: &str) -> Kept {
/// Headers presenting a credential of `space` from its authority, signed for `audience`.
async fn credentialed(s: &Shared, authority: &(String, String), space: &str, audience: &str) -> HeaderMap {
let c = client(1);
credentialed_by(s, authority, space, audience, 1).await
}
/// The same, the credential bound to the key of client `seed`.
async fn credentialed_by(s: &Shared, authority: &(String, String), space: &str, audience: &str, seed: u8) -> HeaderMap {
let c = client(seed);
let t = delegation_token(s, &authority.1, space).await.unwrap();
let cred = credential(s, json!({ "space": space, "credentialKid": c.kid, "delegationToken": t })).await.unwrap();
signed(&c, &cred, audience)
@@ -527,10 +532,11 @@ fn the_schedule() {
for s in [200, 201, 299] {
assert_eq!(outcome(s), Outcome::Delivered);
}
for s in FAILING {
// A redirect is as no answer.
for s in FAILING.into_iter().chain([300, 301, 302, 307, 308]) {
assert_eq!(outcome(s), Outcome::Failed);
}
for s in [300, 400, 401, 403, 404, 409, 501, 505, 523] {
for s in [400, 401, 403, 404, 409, 501, 505, 523] {
assert_eq!(outcome(s), Outcome::Refused);
}
}
@@ -686,14 +692,16 @@ async fn registrations_and_forwarding() {
// Registered for a day.
let t0 = s.space_notify.now();
let got = reg(REGISTER, body(SYNCER_SERVICE), h.clone()).await.unwrap();
let expires = kept(s, alice).registered[&w.space][SYNCER_SERVICE];
let r = kept(s, alice).registered[&w.space][SYNCER_SERVICE].clone();
assert_eq!(r.kid, Some(client(1).kid));
let expires = r.expires;
assert!(expires >= t0 + REGISTRATION && expires <= s.space_notify.now() + REGISTRATION);
assert_eq!(got, json!({ "expiresAt": pds_repo::data::datetime_string(expires as i64) }));
assert_eq!(pds_repo::data::datetime_string(1_794_217_433_972), "2026-11-09T09:43:53.972Z");
// Registering again replaces it; a service where nothing listens is registered all the same.
advance_to(s, t0 + 5 * SECOND);
reg(REGISTER, body(SYNCER_SERVICE), h.clone()).await.unwrap();
assert!(kept(s, alice).registered[&w.space][SYNCER_SERVICE] > expires);
assert!(kept(s, alice).registered[&w.space][SYNCER_SERVICE].expires > expires);
reg(REGISTER, body(SYNCER_DOWN), h.clone()).await.unwrap();
// Refusals: input, credential, then the service.
assert_eq!(reg(REGISTER, json!({ "space": w.space }), h.clone()).await, Err("400 InvalidRequest".into()));
@@ -823,6 +831,297 @@ async fn deletion_notices() {
let _ = std::fs::remove_dir_all(&w.dir);
}
async fn register(s: &Shared, h: &HeaderMap, space: &str, service: &str) -> Result<Json, String> {
send(s, Http::POST, REGISTER, &[], h, &json!({ "space": space, "service": service }).to_string()).await
}
async fn unregister(s: &Shared, h: &HeaderMap, space: &str, service: &str) -> Result<Json, String> {
send(s, Http::POST, UNREGISTER, &[], h, &json!({ "space": space, "service": service }).to_string()).await
}
const MANY: &str = "400 TooManyRegistrations";
const UNRESOLVABLE: &str = "400 ServiceNotResolvable";
const REVOKE: &str = "com.atproto.space.notifyCredentialRevoked";
/// The limits on registrations, as `spec/SPACES-SYNC.md`'s "How it is
/// checked" plays them: 8 a key, 64 a space, a service registered already
/// always replaced (its registrant then the key that replaced it), one
/// withdrawn making room; nothing fetched for a registration refused so;
/// and expired registrations counting against neither.
#[tokio::test]
async fn registration_limits() {
let w = world("notify-limits").await;
let (s, alice) = (&w.s, &w.alice.0);
let services: Vec<(String, String)> = (0..80).map(|i| (format!("#s{i}"), w.url.clone())).collect();
w.plc.serve(SYNCER, None, &services.iter().map(|(id, url)| (id.as_str(), url.as_str())).collect::<Vec<_>>());
let svc = |i: usize| format!("{SYNCER}#s{i}");
let mut keys = Vec::new();
for seed in 1..=9 {
keys.push(credentialed_by(s, &w.alice, &w.space, alice, seed).await);
}
let sp = w.space.as_str();
// One key: 8, and a ninth refused, before anything is fetched for it.
for i in 0..8 {
register(s, &keys[0], sp, &svc(i)).await.unwrap();
}
assert_eq!(register(s, &keys[0], sp, &svc(8)).await, Err(MANY.into()));
let (port, connections) = counting().await;
assert_eq!(register(s, &keys[0], sp, &format!("did:web:localhost%3A{port}#x")).await, Err(MANY.into()));
assert_eq!(register(s, &keys[0], sp, "notadid").await, Err(MANY.into()));
// Its first again is replaced.
register(s, &keys[0], sp, &svc(0)).await.unwrap();
// Seven more keys, 8 each: the space's 64.
for k in 1..8 {
for j in 0..8 {
register(s, &keys[k], sp, &svc(8 * k + j)).await.unwrap();
}
}
assert_eq!(kept(s, alice).registered[sp].len(), 64);
// A ninth key: no new one, but one registered already is replaced, and is its.
assert_eq!(register(s, &keys[8], sp, &svc(64)).await, Err(MANY.into()));
register(s, &keys[8], sp, &svc(0)).await.unwrap();
assert_eq!(kept(s, alice).registered[sp][&svc(0)].kid, Some(client(9).kid));
// The key that registered it has 7, but the space is full.
assert_eq!(register(s, &keys[0], sp, &svc(64)).await, Err(MANY.into()));
// Withdrawn, with no limit, one makes room.
assert_eq!(unregister(s, &keys[0], sp, &svc(1)).await, Ok(Json::Null));
register(s, &keys[0], sp, &svc(64)).await.unwrap();
assert_eq!(register(s, &keys[1], sp, &svc(65)).await, Err(MANY.into()));
assert_eq!(connections.load(Ordering::SeqCst), 0);
// Expired, they count against neither; and are not kept long.
advance_to(s, s.space_notify.now() + REGISTRATION + SECOND);
for i in 0..8 {
register(s, &keys[1], sp, &svc(i)).await.unwrap();
}
assert_eq!(register(s, &keys[1], sp, &svc(8)).await, Err(MANY.into()));
register(s, &keys[0], sp, &svc(8)).await.unwrap();
assert_eq!(kept(s, alice).registered[sp].len(), 9);
let _ = std::fs::remove_dir_all(&w.dir);
}
/// A place among the forwards waiting is had while fewer than 1024 wait.
#[test]
fn forwards_waiting_are_bounded() {
assert_eq!(FORWARDS_WAITING, 1024);
let waiting = Waiting::new(FORWARDS_WAITING);
let mut places: Vec<Place> = (0..FORWARDS_WAITING).map(|_| waiting.enter().expect("a place")).collect();
assert!(waiting.enter().is_none());
places.pop();
let again = waiting.enter().expect("a place given back");
assert!(waiting.enter().is_none());
drop(again);
drop(places);
assert_eq!((0..FORWARDS_WAITING).filter_map(|_| waiting.enter()).count(), FORWARDS_WAITING);
}
/// Endpoints (`spec/SPACES-SYNC.md`, "Environment"): one with a path and a
/// query is sent to at its origin; one with a user and password is
/// registered, but sent nothing; `ftp://` and no scheme do not resolve.
/// With 1024 forwards waiting, one more is given up at once.
#[tokio::test]
async fn endpoints_are_origins() {
let w = world("notify-origins").await;
let (s, party, alice) = (&w.s, &w.party, &w.alice.0);
let host = w.url.strip_prefix("http://").unwrap();
let (base, userpass, ftp) = (format!("{}/base/more?x=1#f", w.url), format!("http://u:p@{host}"), format!("ftp://{host}"));
w.plc.serve(SYNCER, None, &[("#base", &base), ("#userpass", &userpass), ("#ftp", &ftp), ("#bare", host)]);
let h = credentialed(s, &w.alice, &w.space, alice).await;
let based = format!("{SYNCER}#base");
register(s, &h, &w.space, &based).await.unwrap();
register(s, &h, &w.space, &format!("{SYNCER}#userpass")).await.unwrap();
for service in ["#ftp", "#bare"] {
assert_eq!(register(s, &h, &w.space, &format!("{SYNCER}{service}")).await, Err(UNRESOLVABLE.into()), "{service}");
}
let ok = token(&claims(s, WRITER, alice), signer(&w.writer));
let t = s.space_notify.now();
notify(s, Some(&ok), &note(&w.space, WRITER, &tid_at(t), &[1; 32])).await.unwrap();
let got = party.wait_for(1).await;
assert_eq!(got[0].nsid, NOTIFY_WRITE);
service_auth_of(s, &got[0].auth, alice, &based, NOTIFY_WRITE);
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(party.take().is_empty(), "nothing to the endpoint with a user and password");
// 1024 waiting: the next is given up at once, not sent later.
let held: Vec<Place> = (0..FORWARDS_WAITING).map(|_| s.space_notify.forwards.enter().unwrap()).collect();
notify(s, Some(&ok), &note(&w.space, WRITER, &tid_at(t + 1), &[2; 32])).await.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
drop(held);
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(party.take().is_empty());
let r3 = tid_at(t + 2);
notify(s, Some(&ok), &note(&w.space, WRITER, &r3, &[3; 32])).await.unwrap();
assert_eq!(party.wait_for(1).await[0].body["repoRev"], json!(r3));
let _ = std::fs::remove_dir_all(&w.dir);
}
/// What a `did:web`'s host answers for its document.
enum WebDoc {
/// This document, padded to so many bytes if not 0.
Doc(Json, usize),
/// A `302` to this URL.
Moved(String),
}
/// A `did:web` on `localhost` whose host answers as `make` says for the
/// DID; the DID, its port, and how often its document was asked for.
async fn web_did(make: impl FnOnce(&str) -> WebDoc) -> (String, u16, Arc<AtomicUsize>) {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let did = format!("did:web:localhost%3A{port}");
let (status, location, body) = match make(&did) {
WebDoc::Doc(mut doc, size) => {
if size > 0 {
doc["pad"] = json!("");
let n = doc.to_string().len();
doc["pad"] = json!("x".repeat(size - n));
}
(StatusCode::OK, None, doc.to_string())
}
WebDoc::Moved(to) => (StatusCode::FOUND, Some(to), String::new()),
};
let asked = Arc::new(AtomicUsize::new(0));
let counted = asked.clone();
let app = Router::new().route(
"/.well-known/did.json",
get(move || async move {
counted.fetch_add(1, Ordering::SeqCst);
let mut res = (status, [(header::CONTENT_TYPE, "application/json")], body).into_response();
if let Some(to) = location {
res.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&to).unwrap());
}
res
}),
);
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(did, port, asked)
}
/// A `did:web`'s document with its `#atproto` key and a syncer's service at `url`.
fn web_doc(did: &str, key: &SigningKey, url: &str) -> Json {
json!({
"id": did,
"verificationMethod": [{ "id": format!("{did}#atproto"), "type": "Multikey", "controller": did, "publicKeyMultibase": crate::plc::did_key(key.verifying_key()).trim_start_matches("did:key:") }],
"service": [{ "id": "#atproto_space_syncer", "type": "Service", "serviceEndpoint": url }],
})
}
/// With SSRF protection off, a `did:web`'s document is read from its host
/// over `http`, the issuer of service auth's as a syncer's: up to 65536
/// bytes; a redirect, never followed, and a longer one cannot be read.
#[tokio::test]
async fn did_web_documents() {
let w = world("notify-did-web").await;
let (s, alice) = (&w.s, &w.alice.0);
let h = credentialed(s, &w.alice, &w.space, alice).await;
let key = SigningKey::from_slice(&[11; 32]).unwrap();
let max = crate::outbound::DID_DOC_MAX;
let (served, _, _) = web_did(|did| WebDoc::Doc(web_doc(did, &key, &w.url), 0)).await;
let (edge, _, _) = web_did(|did| WebDoc::Doc(web_doc(did, &key, &w.url), max)).await;
let (big, _, _) = web_did(|did| WebDoc::Doc(web_doc(did, &key, &w.url), max + 1)).await;
let (_, port, target_asked) = web_did(|did| WebDoc::Doc(web_doc(did, &key, &w.url), 0)).await;
let (moved, _, moved_asked) = web_did(|_| WebDoc::Moved(format!("http://localhost:{port}/.well-known/did.json"))).await;
let t = s.space_notify.now();
for (i, (did, read)) in [(&served, true), (&edge, true), (&big, false), (&moved, false)].into_iter().enumerate() {
let got = register(s, &h, &w.space, &format!("{did}#atproto_space_syncer")).await;
assert_eq!(got.map(|_| ()), if read { Ok(()) } else { Err(UNRESOLVABLE.into()) }, "{did}");
// Read, its service auth verifies (and the writer is refused later); else none can.
let ok = token(&claims(s, did, alice), signer(&key));
let want = if read { "403 Forbidden" } else { "401 AuthenticationRequired" };
assert_eq!(notify(s, Some(&ok), &note(&w.space, did, &tid_at(t + i as u64), &[1; 32])).await, Err(want.into()), "{did}");
}
assert!(moved_asked.load(Ordering::SeqCst) > 0);
assert_eq!(target_asked.load(Ordering::SeqCst), 0, "a redirect is not followed");
let _ = std::fs::remove_dir_all(&w.dir);
}
/// With SSRF protection on, no `did:web` on `localhost` or an IP address is
/// read: not a syncer's, nor that of an issuer of service auth or of a
/// delegation token. No connection is made.
#[tokio::test]
async fn did_web_through_the_guard() {
let (_plc, plc_url) = Plc::start().await;
let dir = scratch("notify-guard");
let s: Shared = Arc::new(Service::open(&dir, Config { ssrf_protection: true, ..config(&plc_url) }).unwrap());
let alice = create(&s, "alice").await;
let sp = create_space(&s, &alice.1, "m").await;
let h = credentialed(&s, &alice, &sp, &alice.0).await;
let (port, connections) = counting().await;
let key = SigningKey::from_slice(&[12; 32]).unwrap();
let now = s.sessions.now();
for did in [format!("did:web:localhost%3A{port}"), format!("did:web:127.0.0.1%3A{port}")] {
assert_eq!(register(&s, &h, &sp, &format!("{did}#atproto_space_syncer")).await, Err(UNRESOLVABLE.into()), "{did}");
let write = token(&claims(&s, &did, &alice.0), signer(&key));
let got = notify(&s, Some(&write), &note(&sp, &did, &tid_at(s.space_notify.now()), &[1; 32])).await;
assert_eq!(got, Err("401 AuthenticationRequired".into()), "{did}");
let revoke = token(&json!({ "iss": did, "aud": alice.0, "lxm": REVOKE, "iat": now, "exp": now + 60 }), signer(&key));
let body = json!({ "space": space(&did, "x"), "credentials": ["j"] }).to_string();
assert_eq!(send(&s, Http::POST, REVOKE, &[], &authorization(&revoke), &body).await, Err("401 AuthenticationRequired".into()), "{did}");
let header = json!({ "alg": "ES256K", "typ": "atproto-space-delegation+jwt", "kid": "#atproto" });
let payload = json!({ "iss": did, "sub": sp, "aud": format!("{}#atproto_pds", alice.0), "iat": now, "exp": now + 60, "jti": "j" });
let delegated = jwt_of(&header, &payload, signer(&key));
let got = credential(&s, json!({ "space": sp, "credentialKid": client(1).kid, "delegationToken": delegated })).await;
assert_eq!(got, Err("400 InvalidDelegationToken".into()), "{did}");
}
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(connections.load(Ordering::SeqCst), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// A call as `send` makes it, from client address `client`: its answer,
/// and whether it paid its rate limits.
async fn paying(s: &Shared, client: &str, nsid: &str, headers: &HeaderMap, body: &str) -> (Result<(), String>, bool) {
let authorization = crate::authorization(headers);
let bearer = crate::sessions::Bearer::of(authorization.as_deref());
let call = Call { nsid, method: &Http::POST, params: &[], body: body.as_bytes(), bearer, headers, client: client.into(), charged: Default::default(), http: None };
let out = crate::answer(s, &call).await.map(|_| ()).map_err(|e| format!("{} {}", e.status, e.name));
(out, call.charged.get().is_some())
}
/// Service auth pays its rate limits once the checks before its issuer's
/// document is read have passed, and before it is read: what is refused
/// before costs nothing, and a call over its limit is `429` with nothing
/// fetched (`spec/LIMITS.md`, "Rate limits").
#[tokio::test]
async fn service_auth_pays_before_fetching() {
let (_plc, plc_url) = Plc::start().await;
let dir = scratch("notify-pays");
let s = open_with(&dir, &plc_url, |c| c.rate_limits = true);
let (port, connections) = counting().await;
let iss = format!("did:web:localhost%3A{port}");
let key = SigningKey::from_slice(&[13; 32]).unwrap();
let now = s.sessions.now();
let auth = |iss: &str, lxm: &str| authorization(&token(&json!({ "iss": iss, "aud": HOST, "lxm": lxm, "iat": now, "exp": now + 60 }), signer(&key)));
let write = note(&space(HOST, "x"), &iss, &tid_at(s.space_notify.now()), &[1; 32]).to_string();
let (a, b) = ("198.51.100.1", "198.51.100.2");
// Refused before the issuer's document is read: nothing paid.
for (h, want) in [
(HeaderMap::new(), "401 MissingJwt"),
(authorization("Bearer abc"), "401 BadJwt"),
(auth(&iss, REVOKE), "401 BadJwtLexiconMethod"),
(auth("localhost", NOTIFY_WRITE), "401 BadJwtIss"),
] {
assert_eq!(paying(&s, a, NOTIFY_WRITE, &h, &write).await, (Err(want.into()), false), "{want}");
}
assert_eq!(connections.load(Ordering::SeqCst), 0);
// Past them it pays, then reads the document.
assert_eq!(paying(&s, a, NOTIFY_WRITE, &auth(&iss, NOTIFY_WRITE), &write).await, (Err("401 AuthenticationRequired".into()), true));
eventually("the issuer's host to be asked", || connections.load(Ordering::SeqCst) > 0).await;
let before = connections.load(Ordering::SeqCst);
// Another client, its global limit spent: 429, nothing fetched.
let method = Http::GET;
let none = HeaderMap::new();
for _ in 0..3000 {
let call = Call { nsid: "com.atproto.server.describeServer", method: &method, params: &[], body: b"", bearer: crate::sessions::Bearer::None, headers: &none, client: b.into(), charged: Default::default(), http: None };
assert!(crate::limits::charge(&s, &call, None, None).is_ok());
}
let revoke = json!({ "space": space(HOST, "x"), "credentials": ["j"] }).to_string();
for (nsid, body) in [(NOTIFY_WRITE, &write), (REVOKE, &revoke)] {
assert_eq!(paying(&s, b, nsid, &auth(&iss, nsid), body).await, (Err("429 RateLimitExceeded".into()), true), "{nsid}");
}
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(connections.load(Ordering::SeqCst), before);
let _ = std::fs::remove_dir_all(&dir);
}
/// The four methods are tools, none destructive.
#[test]
fn tools() {
@@ -843,9 +1142,12 @@ pub(crate) fn frames_of_each_kind(q: &str, m: &str) -> Vec<Vec<Json>> {
vec![queued(q, r1, &[1; 32], at(1))],
vec![queued(q, r2, &[2; 32], at(2))],
vec![unqueued(q, r2)],
// A registration as kept before registrants were, and as kept now.
vec![json!({ "t": REGISTERED, "space": m, "service": SYNCER_SERVICE, "expires": 5_000 })],
vec![json!({ "t": REGISTERED, "space": m, "service": SYNCER_DOWN, "expires": 6_000 })],
vec![json!({ "t": UNREGISTERED, "space": m, "service": SYNCER_DOWN })],
vec![registered(m, SYNCER_DOWN, 6_000, &client(1).kid)],
vec![unregistered(m, SYNCER_DOWN)],
// As a registration that takes the space's expired ones out logs it.
vec![unregistered(m, SYNCER_SERVICE), registered(m, SYNCER_SERVICE, 7_000, &client(2).kid)],
vec![json!({ "t": DROPPED, "space": m }), owed(m, SYNCER_SERVICE, at(0))],
vec![owed(m, SYNCER_SERVICE, at(1))],
vec![paid(m, SYNCER_SERVICE)],
crates/pds-server/src/blobs.rs+1−1
@@ -599,7 +599,7 @@ pub(crate) async fn upload(
) -> Response {
let authorization = crate::authorization(&headers);
let bearer = crate::sessions::Bearer::of(authorization.as_deref());
let client = crate::limits::client(&headers, peer.map(|Extension(p)| p.0));
let client = crate::limits::client(&svc.config.trusted_proxies, &headers, peer.map(|Extension(p)| p.0));
let mut call = Call { nsid: UPLOAD, method: &method, params: &[], body: &[], bearer, headers: &headers, client, charged: OnceLock::new(), http: None };
let grant = match crate::scopes::look(&svc, &call, &headers).await {
Ok(g) => g,
crates/pds-server/src/email.rs+14−5
crates/pds-server/src/events.rs+1−1
crates/pds-server/src/invites.rs+6−1
crates/pds-server/src/lib.rs+16−5
crates/pds-server/src/lifecycle.rs+79−71
crates/pds-server/src/limits.rs+158−37
crates/pds-server/src/log.rs+32−1
crates/pds-server/src/mcp.rs+1−1
crates/pds-server/src/oauth.rs+413−63
476 lines changed: not loaded until asked for.
crates/pds-server/src/outbound.rs+291−80
crates/pds-server/src/proxy.rs+132−26
crates/pds-server/src/replay.rs+6−0
crates/pds-server/src/scopes.rs+19−7
crates/pds-server/src/server.rs+22−9
crates/pds-server/src/space_authz.rs+117−38
crates/pds-server/src/space_credentials.rs+23−7
crates/pds-server/src/space_notify.rs+137−48
crates/pds-server/src/space_repo.rs+97−1
harness/checks/email.mjs+84−1
harness/checks/lifecycle.mjs+104−5
harness/checks/limits.mjs+170−4
harness/checks/oauth-clients.mjs+5−5
harness/checks/oauth-limits.mjs+104−2
harness/checks/oauth.mjs+90−14
harness/checks/proxy.mjs+38−0
harness/lib/env.mjs+9−1
harness/lib/oauth.mjs+11−0
harness/lib/services.mjs+55−0
harness/spaces/compare.mjs+16−1
harness/spaces/credentials.mjs+28−2
harness/spaces/policies.mjs+95−4
harness/spaces/ssrf.mjsnew+215−0
harness/spaces/sync.mjs+43−1
harness/compare.mjs+7−6
spec/EMAIL.md+29−5
spec/LIFECYCLE.md+82−10
spec/LIMITS.md+126−37
spec/OAUTH-CLIENTS.md+10−4
spec/OAUTH-SCOPES.md+21−8
spec/OAUTH.md+152−21
spec/PROXY.md+61−13
spec/SPACES-CREDENTIALS.md+95−17
spec/SPACES-POLICIES.md+58−12
spec/SPACES-REPO.md+12−3
spec/SPACES-SYNC.md+116−33
README.md+4−0