~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
145 lines · 8.5 KB Raw History
// 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 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. 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 by SIGTERM and started again, a revocation from the second
//      of those issuers reads nothing; one from the third, forgotten in 2,
//      reads its document; then shut down by SIGINT and started again, one
//      from the third reads nothing: the keys outlived each shutdown.
//
// 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.

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 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))

/// 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
  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}` }) })
  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>', ...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()
  {
    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 (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')
  }

  // 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, by SIGTERM and by SIGINT (spec/OPERATIONS.md,
  // "shutdown"): many[1], kept before the first; then many[2], forgotten
  // above and read again after the first start, so that only the SIGINT
  // shutdown can have written it.
  await restartWith(bounded, { signal: 'SIGTERM' })
  await sleep(1000)
  await taken('after a shutdown (SIGTERM) and a start, a key kept before', many[1], 0, { restart: 'SIGTERM, then 1 s' })
  await taken('a key forgotten before the shutdown', many[2], 1, { restart: 'SIGTERM, then 1 s' })
  await restartWith(bounded, { signal: 'SIGINT' })
  await sleep(1000)
  await taken('after a shutdown (SIGINT) and a start, a key read since the start before', many[2], 0, { restart: 'SIGINT, 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()
    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 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 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] ?? 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 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()
  }

  await restartWith(env)
}