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

Spaces' issuer keys renewed in the background; PLC reads reuse connections

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:perf/issuer-keys
.changeset/issuer-keys.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# Spaces' tokens no longer wait for the PLC directory
The key of a delegation token's, a space credential's or a revocation's issuer is kept for `PDS_DID_CACHE_SECS` (an hour by default) rather than five minutes. Once it is half that old, a token it verifies is answered at once and the issuer's document is read again after it, so a busy issuer's calls never wait for the directory; calls that need the same issuer's document at once share one read of it. Reads from the PLC directory now reuse an open connection instead of making a new one each time, which saves a round trip and a TLS handshake on each; posts to it still take a connection of their own.
crates/pds-server/src/space_credentials/jwt.rs+138−29
@@ -3,14 +3,14 @@
//! an issuer's `#atproto` key from its DID document ("Issuers' keys") or a
//! client's JSON Web Key.
use crate::Service;
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::Mutex;
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.
@@ -223,14 +223,90 @@ impl Key {
}
}
/// 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.
const KEYS_KEPT: usize = 10_000;
/// Issuers' keys, as their documents last gave them, and when.
/// 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(Mutex<HashMap<String, (Key, u64)>>);
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)]
@@ -241,51 +317,84 @@ pub(crate) enum Unverified {
Signature,
}
/// Verify `jwt`'s signature against `iss`'s `#atproto` key. A key kept is
/// tried first; if it does not verify, the document is read again, and the
/// token verifies if it verifies against the key read then.
/// 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: &Service,
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 now = s.sessions.now();
let kept = keys_of(&s.space_credentials.keys)
.get(iss)
.filter(|(_, at)| now < at + KEY_KEPT)
.map(|(k, _)| k.clone());
if let Some(k) = &kept
&& k.verifies(alg, jwt.signed.as_bytes(), sig, high_s)
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);
}
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)
{
return Ok(());
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 kept.is_some() {
return Err(if failed.is_some() {
Unverified::Signature
} else {
Unverified::NoKey
});
};
{
let mut keys = keys_of(&s.space_credentials.keys);
if keys.len() >= KEYS_KEPT {
keys.clear();
}
keys.insert(iss.to_string(), (key.clone(), now));
if life > 0 {
keys.keep(iss, key.clone(), began);
}
if key.verifies(alg, jwt.signed.as_bytes(), sig, high_s) {
if verifies(&key) {
Ok(())
} else {
Err(Unverified::Signature)
}
}
fn keys_of(k: &Keys) -> std::sync::MutexGuard<'_, HashMap<String, (Key, u64)>> {
k.0.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
/// 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);
}
});
}
/// `did`'s `#atproto` key, from its document as served now: a `did:plc`'s
crates/pds-server/src/space_credentials/tests.rs+9−4
@@ -271,7 +271,7 @@ pub(crate) async fn authorized(s: &Shared, body: Json) -> Result<Json, String> {
const AUTHORIZE: &str = "com.atproto.space.authorizeSpaceSync";
async fn verify(
s: &Service,
s: &Shared,
headers: &HeaderMap,
audience: &str,
) -> Result<SpaceCredential, String> {
@@ -339,7 +339,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: &Service, did: &str, token: &str) -> bool {
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()
}
@@ -356,9 +356,13 @@ struct World {
}
async fn world(name: &str) -> World {
world_with(name, |_| {}).await
}
async fn world_with(name: &str, change: impl FnOnce(&mut crate::Config)) -> World {
let (directory, plc) = Directory::start().await;
let dir = scratch(name);
let s = open(&dir, &plc);
let s = open_with(&dir, &plc, change);
let alice = create(&s, "alice").await;
let bob = create(&s, "bob").await;
let space = format!("at://{}/space/com.example.forum/main", alice.0);
@@ -1263,7 +1267,8 @@ async fn credentials_are_verified_row_by_row() {
#[tokio::test]
async fn a_rotated_key_is_read_again() {
let w = world("cred-rotated").await;
// 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();
crates/pds-server/src/plc.rs+26−6
@@ -198,11 +198,12 @@ fn did_of(signed: &[u8]) -> String {
format!("did:plc:{}", &base32_encode(&Sha256::digest(signed))[..24])
}
/// The HTTP client the server reaches the PLC directory with. It keeps no
/// The HTTP client the server posts to the PLC directory with. It keeps no
/// idle connection: a server may close one it holds idle (Node's HTTP server
/// does after 5 seconds) just as the next request goes out on it, which then
/// fails, perhaps after the server has read it. Each request takes a
/// connection of its own, and none waits for ever.
/// fails, perhaps after the server has read it. Each post takes a
/// connection of its own, and none waits for ever (`spec/LIMITS.md`, "The
/// PLC directory").
pub fn client() -> reqwest::Result<reqwest::Client> {
reqwest::Client::builder()
.no_proxy()
@@ -212,6 +213,22 @@ pub fn client() -> reqwest::Result<reqwest::Client> {
.build()
}
/// The HTTP client the server reads from the directory with: as `client`,
/// but keeping a connection unused for up to 90 seconds, so that a read
/// after another needs no new connection and TLS handshake. A read changes
/// nothing, so one that fails over a connection the directory closed is
/// sent again over one of its own (`document`). Built as `client` is, so it
/// fails only where that did first, and the server would not have started.
static READS: std::sync::LazyLock<reqwest::Result<reqwest::Client>> =
std::sync::LazyLock::new(|| {
reqwest::Client::builder()
.no_proxy()
.pool_idle_timeout(std::time::Duration::from_secs(90))
.connect_timeout(std::time::Duration::from_secs(5))
.timeout(std::time::Duration::from_secs(15))
.build()
});
/// The most requests to the directory in flight at once, of every kind.
const AT_ONCE: usize = 8;
/// How long a request waits for its turn before it is answered as if the
@@ -228,11 +245,14 @@ async fn turn() -> Result<tokio::sync::SemaphorePermit<'static>, String> {
}
}
/// The JSON the directory serves at `url`, or None if it serves none (404).
/// Reading changes nothing, so a read that failed on its way is tried once more.
/// The JSON the directory serves at `url`, or None if it serves none (404):
/// read over a connection kept from an earlier read, if one is open.
/// Reading changes nothing, so a read that failed on its way is sent once
/// more, with `http`, over a connection of its own.
pub(crate) async fn document(http: &reqwest::Client, url: &str) -> Result<Option<Json>, String> {
let turn = turn().await?;
let res = match crate::ops::send(Target::Plc, http.get(url)).await {
let reads = READS.as_ref().unwrap_or(http);
let res = match crate::ops::send(Target::Plc, reads.get(url)).await {
Ok(res) => res,
Err(e) if !e.is_timeout() => crate::ops::send(Target::Plc, http.get(url))
.await
crates/pds-server/src/space_credentials.rs+4−4
@@ -217,7 +217,7 @@ async fn authorize_space_sync(s: Shared, b: Map<String, Json>) -> Result<Resp, X
/// The steps of `authorizeSpaceSync` (`spec/SPACES-CREDENTIALS.md`,
/// "authorizeSpaceSync") after its input is checked against the lexicon,
/// in order.
async fn authorize(s: &Service, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
async fn authorize(s: &Shared, b: &Map<String, Json>) -> Result<Resp, XrpcError> {
let (space, key) = (required(b, "space")?, required(b, "credentialKey")?);
let Some(sr) = SpaceRef::parse(space) else {
return invalid("space must be a valid space-ref");
@@ -346,7 +346,7 @@ fn space_not_found<T>() -> Result<T, XrpcError> {
/// The user a delegation token speaks for, and the space it names; None if
/// it fails ("Verifying a delegation token"). It is spent if it passes.
async fn delegation(s: &Service, token: &str) -> Option<(String, String)> {
async fn delegation(s: &Shared, token: &str) -> Option<(String, String)> {
let jwt = Jwt::parse(token)?;
let present = |k: &str| jwt.payload.get(k).is_some_and(|v| !v.is_null());
let shaped = jwt.signature.is_some()
@@ -407,7 +407,7 @@ fn refused<T>(name: &'static str, message: &str) -> Result<T, XrpcError> {
/// once the checks before its issuer's document is read have passed, and
/// before it is read (`spec/LIMITS.md`, "Rate limits").
pub(crate) async fn verify_space_credential(
s: &Service,
s: &Shared,
call: &Call<'_>,
audience: &str,
) -> Result<SpaceCredential, XrpcError> {
@@ -579,7 +579,7 @@ async fn notify_credentials_revoked(
/// the checks before its issuer's document is read have passed, and before
/// it is read (`spec/LIMITS.md`, "Rate limits").
pub(crate) async fn service_auth(
s: &Service,
s: &Shared,
call: &Call<'_>,
lxm: &str,
) -> Result<(String, Option<String>), XrpcError> {
crates/pds-server/src/space_notify.rs+1−1
@@ -1512,7 +1512,7 @@ async fn change(
/// credential is verified, and a write checks the free space
/// (`limits::guard`).
async fn host_of(
s: &Service,
s: &Shared,
call: &Call<'_>,
space: &str,
) -> Result<(SpaceRef, Arc<Account>), XrpcError> {
harness/checks/limits.mjs+24−1
@@ -1314,6 +1314,29 @@ async function plcAtOnce() {
count('PLC calls at once', true)
}
/// Of 6 accounts made one after another, each post to the directory the
/// first request on a connection of its own, and the reads that follow
/// them over connections earlier reads left open (spec/LIMITS.md, "The PLC
/// directory").
async function plcConnections() {
// What each connection carried before, so that connections left open by
// earlier checks count too.
const before = plcProxy.connections.map((c) => c.length)
for (let i = 0; i < 6; i++) {
const made = await serverAccount(freshIp())
if (made.res.status !== 200) await broke(CREATE_ACCOUNT, { accounts: 6, 'one after another': true }, 200, made.res)
}
const request = { createAccount: 6, 'one after another': true }
const fresh = plcProxy.connections.map((c, i) => ({ earlier: before[i] ?? 0, now: c.slice(before[i] ?? 0) })).filter((c) => c.now.length)
const isPost = (r) => r.startsWith('POST ')
const shared = fresh.filter((c) => c.now.some(isPost) && (c.earlier > 0 || !isPost(c.now[0]) || c.now.filter(isPost).length > 1))
if (shared.length) await broke('connections to the PLC directory', request, 'each post the first request on a connection of its own', shared)
const reads = fresh.flatMap((c) => c.now).filter((r) => r.startsWith('GET ')).length
const readOver = fresh.filter((c) => !c.now.some(isPost)).length
if (!reads || readOver >= reads) await broke('connections to the PLC directory', request, 'the reads over connections earlier reads left open: fewer connections than reads', { reads, connections: readOver })
count('PLC connections', 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) {
@@ -1674,7 +1697,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, timeouts, diskFloor, blobQuota, blobTtl, openFiles, writesTogether, fileModes,
firehoseMessages, firehoseSubscribers, plcDocuments, plcAtOnce, plcConnections, timeouts, diskFloor, blobQuota, blobTtl, openFiles, writesTogether, fileModes,
]
for (const check of checks) {
if (ONLY && !ONLY.has(check.name)) continue
harness/lib/plc-proxy.mjs+17−7
@@ -1,20 +1,25 @@
// A proxy between the server and the PLC directory, which counts the
// server's requests to it, by method and path, and how many were in flight
// at once, and may hold each up a while (spec/LIMITS.md, "The PLC
// directory"), or be down (spec/LIFECYCLE.md).
// at once, records the requests each connection carried, and may hold each
// up a while (spec/LIMITS.md, "The PLC directory"), or be down
// (spec/LIFECYCLE.md).
import { createServer } from 'node:http'
/// Start a proxy to the directory at `target`. Answers `{url, counts,
/// inFlight, maxInFlight, delayMs, down, close}`; set `delayMs` to hold each
/// request up that long before it is passed on, `maxInFlight` to 0 to
/// count afresh, and `down` to `'refuse'` to close each connection unanswered
/// or to `'error'` to answer each `500`, as a directory that cannot be read.
/// connections, inFlight, maxInFlight, delayMs, down, close}`; each of
/// `connections`, in the order they were made, is the list of its
/// requests, as `<method> <path>`. Set `delayMs` to hold each request up
/// that long before it is passed on, `maxInFlight` to 0 to count afresh,
/// and `down` to `'refuse'` to close each connection unanswered or to
/// `'error'` to answer each `500`, as a directory that cannot be read.
export async function startPlcProxy(target) {
const proxy = { counts: new Map(), inFlight: 0, maxInFlight: 0, delayMs: 0, down: null }
const proxy = { counts: new Map(), connections: [], inFlight: 0, maxInFlight: 0, delayMs: 0, down: null }
const carried = new WeakMap()
const s = createServer(async (req, res) => {
const key = `${req.method} ${decodeURIComponent(req.url)}`
proxy.counts.set(key, (proxy.counts.get(key) ?? 0) + 1)
carried.get(req.socket)?.push(key)
if (proxy.down === 'refuse') return req.socket.destroy()
if (proxy.down === 'error') {
res.writeHead(500)
@@ -39,6 +44,11 @@ export async function startPlcProxy(target) {
proxy.inFlight -= 1
}
})
s.on('connection', (socket) => {
const requests = []
carried.set(socket, requests)
proxy.connections.push(requests)
})
await new Promise((ok) => s.listen(0, '127.0.0.1', ok))
proxy.url = `http://127.0.0.1:${s.address().port}`
/// The requests counted whose path, decoded, is `path`, of any method.
harness/spaces/compare.mjs+9−3
@@ -17,8 +17,10 @@
// permissions, with space type declarations a third PDS publishes
// (scopes.mjs, spec/OAUTH-SCOPES.md, "Spaces"); and last, the
// server alone, the guard every request the spaces make goes through, with
// the server started again with SSRF protection on (ssrf.mjs). It stops at the
// first thing that differs, saying what was asked and what each answered.
// the server started again with SSRF protection on (ssrf.mjs), and how it
// keeps issuers' keys, started again with a short PDS_DID_CACHE_SECS
// (issuers.mjs). It stops at the first thing that differs, saying what was
// asked and what each answered.
//
// cd harness/spaces && npm ci # once
// node compare.mjs [--seed 1] [--accounts 3] [--space-steps 200] -- <command that starts the server>
@@ -48,6 +50,7 @@ import { checkPolicies } from './policies.mjs'
import { checkSpaceSync } from './sync.mjs'
import { checkSsrf } from './ssrf.mjs'
import { checkSpaceScopes, hostDeclarations } from './scopes.mjs'
import { checkIssuerKeys } from './issuers.mjs'
// ---- arguments and the one random source ------------------------------------------
@@ -366,8 +369,11 @@ await exported.statuses()
// publishes (scopes.mjs, spec/OAUTH-SCOPES.md, "Spaces").
await checkSpaceScopes({ ref, cand, accounts, createAccount, rand, differ, count })
// Last: the guard, with the server started again with SSRF protection on,
// and then as before (ssrf.mjs, spec/SPACES-SYNC.md).
// and then as before (ssrf.mjs, spec/SPACES-SYNC.md); and issuers' keys,
// with a short PDS_DID_CACHE_SECS, and then as before (issuers.mjs,
// spec/SPACES-CREDENTIALS.md).
await checkSsrf({ net, cand, env, restartWith, fail, count, front, rand })
await checkIssuerKeys({ cand, env, restartWith, fail, count, front })
console.error(`\nall checks agree (seed ${SEED}), ${accounts.length} accounts`)
for (const [kind, n] of Object.entries(counts).sort()) console.error(` ${kind.padEnd(56)} ${String(n).padStart(5)}`)
harness/spaces/issuers.mjsnew+102−0
@@ -0,0 +1,102 @@
// Issuers' keys, as the server keeps them (spec/SPACES-CREDENTIALS.md,
// "Issuers' keys"), held to the server alone, after the guard in the spaces
// 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:
//
// 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
// read of its own.
//
// And then the server is started again as the run starts it.
import crypto from 'node:crypto'
import { createServer } from 'node:http'
import { once } from 'node:events'
import { Secp256k1Keypair } from '@atproto/crypto'
const T = 'com.example.group'
const R = 'com.atproto.space.notifyCredentialsRevoked'
const LIFE_SECS = 6
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))
/// A did:web on localhost whose document a listener serves after `delayMs`,
/// recording the time each read came.
async function issuer() {
const w = { reads: [], delayMs: 0, key: await Secp256k1Keypair.create() }
const srv = createServer(async (req, res) => {
if (req.url !== '/.well-known/did.json') return res.writeHead(404).end()
w.reads.push(Date.now())
if (w.delayMs) await sleep(w.delayMs)
const doc = { '@context': ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/multikey/v1'], id: w.did, verificationMethod: [{ id: `${w.did}#atproto`, type: 'Multikey', controller: w.did, publicKeyMultibase: w.key.did().slice('did:key:'.length) }] }
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(doc))
})
srv.listen(0, '127.0.0.1')
await once(srv, 'listening')
w.did = `did:web:localhost%3A${srv.address().port}`
w.close = () => srv.close()
return w
}
export async function checkIssuerKeys(h) {
const { cand, env, restartWith, fail, count, front } = h
await restartWith({ ...env, PDS_DID_CACHE_SECS: String(LIFE_SECS) })
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}` }) })
if (made.status !== 200) await fail(cand, 'createAccount for the issuers\' keys checks', {}, 'an account', made.status)
const aud = (await made.json()).did
/// A revocation with service auth from `w`: its status, and how long it took.
async function revoke(w) {
const input = `${b64({ typ: 'JWT', alg: 'ES256K' })}.${b64({ iss: w.did, aud, lxm: R, iat: now(), exp: now() + 60, jti: crypto.randomBytes(16).toString('hex') })}`
const jwt = `${input}.${Buffer.from(await w.key.sign(new Uint8Array(Buffer.from(input)))).toString('base64url')}`
const started = Date.now()
const res = await fetch(`${cand.url}/xrpc/${R}`, { method: 'POST', headers: { authorization: `Bearer ${jwt}`, 'content-type': 'application/json' }, body: JSON.stringify({ space: `at://${w.did}/space/${T}/x`, credentials: ['j'] }) })
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 })
// 1. One read at a time.
{
const w = await issuer()
w.delayMs = 400
const answers = await Promise.all(Array.from({ length: 8 }, () => revoke(w)))
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`)
count('issuers\' keys: one read at a time')
w.close()
}
// 2. Renewed after the answer, and 3. read again once past the window.
{
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 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)
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`)
count('issuers\' keys: renewed after the answer')
await sleep(w.reads[1] + 7000 - 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 })
count('issuers\' keys: read again past their time')
w.close()
}
await restartWith(env)
}
harness/spaces/ssrf.mjs+1−1
spec/LIMITS.md+19−4
spec/SPACES-CREDENTIALS.md+31−6
spec/SPACES-POLICIES.md+2−2
spec/SPACES-SYNC.md+1−1