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

Spaces' issuer keys at scale: local keys, a day's window, a bound, kept

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:perf/issuer-keys-scale
.changeset/issuer-keys-scale.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: minor
---
# Spaces' issuer keys hold up at scale
A spaces token (a delegation token, credential or service auth) issued by an account on this server is now verified against the key the server already holds for it, with nothing read from the PLC directory. Other issuers' keys are used for `PDS_DID_CACHE_SECS` (an hour by default), then go on being used while they are read again in the background, up to the new `PDS_DID_CACHE_MAX_SECS` (a day by default), after which they are read again first. The server keeps up to one key for each 1 KiB of `PDS_CACHE_BYTES` (262,144 by default), forgetting the one used longest ago past that rather than all of them, and writes them to `PDS_DATA_DIR/issuer-keys` at shutdown and each minute they change, so a restart does not read every issuer's document again.
crates/pds-server/src/space_credentials/issuers.rsnew+680−0
680 lines changed: not loaded until asked for.
crates/pds-server/src/space_credentials/jwt.rs+21−177
@@ -3,14 +3,11 @@
//! an issuer's `#atproto` key from its DID document ("Issuers' keys") or a
//! client's JSON Web Key.
use crate::{Service, Shared};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use k256::ecdsa::signature::Verifier;
use pds_repo::Repo;
use serde_json::{Map, Value as Json, json};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
/// A compact JWT, its parts read: the header and payload, JSON objects; the
/// bytes signed, `<header>.<payload>` as sent; and the signature.
@@ -221,186 +218,33 @@ impl Key {
}
}
}
}
/// The most keys kept; past it, all are forgotten.
const KEYS_KEPT: usize = 10_000;
/// Issuers' keys, as their documents last gave them, and when each read
/// began, in milliseconds since the epoch; and each issuer's turn to read
/// its document ("Issuers' keys").
#[derive(Default)]
pub(crate) struct Keys {
kept: Mutex<HashMap<String, (Key, u64)>>,
/// The turns of the issuers some call reads, or waits to read.
turns: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
}
/// An issuer's turn to read its document: held, no other read of it goes on.
struct Turn<'a> {
keys: &'a Keys,
iss: String,
held: Option<tokio::sync::OwnedMutexGuard<()>>,
}
impl Drop for Turn<'_> {
fn drop(&mut self) {
drop(self.held.take());
let mut turns = lock(&self.keys.turns);
if turns
.get(&self.iss)
.is_some_and(|m| Arc::strong_count(m) == 1)
{
turns.remove(&self.iss);
}
}
}
impl Keys {
/// The key kept of `iss` and when its read began, if that was less than
/// `life` ms before `now`.
fn kept(&self, iss: &str, now: u64, life: u64) -> Option<(Key, u64)> {
lock(&self.kept)
.get(iss)
.filter(|(_, at)| now.saturating_sub(*at) < life)
.cloned()
}
fn keep(&self, iss: &str, key: Key, at: u64) {
let mut kept = lock(&self.kept);
if kept.len() >= KEYS_KEPT {
kept.clear();
}
kept.insert(iss.to_string(), (key, at));
}
fn mutex(&self, iss: &str) -> Arc<tokio::sync::Mutex<()>> {
lock(&self.turns)
.entry(iss.to_string())
.or_default()
.clone()
}
/// `iss`'s turn, once any read of it under way has ended.
async fn turn(&self, iss: &str) -> Turn<'_> {
let held = self.mutex(iss).lock_owned().await;
Turn {
keys: self,
iss: iss.to_string(),
held: Some(held),
}
}
/// `iss`'s turn, if no read of it is under way.
fn try_turn(&self, iss: &str) -> Option<Turn<'_>> {
let held = self.mutex(iss).try_lock_owned().ok();
// Made either way, so that dropping it forgets a turn no one holds.
let turn = Turn {
keys: self,
iss: iss.to_string(),
held,
};
turn.held.is_some().then_some(turn)
}
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Why a JWT does not verify against its issuer's key.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Unverified {
/// The issuer's document cannot be read, or names no `#atproto` key.
NoKey,
/// The signature does not verify against it.
Signature,
}
/// Verify `jwt`'s signature against `iss`'s `#atproto` key ("Issuers'
/// keys"). A key kept for less than `PDS_DID_CACHE_SECS` is tried first;
/// one kept for half that or more, if it verifies, is renewed after, with
/// no call waiting. With none kept, or one that does not verify, the
/// document is read, once at a time, and the token verifies if it verifies
/// against the key read then.
pub(crate) async fn verify_issuer(
s: &Shared,
iss: &str,
jwt: &Jwt,
high_s: bool,
) -> Result<(), Unverified> {
let alg = jwt.header("alg").unwrap_or_default();
let sig = jwt.signature.as_deref().unwrap_or_default();
let verifies = |k: &Key| k.verifies(alg, jwt.signed.as_bytes(), sig, high_s);
let keys = &s.space_credentials.keys;
let life = s.config.did_cache.saturating_mul(1000);
let now = s.limits.clock.now_ms();
let mut failed = None;
if let Some((k, at)) = keys.kept(iss, now, life) {
if verifies(&k) {
if now.saturating_sub(at).saturating_mul(2) >= life {
renew(s, iss);
/// The key as issuers' keys are kept (`issuers`): its curve, 0 for
/// secp256k1 and 1 for P-256, then its compressed point.
pub fn packed(&self) -> [u8; 34] {
let mut p = [0u8; 34];
match self {
Key::K256(k) => p[1..].copy_from_slice(k.to_sec1_point(true).as_bytes()),
Key::P256(k) => {
p[0] = 1;
p[1..].copy_from_slice(k.to_sec1_point(true).as_bytes());
}
return Ok(());
}
failed = Some(k);
}
let _turn = keys.turn(iss).await;
// Another call may have read it meanwhile.
if let Some((k, _)) = keys.kept(iss, s.limits.clock.now_ms(), life)
&& failed.as_ref() != Some(&k)
{
if verifies(&k) {
return Ok(());
}
failed = Some(k);
}
let began = s.limits.clock.now_ms();
let Some(key) = fetch_key(s, iss).await else {
return Err(if failed.is_some() {
Unverified::Signature
} else {
Unverified::NoKey
});
};
if life > 0 {
keys.keep(iss, key.clone(), began);
}
if verifies(&key) {
Ok(())
} else {
Err(Unverified::Signature)
p
}
}
/// Read `iss`'s document again, after the call that found its key half its
/// time old is answered: unless another read of it is under way, or one
/// ended since.
fn renew(s: &Shared, iss: &str) {
let (s, iss) = (s.clone(), iss.to_string());
tokio::spawn(async move {
let keys = &s.space_credentials.keys;
let Some(_turn) = keys.try_turn(&iss) else {
return;
};
let life = s.config.did_cache.saturating_mul(1000);
let began = s.limits.clock.now_ms();
if keys
.kept(&iss, began, life)
.is_some_and(|(_, at)| began.saturating_sub(at).saturating_mul(2) < life)
{
return;
}
if let Some(key) = fetch_key(&s, &iss).await {
keys.keep(&iss, key, began);
/// The key `packed` made.
pub fn unpacked(p: &[u8; 34]) -> Option<Key> {
match p[0] {
0 => k256::ecdsa::VerifyingKey::from_sec1_bytes(&p[1..])
.ok()
.map(Key::K256),
1 => p256::ecdsa::VerifyingKey::from_sec1_bytes(&p[1..])
.ok()
.map(Key::P256),
_ => None,
}
});
}
/// `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> {
Key::of_document(&crate::space_authz::document(s, did).await?, did)
}
}
#[cfg(test)]
crates/pds-server/src/space_credentials/tests.rs+117−9
@@ -16,11 +16,12 @@ use std::sync::Arc;
use std::sync::atomic::Ordering;
/// A PLC directory as `testing::plc` serves one, taking any operation, whose
/// documents a test may replace.
/// documents a test may replace, counting the reads of each.
#[derive(Clone, Default)]
pub(crate) struct Directory {
ops: Arc<std::sync::Mutex<HashMap<String, Json>>>,
docs: Arc<std::sync::Mutex<HashMap<String, Json>>>,
reads: Arc<std::sync::Mutex<HashMap<String, usize>>>,
}
impl Directory {
@@ -37,6 +38,7 @@ impl Directory {
StatusCode::OK
}
async fn get_doc(State(d): State<Directory>, Path(did): Path<String>) -> Response {
*d.reads.lock().unwrap().entry(did.clone()).or_default() += 1;
let doc = d.docs.lock().unwrap().get(&did).cloned().or_else(|| {
d.ops
.lock()
@@ -87,6 +89,20 @@ impl Directory {
.unwrap()
.insert(did.to_string(), did_document(did, &op));
}
/// Serve the document of `did`, no account's, with `key` its `#atproto` key.
fn serve(&self, did: &str, key: &k256::ecdsa::SigningKey) {
let op = json!({ "verificationMethods": { "atproto": crate::plc::did_key(key.verifying_key()) }, "alsoKnownAs": [], "services": {} });
self.docs
.lock()
.unwrap()
.insert(did.to_string(), did_document(did, &op));
}
/// How many times `did`'s document was read.
fn reads(&self, did: &str) -> usize {
self.reads.lock().unwrap().get(did).copied().unwrap_or(0)
}
}
/// A JWT of these parts, its signature `sign` makes of the bytes signed.
@@ -341,7 +357,7 @@ fn names(payload: &Json) -> Vec<&str> {
/// Whether `token` is signed, low-S, by `did`'s key as the directory serves it.
async fn signed_by(s: &Shared, did: &str, token: &str) -> bool {
let jwt = Jwt::parse(token).unwrap();
jwt::verify_issuer(s, did, &jwt, false).await.is_ok()
issuers::verify_issuer(s, did, &jwt, false).await.is_ok()
}
struct World {
@@ -1265,32 +1281,45 @@ async fn credentials_are_verified_row_by_row() {
let _ = std::fs::remove_dir_all(&w.dir);
}
/// An issuer no account here is, its document served with `key`, and a
/// space of it.
fn elsewhere(w: &World, key: &k256::ecdsa::SigningKey) -> (&'static str, String) {
let did = "did:plc:zzzzzzzzzzzzzzzzzzzzzzzz";
w.directory.serve(did, key);
(did, format!("at://{did}/space/com.example.forum/main"))
}
#[tokio::test]
async fn a_rotated_key_is_read_again() {
// Issuers' keys kept, as they are with `PDS_DID_CACHE_SECS` above 0.
let w = world_with("cred-rotated", |c| c.did_cache = 3600).await;
let s = &w.s;
let c = client(1);
let alice = w.alice.0.clone();
let first = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
let (iss, space) = elsewhere(&w, &first);
let header = json!({ "alg": "ES256K", "typ": CREDENTIAL_TYP, "kid": "#atproto" });
let n = now(s);
let payload = json!({ "iss": alice, "sub": w.space, "cnf": { "kid": c.kid }, "iat": n, "exp": n + 600, "jti": "j" });
let payload = json!({ "iss": iss, "sub": space, "cnf": { "kid": c.kid }, "iat": n, "exp": n + 600, "jti": "j" });
let bob = w.bob.0.as_str();
let check = |token: &str| {
let h = signed(&c, token, bob);
async move { verify(s, &h, bob).await }
};
let old = jwt_of(&header, &payload, account_key(s, &alice));
let old = jwt_of(&header, &payload, k256_key(&first));
check(&old).await.unwrap();
assert_eq!(w.directory.reads(iss), 1);
let rotated = k256::ecdsa::SigningKey::from_slice(&[43u8; 32]).unwrap();
w.directory.rotate(&alice, &rotated);
// The key kept still verifies what it signed, until a token signed with another is sent.
w.directory.serve(iss, &rotated);
// The key kept still verifies what it signed, with nothing read, until
// a token signed with another is sent.
check(&old).await.unwrap();
assert_eq!(w.directory.reads(iss), 1);
let new = jwt_of(&header, &payload, k256_key(&rotated));
check(&new).await.unwrap();
assert_eq!(w.directory.reads(iss), 2);
assert_eq!(check(&old).await, Err("401 BadJwtSignature".into()));
// Service auth, too, with a high-S signature.
let p = json!({ "iss": alice, "aud": w.bob.0, "lxm": NOTIFY, "exp": n + 60 });
let p = json!({ "iss": iss, "aud": w.bob.0, "lxm": NOTIFY, "exp": n + 60 });
let t = jwt_of(&json!({ "alg": "ES256K" }), &p, |m| {
high_s(k256_key(&rotated)(m))
});
@@ -1298,7 +1327,7 @@ async fn a_rotated_key_is_read_again() {
revoke(
s,
Some(&format!("Bearer {t}")),
json!({ "space": w.space, "credentials": ["x"] })
json!({ "space": space, "credentials": ["x"] })
)
.await,
Ok(Json::Null)
@@ -1306,6 +1335,85 @@ async fn a_rotated_key_is_read_again() {
let _ = std::fs::remove_dir_all(&w.dir);
}
#[tokio::test]
async fn an_account_here_is_held_to_its_own_key_first() {
let w = world("cred-held").await;
let s = &w.s;
let c = client(1);
let alice = w.alice.0.clone();
let rotated = k256::ecdsa::SigningKey::from_slice(&[43u8; 32]).unwrap();
w.directory.rotate(&alice, &rotated);
let header = json!({ "alg": "ES256K", "typ": CREDENTIAL_TYP, "kid": "#atproto" });
let n = now(s);
let payload = json!({ "iss": alice, "sub": w.space, "cnf": { "kid": c.kid }, "iat": n, "exp": n + 600, "jti": "j" });
let bob = w.bob.0.as_str();
let check = |token: &str| {
let h = signed(&c, token, bob);
async move { verify(s, &h, bob).await }
};
let before = w.directory.reads(&alice);
// Signed with the key the server holds: nothing read, whatever her
// document says, though no key is kept (`PDS_DID_CACHE_SECS=0`).
for _ in 0..3 {
check(&jwt_of(&header, &payload, account_key(s, &alice)))
.await
.unwrap();
}
assert_eq!(w.directory.reads(&alice), before);
// Signed with another, it is held to her document as any issuer's is.
check(&jwt_of(&header, &payload, k256_key(&rotated)))
.await
.unwrap();
assert_eq!(w.directory.reads(&alice), before + 1);
let other = k256::ecdsa::SigningKey::from_slice(&[44u8; 32]).unwrap();
assert_eq!(
check(&jwt_of(&header, &payload, k256_key(&other))).await,
Err("401 BadJwtSignature".into())
);
let _ = std::fs::remove_dir_all(&w.dir);
}
#[tokio::test]
async fn a_key_past_its_time_is_used_while_it_is_read_again() {
let w = world_with("cred-renewed", |c| {
c.did_cache = 10;
c.did_cache_max = 100;
})
.await;
let s = &w.s;
let key = k256::ecdsa::SigningKey::from_slice(&[42u8; 32]).unwrap();
let (iss, space) = elsewhere(&w, &key);
let n = now(s);
let p = json!({ "iss": iss, "aud": w.bob.0, "lxm": NOTIFY, "exp": n + 600 });
let t = jwt_of(&json!({ "alg": "ES256K" }), &p, k256_key(&key));
let send = || {
let body = json!({ "space": space, "credentials": ["x"] });
let auth = format!("Bearer {t}");
async move { revoke(s, Some(&auth), body).await }
};
let skew = |secs| s.limits.clock.skew.store(secs, Ordering::SeqCst);
send().await.unwrap();
send().await.unwrap();
assert_eq!(w.directory.reads(iss), 1);
// Past `PDS_DID_CACHE_SECS`: answered with the key kept, read again after.
skew(20);
send().await.unwrap();
for _ in 0..200 {
if w.directory.reads(iss) == 2 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(w.directory.reads(iss), 2);
send().await.unwrap();
assert_eq!(w.directory.reads(iss), 2);
// Past `PDS_DID_CACHE_MAX_SECS` since that read: read first.
skew(200);
send().await.unwrap();
assert_eq!(w.directory.reads(iss), 3);
let _ = std::fs::remove_dir_all(&w.dir);
}
#[tokio::test]
async fn revocations_take_service_auth() {
let w = world("cred-revoke").await;
crates/pds-server/src/cache.rs+5−0
@@ -528,6 +528,11 @@ impl Slot {
slot
}
/// The account's signing key, its store loaded or not.
pub fn signing_key(&self) -> &SigningKey {
self.key.get()
}
/// Compact its store's log from now on, the table put in place under its lock.
fn compacted(&self, st: &Store) {
let fold = crate::checkpoint::AccountFold {
crates/pds-server/src/lib.rs+12−1
@@ -150,8 +150,15 @@ pub(crate) struct Config {
/// `com.atproto.space.importRepo` takes (`PDS_BLOB_UPLOAD_LIMIT`,
/// `spec/LIMITS.md`); `describeServer` answers it.
pub blob_upload_limit: u64,
/// How long, in seconds, a DID document fetched from the directory is served.
/// How long, in seconds, a DID document fetched from the directory is
/// served, and a spaces token's issuer's key used with no read
/// (`PDS_DID_CACHE_SECS`).
pub did_cache: u64,
/// How long, in seconds, a spaces token's issuer's key is used at all,
/// read again in the background past `did_cache`: `did_cache` where
/// that is more (`PDS_DID_CACHE_MAX_SECS`, `spec/SPACES-CREDENTIALS.md`,
/// "Issuers' keys").
pub did_cache_max: u64,
/// How long after its input is checked `createSession` answers, at the soonest.
pub login_floor: std::time::Duration,
/// How long after its body is checked OAuth's sign-in answers, at the soonest.
@@ -276,6 +283,7 @@ impl Config {
blobs::DEFAULT_UPLOAD_LIMIT,
)?,
did_cache: limits::env_u64("PDS_DID_CACHE_SECS", 3600)?,
did_cache_max: limits::env_u64("PDS_DID_CACHE_MAX_SECS", 86_400)?,
login_floor: std::time::Duration::from_millis(350),
sign_in_floor: std::time::Duration::from_millis(400),
mailer: email::Mailer::from_env()?,
@@ -841,6 +849,8 @@ pub fn run() {
cache::sweep_every(&svc);
// Notifications kept when the server stopped are sent again when due.
space_notify::start(&svc);
// Issuers' keys the last run kept are read back while it serves.
space_credentials::issuers::start(&svc);
let signal = limits::serve(listener, app, stop).await;
ops::shutdown(&svc, signal).await
})
@@ -1519,6 +1529,7 @@ mod testing {
max_import: 5 << 20,
blob_upload_limit: crate::blobs::DEFAULT_UPLOAD_LIMIT,
did_cache: 0,
did_cache_max: 86_400,
login_floor: std::time::Duration::ZERO,
sign_in_floor: std::time::Duration::ZERO,
mailer: Default::default(),
crates/pds-server/src/ops.rs+12−6
@@ -521,11 +521,13 @@ pub(crate) fn signals() -> impl Future<Output = &'static str> {
}
/// Shut down, the server having stopped taking connections and its requests
/// finished: close the firehose's subscriptions, close the logs and sync
/// what is written (`settle`), export the spans held, leave the mark of a
/// shutdown, say so, and exit 0. The mark is left only once `settle` has
/// answered that all this run wrote is on disk: where it fails, or the
/// process is killed before the mark, the next start is as after a kill.
/// finished: close the firehose's subscriptions, write the issuers' keys
/// kept (`space_credentials::issuers`, a cache, not synced), close the logs
/// and sync what is written (`settle`), export the spans held, leave the
/// mark of a shutdown, say so, and exit 0. The mark is left only once
/// `settle` has answered that all this run wrote is on disk: where it
/// fails, or the process is killed before the mark, the next start is as
/// after a kill.
/// It is so too, but for its `recovered` line, where what this run found
/// was not yet made durable (`mark`), which nothing here waits for.
pub(crate) async fn shutdown(svc: &Shared, signal: &'static str) -> ! {
@@ -537,7 +539,11 @@ pub(crate) async fn shutdown(svc: &Shared, signal: &'static str) -> ! {
tokio::time::sleep(Duration::from_millis(25)).await;
}
let s = svc.clone();
let synced = tokio::task::spawn_blocking(move || settle(&s)).await;
let synced = tokio::task::spawn_blocking(move || {
crate::space_credentials::issuers::write(&s);
settle(&s)
})
.await;
if let Some(e) = &ops().exporter {
e.flush(Instant::now() + FLUSH).await;
}
crates/pds-server/src/space_credentials.rs+7−5
@@ -17,6 +17,7 @@
//! (`space_notify`).
mod attestation;
pub(crate) mod issuers;
pub(crate) mod jwt;
#[cfg(test)]
pub(crate) mod tests;
@@ -30,7 +31,8 @@ use crate::{
opt, read, required,
};
use axum::http::{HeaderMap, header};
use jwt::{Jwt, Unverified};
use issuers::Unverified;
use jwt::Jwt;
use pds_repo::data::valid_did;
use pds_space::SpaceRef;
use pds_store::Wal;
@@ -79,7 +81,7 @@ pub(crate) fn handler(nsid: &str) -> Option<Handler> {
pub(crate) struct Credentials {
/// Each revoked credential, by the digest of its space and `jti`.
revoked: Mutex<Held<[u8; 32]>>,
keys: jwt::Keys,
keys: issuers::Keys,
}
/// A revocation's digest: SHA-256 of the space, a zero byte and the `jti`.
@@ -365,7 +367,7 @@ async fn delegation(s: &Shared, token: &str) -> Option<(String, String)> {
if jwt.claim("aud") != Some(format!("{}#atproto_pds", sr.authority).as_str()) {
return None;
}
jwt::verify_issuer(s, iss, &jwt, false).await.ok()?;
issuers::verify_issuer(s, iss, &jwt, false).await.ok()?;
// Kept until 5 seconds after its `exp`, while it could still be taken.
let until = (exp + SKEW).ceil().clamp(0.0, u64::MAX as f64) as u64;
s.check_and_record(&format!("delegation {iss} {jti}"), until)
@@ -474,7 +476,7 @@ pub(crate) async fn verify_space_credential(
return refused("BadJwt", "Credential iss is not a DID");
};
crate::limits::charge(s, call, None, None)?;
match jwt::verify_issuer(s, iss, &jwt, false).await {
match issuers::verify_issuer(s, iss, &jwt, false).await {
Ok(()) => {}
Err(Unverified::NoKey) => {
return refused("BadJwtIss", "Could not resolve the credential's issuer key");
@@ -627,7 +629,7 @@ pub(crate) async fn service_auth(
return refused("BadJwtIss", "Bad jwt iss");
}
crate::limits::charge(s, call, None, None)?;
match jwt::verify_issuer(s, did, &jwt, true).await {
match issuers::verify_issuer(s, did, &jwt, true).await {
Ok(()) => Ok((iss.to_string(), jwt.claim("aud").map(str::to_string))),
Err(Unverified::NoKey) => refused(
"AuthenticationRequired",
harness/checks/limits.mjs+27−1
@@ -1337,6 +1337,32 @@ async function plcConnections() {
count('PLC connections', true)
}
/// An issuer that is an account here: authorizeSpaceSync with a delegation
/// token the server signed for one of its accounts, of a space another of
/// its accounts made, public: taken, with nothing read of the user's
/// document from the directory (spec/SPACES-CREDENTIALS.md, "Issuers'
/// keys").
async function plcLocalIssuer() {
const ip = freshIp()
const [authority, user] = [await serverAccount(ip), await serverAccount(ip)]
if (authority.res.status !== 200 || user.res.status !== 200) await broke(CREATE_ACCOUNT, {}, 200, [authority.res, user.res])
const space = `at://${authority.did}/space/com.example.group/local`
const made = await send(cand, 'com.atproto.space.createSpace', { body: { spaceType: 'com.example.group', skey: 'local', policy: { $type: 'com.atproto.memberspace.policy', publicRead: true } }, token: authority.access, ip })
if (made.status !== 200) await broke('com.atproto.space.createSpace', { publicRead: true }, 200, made)
const request = { delegationToken: 'by an account here, of a space another account here made', space: 'public' }
const { P256Keypair } = await import('@atproto/crypto')
const credentialKey = (await P256Keypair.create()).did()
for (let i = 0; i < 3; i++) {
const before = plcProxy.countOf(`/${user.did}`)
const token = await send(cand, 'com.atproto.space.getDelegationToken', { params: { space }, token: user.access, ip })
if (token.status !== 200) await broke('com.atproto.space.getDelegationToken', {}, 200, token)
const traded = await send(cand, 'com.atproto.space.authorizeSpaceSync', { body: { space, credentialKey, delegationToken: token.body?.token }, ip })
const read = plcProxy.countOf(`/${user.did}`) - before
if (traded.status !== 200 || read) await broke('com.atproto.space.authorizeSpaceSync', request, '200, with nothing read of the user\'s document', { status: traded.status, error: traded.body?.error, reads: read })
}
count('an issuer that is an account here, nothing read', true)
}
/// How long until a connection the server is sent `bytes` on, and then
/// nothing, is closed; null if not within `ms`.
function closedAfter(bytes, ms) {
@@ -1697,7 +1723,7 @@ export async function limitsRun() {
const checks = [
signupLimit, loginLimit, handleLimit, uploadLimit, uploadSize, writeLimit, forwardedLimit, globalLimit, emailRequestLimits, passwordResetLimit, resetLimit, accountDeleteRequestLimit, deleteLimit, ...OAUTH_LIMIT_CHECKS,
sessionCap, appPasswordCap, ...OAUTH_SERVER_CHECKS, clientAddress, adminUnset, spacesPayFirst, didWebApart, outboundCaps, requestsOut, spaceImportSize,
firehoseMessages, firehoseSubscribers, plcDocuments, plcAtOnce, plcConnections, timeouts, diskFloor, blobQuota, blobTtl, openFiles, writesTogether, fileModes,
firehoseMessages, firehoseSubscribers, plcDocuments, plcAtOnce, plcConnections, plcLocalIssuer, timeouts, diskFloor, blobQuota, blobTtl, openFiles, writesTogether, fileModes,
]
for (const check of checks) {
if (ONLY && !ONLY.has(check.name)) continue
harness/spaces/compare.mjs+7−6
@@ -108,17 +108,18 @@ async function waitReady(url) {
await new Promise((ok) => setTimeout(ok, 20))
}
}
async function killServer() {
async function killServer(signal = 'SIGKILL') {
const dying = serverProc
if (!dying || serverExited) return
const gone = new Promise((ok) => dying.once('exit', ok))
dying.kill('SIGKILL')
dying.kill(signal)
await gone
}
/// Killed and started again on its data with `e`, as a variant of the run
/// needs (ssrf.mjs: SSRF protection on, then off again).
async function restartWith(e) {
await killServer()
/// Killed, or with `gently` shut down (SIGTERM), and started again on its
/// data with `e`, as a variant of the run needs (ssrf.mjs: SSRF protection
/// on, then off again; issuers.mjs: issuers' keys across a shutdown).
async function restartWith(e, { gently = false } = {}) {
await killServer(gently ? 'SIGTERM' : 'SIGKILL')
startServer(e)
await waitReady(cand.url)
}
harness/spaces/issuers.mjs+57−23
@@ -3,17 +3,26 @@
// run: how long the reference keeps a document, and whether a call waits
// for it, are not the page's to compare.
//
// The server is started again with PDS_DID_CACHE_SECS=6. The calls are
// revocations, each with service auth from a did:web issuer on localhost
// whose document an HTTP listener of the harness serves, recording when
// each read came and holding its answer up as the check says:
// The calls are revocations, each with service auth from a did:web issuer
// on localhost whose document an HTTP listener of the harness serves,
// recording when each read came and holding its answer up as the check
// says. The server is started again twice:
//
// With PDS_CACHE_BYTES=65536, so that it keeps at most 64 keys:
// 1. 8 revocations at once from an issuer not read before, its document
// 400 ms slow: each taken, with one read of it;
// 2. from another, a revocation 3.5 s after its document was read (past
// half of 6 s), its document now 1.5 s slow: answered within 1 s, and
// the document read once more after;
// 3. from that issuer, a revocation 7 s after that read: it waits for a
// 2. 65 more issuers, one revocation each, then one from the second of
// them, which must read nothing, and one from the first, which must
// read its document again: the key used longest ago is forgotten, and
// only it;
// 3. shut down (SIGTERM) and started again, a revocation from the second
// of those issuers reads nothing: its key outlived the restart.
//
// With PDS_DID_CACHE_SECS=3 and PDS_DID_CACHE_MAX_SECS=8:
// 4. from a new issuer, a revocation 3.5 s after its document was read,
// its document now 1.5 s slow: answered within 1 s, and the document
// read once more after;
// 5. from that issuer, a revocation 9 s after that read: it waits for a
// read of its own.
//
// And then the server is started again as the run starts it.
@@ -25,7 +34,7 @@ import { Secp256k1Keypair } from '@atproto/crypto'
const T = 'com.example.group'
const R = 'com.atproto.space.notifyCredentialsRevoked'
const LIFE_SECS = 6
const KEPT = 64
const now = () => Math.floor(Date.now() / 1000)
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url')
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms))
@@ -50,7 +59,8 @@ async function issuer() {
export async function checkIssuerKeys(h) {
const { cand, env, restartWith, fail, count, front } = h
await restartWith({ ...env, PDS_DID_CACHE_SECS: String(LIFE_SECS) })
const bounded = { ...env, PDS_CACHE_BYTES: String(KEPT * 1024) }
await restartWith(bounded)
const f = front()
const made = await fetch(`${cand.url}/xrpc/com.atproto.server.createAccount`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ handle: `${f}.test`, email: `${f}@example.com`, password: `pw-${f}` }) })
@@ -66,34 +76,58 @@ export async function checkIssuerKeys(h) {
await res.arrayBuffer()
return { status: res.status, ms: Date.now() - started }
}
const request = (what) => ({ iss: 'did:web:localhost%3A<port>', PDS_DID_CACHE_SECS: LIFE_SECS, ...what })
const request = (what) => ({ iss: 'did:web:localhost%3A<port>', ...what })
/// A revocation from `w` that must be taken, and read its document `reads` times.
async function taken(kind, w, reads, what) {
const before = w.reads.length
const r = await revoke(w)
if (r.status !== 200 || w.reads.length - before !== reads) await fail(cand, `issuers' keys: ${kind}`, request(what), `200, its document read ${reads} times`, { status: r.status, reads: w.reads.length - before })
}
// 1. One read at a time.
const first = await issuer()
{
const w = await issuer()
w.delayMs = 400
const answers = await Promise.all(Array.from({ length: 8 }, () => revoke(w)))
first.delayMs = 400
const answers = await Promise.all(Array.from({ length: 8 }, () => revoke(first)))
if (answers.some((a) => a.status !== 200)) await fail(cand, 'issuers\' keys: 8 revocations at once from an issuer not read before', request({ 'document slow by': '400 ms' }), 'each 200', answers.map((a) => a.status))
if (w.reads.length !== 1) await fail(cand, 'issuers\' keys: one read of an issuer\'s document at a time', request({ revocations: '8 at once' }), 'one read, the others waiting for it', `${w.reads.length} reads`)
if (first.reads.length !== 1) await fail(cand, 'issuers\' keys: one read of an issuer\'s document at a time', request({ revocations: '8 at once' }), 'one read, the others waiting for it', `${first.reads.length} reads`)
count('issuers\' keys: one read at a time')
w.close()
}
// 2. Renewed after the answer, and 3. read again once past the window.
// 2. The key used longest ago forgotten, and only it.
const many = []
for (let i = 0; i <= KEPT; i++) {
const w = await issuer()
many.push(w)
await taken('a revocation from an issuer not read before', w, 1, { PDS_CACHE_BYTES: KEPT * 1024 })
}
await taken('one key past the bound: a key used since', many[1], 0, { PDS_CACHE_BYTES: KEPT * 1024, issuers: KEPT + 2, 'the second of the last': 'used again' })
await taken('one key past the bound: the key used longest ago', many[0], 1, { PDS_CACHE_BYTES: KEPT * 1024, issuers: KEPT + 2, 'the first of the last': 'used again' })
count('issuers\' keys: the one used longest ago forgotten')
// 3. Kept across a shutdown.
await restartWith(bounded, { gently: true })
await sleep(1000)
await taken('after a shutdown and a start, a key kept before', many[1], 0, { restart: 'SIGTERM, then 1 s' })
count('issuers\' keys: kept across a shutdown')
for (const w of [first, ...many]) w.close()
// 4. Renewed after the answer, and 5. read again once past the window.
await restartWith({ ...env, PDS_DID_CACHE_SECS: '3', PDS_DID_CACHE_MAX_SECS: '8' })
{
const windows = { PDS_DID_CACHE_SECS: 3, PDS_DID_CACHE_MAX_SECS: 8 }
const w = await issuer()
const first = await revoke(w)
if (first.status !== 200 || w.reads.length !== 1) await fail(cand, 'issuers\' keys: a revocation from an issuer not read before', request({}), '200, its document read once', { status: first.status, reads: w.reads.length })
await taken('a revocation from an issuer not read before', w, 1, windows)
await sleep(w.reads[0] + 3500 - Date.now())
w.delayMs = 1500
const stale = await revoke(w)
if (stale.status !== 200 || stale.ms >= 1000) await fail(cand, 'issuers\' keys: a key kept past half its time, answered at once', request({ 'since its read': '3.5 s', 'document slow by': '1500 ms' }), '200 within 1000 ms', stale)
if (stale.status !== 200 || stale.ms >= 1000) await fail(cand, 'issuers\' keys: a key kept past PDS_DID_CACHE_SECS, answered at once', request({ ...windows, 'since its read': '3.5 s', 'document slow by': '1500 ms' }), '200 within 1000 ms', stale)
await sleep(2500)
if (w.reads.length !== 2) await fail(cand, 'issuers\' keys: a key kept past half its time, renewed after the answer', request({ 'since its read': '3.5 s' }), 'its document read once more', `${w.reads.length - 1} reads after the first`)
if (w.reads.length !== 2) await fail(cand, 'issuers\' keys: a key kept past PDS_DID_CACHE_SECS, renewed after the answer', request({ ...windows, 'since its read': '3.5 s' }), 'its document read once more', `${w.reads.length - 1} reads after the first`)
count('issuers\' keys: renewed after the answer')
await sleep(w.reads[1] + 7000 - Date.now())
await sleep((w.reads[1] ?? Date.now()) + 9000 - Date.now())
const expired = await revoke(w)
if (expired.status !== 200 || expired.ms < 1400 || w.reads.length !== 3) await fail(cand, 'issuers\' keys: a key kept past its time, read again before it is used', request({ 'since its last read': '7 s', 'document slow by': '1500 ms' }), '200 after waiting for a read of its own: at least 1400 ms, one read more', { ...expired, reads: w.reads.length })
if (expired.status !== 200 || expired.ms < 1400 || w.reads.length !== 3) await fail(cand, 'issuers\' keys: a key kept past PDS_DID_CACHE_MAX_SECS, read again before it is used', request({ ...windows, 'since its last read': '9 s', 'document slow by': '1500 ms' }), '200 after waiting for a read of its own: at least 1400 ms, one read more', { ...expired, reads: w.reads.length })
count('issuers\' keys: read again past their time')
w.close()
}
spec/LIMITS.md+6−2
spec/SPACES-CREDENTIALS.md+54−24
spec/STORE.md+7−2