~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
670 lines · 56.8 KB Raw History
// Spaces' credentials (spec/SPACES-CREDENTIALS.md), in the spaces run. A
// second alpha PDS, the peer, plays the parties the side under test does
// not, so each check is made twice: once with the alpha in a role, once with
// the server in it. Three roles, three topologies, in this order:
//
//   - user's PDS: the user on the peer or the server, the space host the
//     first alpha, which must trade the user's tokens. It needs nothing of
//     the server but this page's methods, so it goes first;
//   - space host: the authority on the alpha or the server, its member on
//     the peer; the member's delegation tokens (from the peer) are traded for
//     credentials, which the peer, as repo host, must take. The server's
//     spaces are made with the policies' methods;
//   - repo host: a writer on the peer or the server, the space host the first
//     alpha; credentials, HTTP signatures and revocations are presented to
//     the writer's host, through the space repo's listRecords.
//
// The answers are compared as spec/PDS.md says (status and error; DIDs named
// by role), and each side is held to the page where it says more. Tokens the
// alpha cannot be made to send are signed here with the account keys the
// in-process alpha holds.

import crypto from 'node:crypto'
import { isDeepStrictEqual } from 'node:util'
import { verifySignature, Secp256k1Keypair } from '@atproto/crypto'
import * as plc from '@did-plc/lib'
import { base58btc } from 'multiformats/bases/base58'
import { newP256, p256Point, signCredential } from './lib/spec.mjs'
import { countingListener } from './ssrf.mjs'

const T = 'com.example.group'
const R = 'com.atproto.space.notifyCredentialsRevoked'
const AUTHORIZE = 'com.atproto.space.authorizeSpaceSync'
const TID = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/
const MEMBERSPACE = 'com.atproto.memberspace.policy'
const APP = 'https://app.example/client-metadata.json'
const UNREACHABLE = 'https://127.0.0.1:1/client-metadata.json'
const HOLE = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// The order of secp256k1, to make a high-S signature of a low-S one.
const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141')

const now = () => Math.floor(Date.now() / 1000)
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url')
const unb64 = (s) => JSON.parse(Buffer.from(s, 'base64url').toString('utf8'))

/// A JWT signed by an alpha account's key; `header`/`payload` objects, or
/// strings taken as the parts already encoded.
async function sign(key, header, payload, { highS = false } = {}) {
  const input = `${typeof header === 'string' ? header : b64(header)}.${typeof payload === 'string' ? payload : b64(payload)}`
  let sig = Buffer.from(await key.sign(new Uint8Array(Buffer.from(input))))
  if (highS) {
    const s = BigInt(`0x${sig.subarray(32).toString('hex')}`)
    sig = Buffer.concat([sig.subarray(0, 32), Buffer.from((N - s).toString(16).padStart(64, '0'), 'hex')])
  }
  return `${input}.${sig.toString('base64url')}`
}
const jti = () => crypto.randomBytes(16).toString('hex')

/// A P-256 did:key of an x with no point on the curve, and one of an
/// uncompressed point: neither is a P-256 key (spec/SPACES.md, "P-256
/// did:keys").
function badP256Keys(key) {
  let x
  for (let i = 0; ; i++) {
    x = crypto.createHash('sha256').update(`off-curve ${i}`).digest()
    try { crypto.ECDH.convertKey(Buffer.concat([Buffer.from([2]), x]), 'prime256v1') } catch { break }
  }
  return {
    offCurve: `did:key:${base58btc.encode(Uint8Array.from([0x80, 0x24, 2, ...x]))}`,
    uncompressed: `did:key:${base58btc.encode(Uint8Array.from([0x80, 0x24, ...p256Point(key.did)]))}`,
  }
}

export async function checkSpaceCredentials(h) {
  const { net, ref, cand, differ, count, front } = h
  const peer = net.extraPdses[0]
  const alpha = net.pds
  const plcUrl = net.plc.url

  // ---- requests ------------------------------------------------------------------------

  async function call(base, nsid, { method, params, body, headers = {}, rawBody, contentType } = {}) {
    const url = new URL(`/xrpc/${nsid}`, base)
    for (const [k, v] of Object.entries(params ?? {})) url.searchParams.set(k, v)
    const hs = { ...headers }
    if (body !== undefined || rawBody !== undefined) hs['content-type'] = contentType ?? 'application/json'
    const res = await fetch(url, { method: method ?? (body === undefined && rawBody === undefined ? 'GET' : 'POST'), headers: hs, body: rawBody ?? (body === undefined ? undefined : JSON.stringify(body)) })
    const text = await res.text()
    let parsed = null
    try { parsed = text ? JSON.parse(text) : null } catch { parsed = { unparsed: text.slice(0, 200) } }
    return { status: res.status, body: parsed }
  }
  const bearer = (t) => ({ authorization: `Bearer ${t}` })

  async function account(base, domain) {
    const f = front()
    const res = await call(base, 'com.atproto.server.createAccount', { body: { handle: `${f}${domain}`, email: `${f}@example.com`, password: `pw-${f}` } })
    if (res.status !== 200) await differ('com.atproto.server.createAccount', { base, handle: `${f}${domain}` }, 'an account', res, 'the harness could not make an account it needs')
    return { did: res.body.did, base, password: `pw-${f}`, token: res.body.accessJwt, refresh: res.body.refreshJwt }
  }
  const alphaKey = async (pds, did) => pds.ctx.actorStore.keypair(did)
  const plcKey = async (did) => (await (await fetch(`${plcUrl}/${did}/data`)).json()).verificationMethods.atproto

  // ---- comparing ----------------------------------------------------------------------------

  /// Each side's names: DID → role, with its URLs.
  const rename = (side, v) => {
    const walk = (x) => {
      if (typeof x === 'string') { for (const [d, n] of side.names) x = x.split(d).join(n); return x }
      if (Array.isArray(x)) return x.map(walk)
      if (x && typeof x === 'object') return Object.fromEntries(Object.entries(x).map(([k, y]) => [k, walk(y)]))
      return x
    }
    return walk(v)
  }
  const shape = (side, res, pick) => res.status >= 400 ? { status: res.status, error: res.body?.error ?? null } : { status: res.status, body: rename(side, pick ? pick(res.body, side) : res.body) }
  /// A JWT as compared: its header, and its payload with `iat`, `exp` and `jti` as their form.
  const jwtShape = (token) => {
    if (typeof token !== 'string' || token.split('.').length !== 3) return { notAJwt: token ?? null }
    const [header, payload] = token.split('.').slice(0, 2).map((p) => { try { return unb64(p) } catch { return '<not JSON>' } })
    const out = { ...payload }
    if (typeof payload.iat === 'number') out.iat = '<iat>'
    if (typeof payload.exp === 'number') out.exp = typeof payload.iat === 'number' ? `<iat + ${payload.exp - payload.iat}>` : '<exp>'
    if (typeof payload.jti === 'string' && /^[0-9a-f]{32}$/.test(payload.jti)) out.jti = '<32 hex digits>'
    return { header, payload: out }
  }
  /// authorizeSpaceSync's answer as compared: the credential as a JWT, and
  /// whether it has a spaceRev, a TID.
  const asCredential = (body) => ({ credential: jwtShape(body?.credential), spaceRev: body?.spaceRev === undefined ? 'absent' : TID.test(body.spaceRev) ? '<tid>' : body.spaceRev })
  const asToken = (body) => ({ token: jwtShape(body?.token) })
  const matches = (want, n) => typeof want === 'number' ? n.status === want : n.status === want.status && n.error === want.error

  /// Send `run(side)` on both sides, compare, and hold each to `want`
  /// (a status, or `{status, error}`) where given.
  async function both(sides, kind, request, run, { pick, want } = {}) {
    const [a, b] = await Promise.all(sides.map(run))
    const [na, nb] = [shape(sides[0], a, pick), shape(sides[1], b, pick)]
    if (!isDeepStrictEqual(na, nb)) await differ(kind, request, na, nb)
    if (want !== undefined) for (const [side, n] of [[sides[0], na], [sides[1], nb]]) if (!matches(want, n)) await fail(side, kind, request, want, n)
    count(kind)
    return [a, b]
  }
  const fail = (side, what, request, want, got) => differ(`the ${side.label}'s ${what}`, request, want, got, side.isRef ? 'the reference fails the check it is held to' : undefined)
  const NOT_FOUND = { status: 400, error: 'SpaceNotFound' }
  const BAD_DT = { status: 400, error: 'InvalidDelegationToken' }
  const BAD_REQ = { status: 400, error: 'InvalidRequest' }
  const BAD_TOKEN = { status: 400, error: 'InvalidToken' }

  /// A token or credential the side minted must be as the page says, and
  /// verify against its issuer's key in the directory, low-S
  /// (spec/SPACES-CREDENTIALS.md, "The tokens this server signs").
  async function checkMinted(side, kind, token, want) {
    const parts = typeof token === 'string' ? token.split('.') : []
    let header, payload
    try { [header, payload] = parts.slice(0, 2).map(unb64) } catch {}
    const got = { header, payload }
    const expect = {
      header: { alg: 'ES256K', typ: want.typ, kid: '#atproto' },
      payload: Object.fromEntries(Object.entries({ iss: want.iss, sub: want.sub, aud: want.aud, cnf: want.cnf, iat: payload?.iat, exp: payload?.iat + want.life, jti: payload?.jti }).filter(([, v]) => v !== undefined)),
    }
    const fresh = typeof payload?.iat === 'number' && Math.abs(payload.iat - now()) <= 30 && typeof payload?.jti === 'string' && /^[0-9a-f]{32}$/.test(payload.jti)
    if (parts.length !== 3 || !isDeepStrictEqual(got, expect) || !fresh) return fail(side, `${kind}: the token's claims`, {}, expect, got)
    const ok = await verifySignature(await plcKey(want.iss), new Uint8Array(Buffer.from(`${parts[0]}.${parts[1]}`)), new Uint8Array(Buffer.from(parts[2], 'base64url')), { jwtAlg: 'ES256K' }).catch(() => false)
    if (!ok) await fail(side, `${kind}: the token's signature`, {}, 'ES256K, low-S, by the issuer\'s #atproto key in the directory', parts[2])
  }

  // The parties every topology shares: a credential key, and the peer's member.
  const kid = newP256()
  const { offCurve, uncompressed } = badP256Keys(kid)
  const k256 = await Secp256k1Keypair.create()

  // =========================================================================================
  // The server as the user's PDS: the user on the peer or the server, the
  // space host the first alpha (spec/SPACES-CREDENTIALS.md,
  // "getDelegationToken").
  // =========================================================================================
  {
    const authority = await account(alpha.url, '.test')
    const sides = []
    for (const [s, base, domain] of [[ref, peer.url, '.test2'], [cand, cand.url, '.test']]) {
      const user = await account(base, domain)
      sides.push({ label: s === ref ? 'peer (alpha)' : 'server', isRef: s === ref, base, user, names: [[authority.did, '<authority>'], [user.did, '<user>'], [base, '<url>']] })
    }
    const space = `at://${authority.did}/space/${T}/users`
    const made = await call(alpha.url, 'com.atproto.space.createSpace', { headers: bearer(authority.token), body: { spaceType: T, skey: 'users', policy: { $type: MEMBERSPACE } } })
    if (made.status !== 200) await differ('the alpha\'s createSpace', {}, 'a space', made, 'the harness could not make a space')
    for (const side of sides) await call(alpha.url, 'com.atproto.memberspace.putMembers', { headers: bearer(authority.token), body: { space, members: [{ did: side.user.did, read: true, write: false }] } })
    const dt = (side, { params = { space }, headers = bearer(side.user.token), method } = {}) => call(side.base, 'com.atproto.space.getDelegationToken', { params, headers, method })

    const [a, b] = await both(sides, 'getDelegationToken', { space: '<users>' }, (side) => dt(side), { pick: asToken, want: 200 })
    for (const [side, res] of [[sides[0], a], [sides[1], b]]) {
      await checkMinted(side, 'getDelegationToken', res.body?.token, { typ: 'atproto-space-delegation+jwt', iss: side.user.did, sub: space, aud: `${authority.did}#atproto_pds`, life: 60 })
      side.token = res.body?.token
    }
    await both(sides, 'a delegation token the user\'s PDS minted, at the alpha as space host', {}, (side) => call(alpha.url, AUTHORIZE, { body: { space, credentialKey: kid.did, delegationToken: side.token } }), { pick: asCredential, want: 200 })
    await both(sides, 'that delegation token again, at the alpha', {}, (side) => call(alpha.url, AUTHORIZE, { body: { space, credentialKey: kid.did, delegationToken: side.token } }), { want: BAD_DT })
    await both(sides, 'getDelegationToken: a space whose authority no one hosts', {}, (side) => dt(side, { params: { space: `at://${HOLE}/space/${T}/x` } }), { pick: asToken, want: 200 })
    await both(sides, 'getDelegationToken: a did:web authority', {}, (side) => dt(side, { params: { space: `at://did:web:example.com/space/${T}/x` } }), { pick: asToken, want: 200 })

    // Who may not.
    for (const side of sides) {
      const app = await call(side.base, 'com.atproto.server.createAppPassword', { headers: bearer(side.user.token), body: { name: 'spaces' } })
      const priv = await call(side.base, 'com.atproto.server.createAppPassword', { headers: bearer(side.user.token), body: { name: 'spaces-privileged', privileged: true } })
      side.app = (await call(side.base, 'com.atproto.server.createSession', { body: { identifier: side.user.did, password: app.body?.password } })).body
      side.priv = (await call(side.base, 'com.atproto.server.createSession', { body: { identifier: side.user.did, password: priv.body?.password } })).body
      const cred = await call(alpha.url, AUTHORIZE, { body: { space, credentialKey: kid.did, delegationToken: (await dt(side)).body?.token } })
      side.credHeaders = signCredential(kid, cred.body?.credential ?? 'x.y.z', side.user.did)
    }
    for (const [what, headersOf, want, params] of [
      ['no token', () => ({}), { status: 401, error: 'AuthMissing' }],
      ['an app password\'s session', (s) => bearer(s.app?.accessJwt), BAD_TOKEN],
      ['a privileged app password\'s session', (s) => bearer(s.priv?.accessJwt), BAD_TOKEN],
      ['a refresh token', (s) => bearer(s.user.refresh), BAD_TOKEN],
      ['a token the server did not give', () => bearer('abc'), BAD_TOKEN],
      ['Basic', () => ({ authorization: 'Basic YWRtaW46eA==' }), BAD_TOKEN],
      ['a space credential', (s) => s.credHeaders, BAD_TOKEN],
      ['no space', (s) => bearer(s.user.token), BAD_REQ, {}],
      ['a space that is no space-ref, no token', () => ({}), BAD_REQ, { space: 'nope' }],
      ['a space that is no space-ref, an app password', (s) => bearer(s.app?.accessJwt), BAD_REQ, { space: 'nope' }],
      ['a handle for the authority', (s) => bearer(s.user.token), BAD_REQ, { space: `at://someone.test/space/${T}/x` }],
      ['a record URI', (s) => bearer(s.user.token), BAD_REQ, { space: `at://${authority.did}/com.example.post/x` }],
    ]) {
      await both(sides, `getDelegationToken: ${what}`, { params }, (side) => dt(side, { headers: headersOf(side), params: params ?? { space } }), { want })
    }
    await both(sides, 'getDelegationToken: POST', {}, (side) => call(side.base, 'com.atproto.space.getDelegationToken', { params: { space }, headers: bearer(side.user.token), body: {} }), { want: BAD_REQ })
  }

  // =========================================================================================
  // The server as space host: an authority on each side, its member and a
  // non-member on the peer (spec/SPACES-CREDENTIALS.md, "authorizeSpaceSync").
  // =========================================================================================
  {
    const member = await account(peer.url, '.test2')
    const outsider = await account(peer.url, '.test2')
    const memberKey = await alphaKey(peer, member.did)
    const outsiderKey = await alphaKey(peer, outsider.did)
    const sides = []
    for (const [s, base] of [[ref, alpha.url], [cand, cand.url]]) {
      const authority = await account(base, '.test')
      sides.push({ label: s.name, isRef: s === ref, base, authority, names: [[authority.did, '<authority>'], [member.did, '<member>'], [outsider.did, '<outsider>'], [base, '<url>']] })
    }
    const sp = (side, skey) => `at://${side.authority.did}/space/${T}/${skey}`
    const asAuthority = (side) => bearer(side.authority.token)

    // The spaces, alike on each side.
    const policies = {
      members: { $type: MEMBERSPACE },
      open: { $type: MEMBERSPACE, publicRead: true },
      own: { $type: 'com.atproto.personalspace.policy' },
      apps: { $type: MEMBERSPACE, allowedApps: [APP] },
      gone: { $type: MEMBERSPACE, publicRead: true },
    }
    for (const [skey, policy] of Object.entries(policies)) {
      await both(sides, 'space host: createSpace', { skey, policy }, (side) => call(side.base, 'com.atproto.space.createSpace', { headers: asAuthority(side), body: { spaceType: T, skey, policy } }), { want: 200 })
    }
    for (const skey of ['members', 'apps']) {
      await both(sides, 'space host: putMembers', { skey, did: '<member>' }, (side) => call(side.base, 'com.atproto.memberspace.putMembers', { headers: asAuthority(side), body: { space: sp(side, skey), members: [{ did: member.did, read: true, write: true }] } }), { want: 200 })
    }
    await both(sides, 'space host: deleteSpace', { skey: 'gone' }, (side) => call(side.base, 'com.atproto.space.deleteSpace', { headers: asAuthority(side), body: { space: sp(side, 'gone') } }), { want: 200 })
    // The member's record in each side's space, on the peer.
    for (const side of sides) {
      const res = await call(peer.url, 'com.atproto.space.createRecord', { headers: bearer(member.token), body: { space: sp(side, 'members'), repo: member.did, collection: 'com.example.post', rkey: 'r1', record: { $type: 'com.example.post', text: 'hello' } } })
      if (res.status !== 200) await differ('the peer\'s space.createRecord', { space: '<members>' }, 'a record', res, 'the harness could not write the member\'s record')
    }

    const tokenOf = async (user, space) => {
      const res = await call(peer.url, 'com.atproto.space.getDelegationToken', { params: { space }, headers: bearer(user.token) })
      if (res.status !== 200) await differ('the peer\'s getDelegationToken', { space }, 'a token', res, 'the harness could not get a delegation token')
      return res.body.token
    }
    const gsc = (side, body, headers) => call(side.base, AUTHORIZE, { body, headers })
    const traded = async (kind, request, bodyOf, opts = {}) => both(sides, `authorizeSpaceSync: ${kind}`, request, async (side) => gsc(side, await bodyOf(side)), { pick: asCredential, ...opts })
    /// Each side's answer has a spaceRev, a TID, or none (spec/SPACES-CREDENTIALS.md,
    /// "authorizeSpaceSync"; spec/SPACES-SYNC.md, "The writer set").
    const spaceRevIs = async (kind, answers, has) => {
      for (const [side, res] of [[sides[0], answers[0]], [sides[1], answers[1]]]) {
        const got = res.body?.spaceRev
        if (has ? !TID.test(got ?? '') : got !== undefined) await fail(side, `authorizeSpaceSync: ${kind}: its spaceRev`, {}, has ? 'a TID: the member wrote there' : 'none: no one wrote there', got ?? 'none')
      }
    }

    // Traded: the credential as the page says, and taken by the peer as repo host.
    const [a, b] = await traded('a member\'s token', { space: '<members>', credentialKey: '<kid>', delegationToken: '<member\'s>' }, async (side) => (side.token = await tokenOf(member, sp(side, 'members')), { space: sp(side, 'members'), credentialKey: kid.did, delegationToken: side.token }), { want: 200 })
    await spaceRevIs('a member\'s token', [a, b], true)
    for (const [side, res] of [[sides[0], a], [sides[1], b]]) {
      await checkMinted(side, 'authorizeSpaceSync', res.body?.credential, { typ: 'atproto-space-credential+jwt', iss: side.authority.did, sub: sp(side, 'members'), cnf: { kid: kid.did }, life: 600 })
      side.credential = res.body?.credential
    }
    await both(sides, 'a credential the space host minted, at the peer as repo host', { method: 'space.listRecords', repo: '<member>', audience: '<member>' }, (side) => call(peer.url, 'com.atproto.space.listRecords', { params: { space: sp(side, 'members'), repo: member.did }, headers: signCredential(kid, side.credential, member.did) }), { want: 200 })
    await traded('the same token again', { delegationToken: '<spent>' }, (side) => ({ space: sp(side, 'members'), credentialKey: kid.did, delegationToken: side.token }), { want: BAD_DT })

    // The perimeters, and what is not there (spec/SPACES-CREDENTIALS.md,
    // "For the other parts"; spec/SPACES-POLICIES.md, "Who is authorized").
    await traded('no token, members only', {}, (side) => ({ space: sp(side, 'members'), credentialKey: kid.did }), { want: NOT_FOUND })
    await spaceRevIs('no token, public', await traded('no token, public', {}, (side) => ({ space: sp(side, 'open'), credentialKey: kid.did }), { want: 200 }), false)
    await traded('an empty token, public', { delegationToken: '' }, (side) => ({ space: sp(side, 'open'), credentialKey: kid.did, delegationToken: '' }), { want: 200 })
    await traded('an empty token, members only', { delegationToken: '' }, (side) => ({ space: sp(side, 'members'), credentialKey: kid.did, delegationToken: '' }), { want: NOT_FOUND })
    await traded('a non-member\'s token', {}, async (side) => ({ space: sp(side, 'members'), credentialKey: kid.did, delegationToken: await tokenOf(outsider, sp(side, 'members')) }), { want: NOT_FOUND })
    await traded('a member\'s token, personalspace', {}, async (side) => ({ space: sp(side, 'own'), credentialKey: kid.did, delegationToken: await tokenOf(member, sp(side, 'own')) }), { want: NOT_FOUND })
    {
      const [x, y] = await traded('the authority\'s own token, personalspace', { delegationToken: '<the authority\'s, from its own PDS>' }, async (side) => {
        const res = await call(side.base, 'com.atproto.space.getDelegationToken', { params: { space: sp(side, 'own') }, headers: asAuthority(side) })
        return { space: sp(side, 'own'), credentialKey: kid.did, delegationToken: res.body?.token }
      }, { want: 200 })
      void x; void y
    }
    await traded('a token for another space', { space: '<open>', delegationToken: '<for members>' }, async (side) => (side.token = await tokenOf(member, sp(side, 'members')), { space: sp(side, 'open'), credentialKey: kid.did, delegationToken: side.token }), { want: BAD_DT })
    await traded('that token, spent, for its space', {}, (side) => ({ space: sp(side, 'members'), credentialKey: kid.did, delegationToken: side.token }), { want: BAD_DT })
    await traded('allowedApps, no attestation', {}, async (side) => (side.token = await tokenOf(member, sp(side, 'apps')), { space: sp(side, 'apps'), credentialKey: kid.did, delegationToken: side.token }), { want: { status: 400, error: 'AppNotAuthorized' } })
    await traded('that token, spent by the refusal', {}, (side) => ({ space: sp(side, 'apps'), credentialKey: kid.did, delegationToken: side.token }), { want: BAD_DT })
    await traded('allowedApps, the authority, no attestation', {}, async (side) => {
      const res = await call(side.base, 'com.atproto.space.getDelegationToken', { params: { space: sp(side, 'apps') }, headers: asAuthority(side) })
      return { space: sp(side, 'apps'), credentialKey: kid.did, delegationToken: res.body?.token }
    }, { want: { status: 400, error: 'AppNotAuthorized' } })
    await traded('a missing space', {}, (side) => ({ space: sp(side, 'missing'), credentialKey: kid.did }), { want: NOT_FOUND })
    await traded('a missing space, a token that is no JWT', {}, (side) => ({ space: sp(side, 'missing'), credentialKey: kid.did, delegationToken: 'abc' }), { want: BAD_DT })
    await traded('a missing space, with a token', {}, async (side) => (side.token = await tokenOf(member, sp(side, 'missing')), { space: sp(side, 'missing'), credentialKey: kid.did, delegationToken: side.token }), { want: NOT_FOUND })
    await traded('that token, spent by the refusal of a missing space', {}, (side) => ({ space: sp(side, 'missing'), credentialKey: kid.did, delegationToken: side.token }), { want: BAD_DT })
    // A deleted space is answered before the token is read: the token is not
    // spent, and is taken once the space is created again.
    await traded('a deleted space', {}, (side) => ({ space: sp(side, 'gone'), credentialKey: kid.did }), { want: { status: 400, error: 'SpaceDeleted' } })
    await traded('a deleted space, a token that is no JWT', {}, (side) => ({ space: sp(side, 'gone'), credentialKey: kid.did, delegationToken: 'abc' }), { want: { status: 400, error: 'SpaceDeleted' } })
    await traded('a deleted space, with a token', {}, async (side) => (side.token = await tokenOf(member, sp(side, 'gone')), { space: sp(side, 'gone'), credentialKey: kid.did, delegationToken: side.token }), { want: { status: 400, error: 'SpaceDeleted' } })
    await both(sides, 'space host: createSpace of the deleted space again', { skey: 'gone' }, (side) => call(side.base, 'com.atproto.space.createSpace', { headers: asAuthority(side), body: { spaceType: T, skey: 'gone', policy: policies.gone } }), { want: 200 })
    await traded('that token, not spent, once the space is created again', {}, (side) => ({ space: sp(side, 'gone'), credentialKey: kid.did, delegationToken: side.token }), { want: 200 })
    {
      const elsewhere = `at://${member.did}/space/${T}/x`
      await traded('an authority hosted elsewhere', { space: '<the member\'s>' }, () => ({ space: elsewhere, credentialKey: kid.did }), { want: NOT_FOUND })
      await traded('an authority hosted elsewhere, a token that is no JWT', { space: '<the member\'s>' }, () => ({ space: elsewhere, credentialKey: kid.did, delegationToken: 'abc' }), { want: NOT_FOUND })
      await traded('an authority hosted elsewhere, with a token', { space: '<the member\'s>' }, async () => ({ space: elsewhere, credentialKey: kid.did, delegationToken: await tokenOf(member, elsewhere) }), { want: NOT_FOUND })
    }

    // credentialKey, then the token: a refusal of the key does not spend it.
    await traded('a secp256k1 credentialKey', { credentialKey: '<k256>' }, async (side) => (side.token = await tokenOf(member, sp(side, 'members')), { space: sp(side, 'members'), credentialKey: k256.did(), delegationToken: side.token }), { want: BAD_REQ })
    await traded('that token, not spent', {}, (side) => ({ space: sp(side, 'members'), credentialKey: kid.did, delegationToken: side.token }), { want: 200 })
    for (const [what, credentialKey] of [['not a did:key', 'nope'], ['off the curve', offCurve], ['uncompressed', uncompressed], ['empty', '']]) {
      await traded(`a credentialKey ${what}`, { credentialKey }, (side) => ({ space: sp(side, 'open'), credentialKey }), { want: BAD_REQ })
    }
    await traded('a credentialKey that is no key, of an authority hosted elsewhere', {}, () => ({ space: `at://${member.did}/space/${T}/x`, credentialKey: 'nope' }), { want: BAD_REQ })
    await traded('no credentialKey', {}, (side) => ({ space: sp(side, 'open') }), { want: BAD_REQ })
    await traded('no space', {}, () => ({ credentialKey: kid.did }), { want: BAD_REQ })
    await traded('a space that is no space-ref', { space: 'at://x' }, () => ({ space: 'at://x', credentialKey: kid.did }), { want: BAD_REQ })
    await traded('a record URI for a space', {}, (side) => ({ space: `at://${side.authority.did}/com.example.post/x`, credentialKey: kid.did }), { want: BAD_REQ })
    await traded('a token that is a number', {}, (side) => ({ space: sp(side, 'open'), credentialKey: kid.did, delegationToken: 5 }), { want: BAD_REQ })
    await both(sides, 'authorizeSpaceSync: GET', {}, (side) => call(side.base, AUTHORIZE, { params: { space: sp(side, 'open'), credentialKey: kid.did } }), { want: BAD_REQ })
    await both(sides, 'authorizeSpaceSync: text/plain', {}, (side) => call(side.base, AUTHORIZE, { rawBody: 'x', contentType: 'text/plain' }), { want: BAD_REQ })
    for (const [what, headers] of [['a token the server did not give', bearer('abc')], ['Basic', { authorization: 'Basic YWRtaW46eA==' }], ['an unknown scheme', { authorization: 'Foo bar' }], ['three words', { authorization: 'Bearer a b' }]]) {
      await both(sides, `authorizeSpaceSync: ignores Authorization, ${what}`, {}, (side) => gsc(side, { space: sp(side, 'open'), credentialKey: kid.did }, headers), { pick: asCredential, want: 200 })
    }
    await both(sides, 'authorizeSpaceSync: ignores Authorization, a session', {}, (side) => gsc(side, { space: sp(side, 'open'), credentialKey: kid.did }, asAuthority(side)), { pick: asCredential, want: 200 })

    // Delegation tokens signed here, each with one thing wrong or unusual
    // (spec/SPACES-CREDENTIALS.md, "Verifying a delegation token").
    const dh = { alg: 'ES256K', typ: 'atproto-space-delegation+jwt', kid: '#atproto' }
    const dp = (side, o = {}) => ({ iss: member.did, sub: sp(side, 'members'), aud: `${side.authority.did}#atproto_pds`, iat: now(), exp: now() + 60, jti: jti(), ...o })
    const forged = (what, make, want, space = 'members') => traded(`a token ${what}`, { delegationToken: what }, async (side) => ({ space: sp(side, space), credentialKey: kid.did, delegationToken: await make(side) }), { want })
    await forged('as the PDS signs it', (s) => sign(memberKey, dh, dp(s)), 200)
    await forged('with a bare DID for aud', (s) => sign(memberKey, dh, dp(s, { aud: s.authority.did })), BAD_DT)
    await forged('for another host', (s) => sign(memberKey, dh, dp(s, { aud: `${outsider.did}#atproto_pds` })), BAD_DT)
    await forged('with no aud', (s) => sign(memberKey, dh, dp(s, { aud: undefined })), BAD_DT)
    await forged('30 seconds past exp', (s) => sign(memberKey, dh, dp(s, { iat: now() - 90, exp: now() - 30 })), BAD_DT)
    await forged('2 seconds past exp', (s) => sign(memberKey, dh, dp(s, { iat: now() - 62, exp: now() - 2 })), 200)
    await forged('with exp an hour ahead', (s) => sign(memberKey, dh, dp(s, { exp: now() + 3600 })), 200)
    await forged('issued 59 minutes ahead', (s) => sign(memberKey, dh, dp(s, { iat: now() + 3540, exp: now() + 3600 })), 200)
    await forged('with no iat', (s) => sign(memberKey, dh, dp(s, { iat: undefined })), 200)
    await forged('with lxm and cnf', (s) => sign(memberKey, dh, dp(s, { lxm: AUTHORIZE, cnf: { kid: kid.did } })), 200)
    await forged('with no exp', (s) => sign(memberKey, dh, dp(s, { exp: undefined })), BAD_DT)
    await forged('with exp a string', (s) => sign(memberKey, dh, dp(s, { exp: String(now() + 60) })), BAD_DT)
    await forged('of typ JWT', (s) => sign(memberKey, { ...dh, typ: 'JWT' }, dp(s)), BAD_DT)
    await forged('of a credential\'s typ', (s) => sign(memberKey, { ...dh, typ: 'atproto-space-credential+jwt' }, dp(s)), BAD_DT)
    await forged('with no kid', (s) => sign(memberKey, { alg: 'ES256K', typ: dh.typ }, dp(s)), BAD_DT)
    await forged('with kid #atproto_kem', (s) => sign(memberKey, { ...dh, kid: '#atproto_kem' }, dp(s)), BAD_DT)
    await forged('with alg ES256', (s) => sign(memberKey, { ...dh, alg: 'ES256' }, dp(s)), BAD_DT)
    await forged('with alg none', (s) => sign(memberKey, { ...dh, alg: 'none' }, dp(s)), BAD_DT)
    await forged('with no jti', (s) => sign(memberKey, dh, dp(s, { jti: undefined })), BAD_DT)
    await forged('with jti a number', (s) => sign(memberKey, dh, dp(s, { jti: 5 })), BAD_DT)
    await forged('signed by another account', (s) => sign(outsiderKey, dh, dp(s)), BAD_DT)
    await forged('high-S', (s) => sign(memberKey, dh, dp(s), { highS: true }), BAD_DT)
    await forged('from a DID the directory lacks', (s) => sign(memberKey, dh, dp(s, { iss: HOLE })), BAD_DT)
    await forged('from no DID', (s) => sign(memberKey, dh, dp(s, { iss: 'member' })), BAD_DT)
    await forged('for no space', (s) => sign(memberKey, dh, dp(s, { sub: 'at://x' })), BAD_DT)
    await forged('with a bad signature encoding', async (s) => (await sign(memberKey, dh, dp(s))).slice(0, -3) + '!!!', BAD_DT)
    await forged('of two parts', () => 'a.b', BAD_DT)
    await forged('with a header not JSON', (s) => sign(memberKey, 'eyJ', b64(dp(s))), BAD_DT)
    await forged('a session token', () => member.token, BAD_DT)
    await forged('abc', () => 'abc', BAD_DT)
    // A jti is spent per issuer (spec/SPACES-CREDENTIALS.md, "Single-use values").
    {
      const shared = {}
      await forged('with a jti', (s) => sign(memberKey, dh, dp(s, { jti: (shared[s.label] = jti()) })), 200)
      await forged('with that jti again', (s) => sign(memberKey, dh, dp(s, { jti: shared[s.label], exp: now() + 30 })), BAD_DT)
      await forged('with that jti, another issuer', (s) => sign(outsiderKey, dh, dp(s, { iss: outsider.did, sub: sp(s, 'open'), jti: shared[s.label] })), 200, 'open')
    }

    // Client attestations: none can verify here (an https client the run
    // cannot serve). One whose client cannot be fetched is compared; the
    // malformed are held to the page alone (the reference answers 500)
    // (spec/SPACES-CREDENTIALS.md, "Verifying a client attestation").
    const attest = (s, o = {}, header = {}) => sign(memberKey, { alg: 'ES256', typ: 'atproto-client-attestation+jwt', kid: 'k1', ...header }, { iss: UNREACHABLE, sub: UNREACHABLE, aud: `${s.authority.did}#atproto_pds`, iat: now(), exp: now() + 60, jti: jti(), ...o })
    const BAD_ATT = { status: 400, error: 'InvalidClientAttestation' }
    await traded('an attestation whose client cannot be fetched', { clientAttestation: UNREACHABLE }, async (s) => ({ space: sp(s, 'open'), credentialKey: kid.did, clientAttestation: await attest(s) }), { want: BAD_ATT })
    await traded('an empty attestation', { clientAttestation: '' }, (s) => ({ space: sp(s, 'open'), credentialKey: kid.did, clientAttestation: '' }), { want: 200 })
    await traded('a bad token and a bad attestation', {}, (s) => ({ space: sp(s, 'members'), credentialKey: kid.did, delegationToken: 'abc', clientAttestation: 'abc' }), { want: BAD_DT })
    const cs = sides[1]
    for (const [what, make] of [
      ['abc', async () => 'abc'],
      ['of typ JWT', (s) => attest(s, {}, { typ: 'JWT' })],
      ['with iss other than sub', (s) => attest(s, { sub: 'https://other.example/client-metadata.json' })],
      ['with no aud', (s) => attest(s, { aud: undefined })],
      ['with no jti', (s) => attest(s, { jti: undefined })],
    ]) {
      const request = { space: '<open>', clientAttestation: what }
      const res = await gsc(cs, { space: sp(cs, 'open'), credentialKey: kid.did, clientAttestation: await make(cs) })
      const n = shape(cs, res)
      if (!matches(BAD_ATT, n)) await fail(cs, `authorizeSpaceSync: an attestation ${what}`, request, BAD_ATT, n)
      count('authorizeSpaceSync: a malformed attestation (the page alone)')
    }

    // Held to the page alone, the reference taking any exp ahead: a token or
    // attestation whose exp is more than an hour ahead is refused, and an
    // attestation so is refused before its client is fetched
    // (spec/SPACES-CREDENTIALS.md, "Verifying a delegation token",
    // "Verifying a client attestation", "Where the reference departs from
    // this page").
    for (const [what, ahead] of [['3610 seconds', 3610], ['a day', 86400]]) {
      const request = { delegationToken: `exp ${what} ahead` }
      const n = shape(cs, await gsc(cs, { space: sp(cs, 'members'), credentialKey: kid.did, delegationToken: await sign(memberKey, dh, dp(cs, { exp: now() + ahead })) }))
      if (!matches(BAD_DT, n)) await fail(cs, `authorizeSpaceSync: a token whose exp is ${what} ahead`, request, BAD_DT, n)
      count('authorizeSpaceSync: a token whose exp is past an hour ahead (the page alone)')
    }
    {
      const client = await countingListener()
      const id = `https://localhost:${client.port}/client-metadata.json`
      const at = (ahead) => attest(cs, { iss: id, sub: id, exp: now() + ahead })
      for (const [what, ahead, connects] of [['a day', 86400, false], ['a minute', 60, true]]) {
        const before = client.connections
        const request = { clientAttestation: `exp ${what} ahead, its client at https://localhost:<port>` }
        const n = shape(cs, await gsc(cs, { space: sp(cs, 'open'), credentialKey: kid.did, clientAttestation: await at(ahead) }))
        if (!matches(BAD_ATT, n)) await fail(cs, `authorizeSpaceSync: an attestation whose exp is ${what} ahead`, request, BAD_ATT, n)
        await new Promise((ok) => setTimeout(ok, 200))
        if ((client.connections > before) !== connects) await fail(cs, `authorizeSpaceSync: an attestation whose exp is ${what} ahead, its client`, request, connects ? 'fetched' : 'not fetched, refused before', `${client.connections - before} connections`)
        count('authorizeSpaceSync: an attestation and its exp (the page alone)')
      }
      client.close()
    }

    // Spent before the restart, refused after it (spec/SPACES-CREDENTIALS.md,
    // "Single-use values", "Durability", "Where the reference departs from
    // this page").
    h.afterRestart.push(async () => {
      const token = cs.lastToken
      const res = await gsc(cs, { space: sp(cs, 'members'), credentialKey: kid.did, delegationToken: token })
      const n = shape(cs, res)
      if (!matches(BAD_DT, n)) await fail(cs, 'authorizeSpaceSync: a token spent before a restart', { delegationToken: '<spent, an hour to live>' }, BAD_DT, n)
      count('authorizeSpaceSync: a token spent before a restart')
    })
    cs.lastToken = await sign(memberKey, dh, dp(cs, { exp: now() + 3600 }))
    const spent = shape(cs, await gsc(cs, { space: sp(cs, 'members'), credentialKey: kid.did, delegationToken: cs.lastToken }))
    if (!matches(200, spent)) await fail(cs, 'authorizeSpaceSync: a token living an hour', {}, 200, spent)
  }

  // =========================================================================================
  // The server as repo host: a writer on the peer or the server, the
  // authority on the first alpha; credentials, signatures and revocations
  // presented to the writer's host (spec/SPACES-CREDENTIALS.md, "Presenting
  // a credential", "Verifying a credential", "Revocation").
  // =========================================================================================
  {
    const authority = await account(alpha.url, '.test')
    const stranger = await account(alpha.url, '.test')
    const authorityKey = await alphaKey(alpha, authority.did)
    const strangerKey = await alphaKey(alpha, stranger.did)
    const sides = []
    for (const [s, base, domain] of [[ref, peer.url, '.test2'], [cand, cand.url, '.test']]) {
      const writer = await account(base, domain)
      const neighbour = await account(base, domain)
      sides.push({ label: s === ref ? 'peer (alpha)' : 'server', isRef: s === ref, base, writer, neighbour, names: [[authority.did, '<authority>'], [stranger.did, '<stranger>'], [writer.did, '<writer>'], [neighbour.did, '<neighbour>'], [base, '<url>']] })
    }
    const space = `at://${authority.did}/space/${T}/repos`
    const other = `at://${authority.did}/space/${T}/open`
    for (const [skey, policy] of [['repos', { $type: MEMBERSPACE }], ['open', { $type: MEMBERSPACE, publicRead: true }]]) {
      const made = await call(alpha.url, 'com.atproto.space.createSpace', { headers: bearer(authority.token), body: { spaceType: T, skey, policy } })
      if (made.status !== 200) await differ('the alpha\'s createSpace', { skey }, 'a space', made, 'the harness could not make a space')
    }
    for (const side of sides) await call(alpha.url, 'com.atproto.memberspace.putMembers', { headers: bearer(authority.token), body: { space, members: [{ did: side.writer.did, read: true, write: true }] } })
    await both(sides, 'repo host: space.createRecord', { space: '<repos>', rkey: 'r1' }, (side) => call(side.base, 'com.atproto.space.createRecord', { headers: bearer(side.writer.token), body: { space, repo: side.writer.did, collection: 'com.example.post', rkey: 'r1', record: { $type: 'com.example.post', text: 'hello' } } }), { pick: () => ({}), want: 200 })

    // A credential the alpha issued, for the authority itself.
    const issue = async (s, key = kid) => {
      const token = (await call(alpha.url, 'com.atproto.space.getDelegationToken', { params: { space: s }, headers: bearer(authority.token) })).body?.token
      const res = await call(alpha.url, AUTHORIZE, { body: { space: s, credentialKey: key.did, delegationToken: token } })
      if (res.status !== 200) await differ('the alpha\'s authorizeSpaceSync', { space: s }, 'a credential', res, 'the harness could not get a credential')
      return res.body.credential
    }
    const credential = await issue(space)
    const otherCredential = await issue(other)
    const list = (side, headers, s = space, repo = side.writer.did) => call(side.base, 'com.atproto.space.listRecords', { params: { space: s, repo }, headers })
    const read = (kind, request, headersOf, want, s) => both(sides, `listRecords with a credential: ${kind}`, request, async (side) => list(side, await headersOf(side), s), { want })
    const withSig = (side, c, aud = side.writer.did, opts) => signCredential(kid, c, aud, opts)
    const AUDIENCE = { status: 401, error: 'BadSpaceAudience' }
    const SIG = { status: 401, error: 'BadSpaceSignature' }

    await read('the alpha\'s', {}, (s) => withSig(s, credential), 200)
    await read('the alpha\'s, again', {}, (s) => withSig(s, credential), 200)
    await read('addressed to the authority', { audience: '<authority>' }, (s) => withSig(s, credential, authority.did), AUDIENCE)
    await read('addressed to the neighbour', { audience: '<neighbour>' }, (s) => withSig(s, credential, s.neighbour.did), AUDIENCE)
    await read('addressed to no DID', { audience: 'writer' }, (s) => withSig(s, credential, 'writer'), SIG)
    await read('with no audience', {}, (s) => { const { 'atproto-space-audience': _, ...rest } = withSig(s, credential); return rest }, SIG)
    await read('unsigned', {}, (s) => ({ authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': s.writer.did }), SIG)
    await read('unsigned, addressed to the authority', {}, () => ({ authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': authority.did }), SIG)
    await read('as a bearer token', {}, () => bearer(credential), BAD_TOKEN)
    await read('the scheme in lower case', {}, (s) => withSig(s, credential, s.writer.did, { scheme: 'atproto-space-credential' }), 200)
    await read('the scheme in upper case', {}, (s) => withSig(s, credential, s.writer.did, { scheme: 'ATPROTO-SPACE-CREDENTIAL' }), 200)
    await read('three words', {}, (s) => ({ ...withSig(s, credential), authorization: `Atproto-Space-Credential ${credential} x` }), BAD_TOKEN)
    await read('signed by another key', {}, (s) => signCredential(newP256(), credential, s.writer.did), SIG)
    await read('signed for another audience', {}, (s) => ({ ...withSig(s, credential, authority.did), signature: withSig(s, credential).signature }), SIG)
    await read('tagged otherwise', {}, (s) => { const x = withSig(s, credential); x['signature-input'] = x['signature-input'].replace('tag="atproto-space-credential"', 'tag="x"'); return x }, SIG)
    // The signature is found by its tag, whatever its label (spec/SPACES.md,
    // "HTTP Message Signatures").
    await read('labelled otherwise', {}, (s) => withSig(s, credential, s.writer.did, { label: 'atproto-space-credential' }), 200)
    await read('beside another signature, untagged', {}, (s) => { const x = withSig(s, credential); return { ...x, 'signature-input': `other=("authorization");created=1, ${x['signature-input']}`, signature: `other=:${Buffer.alloc(64, 1).toString('base64')}:, ${x.signature}` } }, 200)
    await read('tagged twice', {}, (s) => { const x = withSig(s, credential); return { ...x, 'signature-input': `${x['signature-input']}, dup=${x['signature-input'].slice('sig='.length)}`, signature: `${x.signature}, dup=${x.signature.slice('sig='.length)}` } }, SIG)
    await read('with its keyid', {}, (s) => withSig(s, credential, s.writer.did, { extra: `;keyid="${kid.did}"` }), 200)
    await read('with another keyid', {}, (s) => withSig(s, credential, s.writer.did, { extra: ';keyid="x"' }), SIG)
    await read('with another alg', {}, (s) => withSig(s, credential, s.writer.did, { extra: ';alg="ed25519"' }), SIG)
    await read('with created', {}, (s) => withSig(s, credential, s.writer.did, { extra: ';created=1' }), 200)
    await read('for another space', { space: '<open>', credential: '<repos>' }, (s) => withSig(s, otherCredential), { status: 400, error: 'InvalidCredential' })
    await read('a credential for the space, in its own', { space: '<open>' }, (s) => withSig(s, otherCredential), 200, other)

    // Credentials signed here with the authority's key, each with one thing wrong or unusual
    // (spec/SPACES-CREDENTIALS.md, "Verifying a credential", "Issuers' keys").
    const ch = { alg: 'ES256K', typ: 'atproto-space-credential+jwt', kid: '#atproto' }
    const cp = (o = {}) => ({ iss: authority.did, sub: space, cnf: { kid: kid.did }, iat: now(), exp: now() + 600, jti: jti(), ...o })
    const forged = (what, make, want, aud) => read(`signed ${what}`, { credential: what }, async (s) => withSig(s, await make(), aud ?? s.writer.did), want)
    const E = (error) => ({ status: 401, error })
    await forged('as an authority signs it', () => sign(authorityKey, ch, cp()), 200)
    await forged('with an aud', () => sign(authorityKey, ch, cp({ aud: 'did:plc:someoneelse' })), 200)
    await forged('of typ JWT', () => sign(authorityKey, { ...ch, typ: 'JWT' }, cp()), E('BadJwtType'))
    await forged('of a delegation token\'s typ', () => sign(authorityKey, { ...ch, typ: 'atproto-space-delegation+jwt' }, cp()), E('BadJwtType'))
    await forged('with no kid', () => sign(authorityKey, { alg: 'ES256K', typ: ch.typ }, cp()), E('BadJwt'))
    await forged('with no alg', () => sign(authorityKey, { typ: ch.typ, kid: '#atproto' }, cp()), E('BadJwt'))
    await forged('with no iss', () => sign(authorityKey, ch, cp({ iss: undefined })), E('BadJwtIss'))
    await forged('with no sub', () => sign(authorityKey, ch, cp({ sub: undefined })), E('BadJwtSub'))
    await forged('with no exp', () => sign(authorityKey, ch, cp({ exp: undefined })), E('BadJwt'))
    await forged('with no cnf', () => sign(authorityKey, ch, cp({ cnf: undefined })), E('BadJwtCnf'))
    await forged('with cnf.kid no DID', () => sign(authorityKey, ch, cp({ cnf: { kid: 'x' } })), E('BadJwtCnf'))
    await forged('with no jti', () => sign(authorityKey, ch, cp({ jti: undefined })), E('BadJwt'))
    await forged('with an empty jti', () => sign(authorityKey, ch, cp({ jti: '' })), E('BadJwt'))
    await forged('with no iat', () => sign(authorityKey, ch, cp({ iat: undefined })), E('BadJwt'))
    await forged('with iat a string', () => sign(authorityKey, ch, cp({ iat: String(now()) })), E('BadJwt'))
    await forged('with exp at iat', () => { const t = now(); return sign(authorityKey, ch, cp({ iat: t, exp: t })) }, E('BadJwt'))
    await forged('living an hour', () => { const t = now(); return sign(authorityKey, ch, cp({ iat: t, exp: t + 3600 })) }, 200)
    await forged('living an hour and a second', () => { const t = now(); return sign(authorityKey, ch, cp({ iat: t, exp: t + 3601 })) }, E('BadJwt'))
    await forged('issued 2 seconds ahead', () => sign(authorityKey, ch, cp({ iat: now() + 2, exp: now() + 600 })), 200)
    await forged('issued 30 seconds ahead', () => sign(authorityKey, ch, cp({ iat: now() + 30, exp: now() + 600 })), E('BadJwt'))
    await forged('2 seconds past exp', () => sign(authorityKey, ch, cp({ iat: now() - 100, exp: now() - 2 })), 200)
    await forged('30 seconds past exp', () => sign(authorityKey, ch, cp({ iat: now() - 100, exp: now() - 30 })), E('JwtExpired'))
    await forged('past exp, by another key', () => sign(strangerKey, ch, cp({ iat: now() - 100, exp: now() - 30 })), E('JwtExpired'))
    await forged('past exp, of another typ', () => sign(authorityKey, { ...ch, typ: 'x' }, cp({ iat: now() - 100, exp: now() - 30 })), E('BadJwtType'))
    await forged('from no DID', () => sign(authorityKey, ch, cp({ iss: 'authority' })), E('BadJwt'))
    await forged('from a DID the directory lacks', () => sign(authorityKey, ch, cp({ iss: HOLE, sub: `at://${HOLE}/space/${T}/x` })), E('BadJwtIss'))
    await forged('by another key', () => sign(strangerKey, ch, cp()), E('BadJwtSignature'))
    await forged('high-S', () => sign(authorityKey, ch, cp(), { highS: true }), E('BadJwtSignature'))
    await forged('with alg ES256', () => sign(authorityKey, { ...ch, alg: 'ES256' }, cp()), E('BadJwtSignature'))
    await forged('with alg none', () => sign(authorityKey, { ...ch, alg: 'none' }, cp()), E('BadJwtSignature'))
    await forged('for no space', () => sign(authorityKey, ch, cp({ sub: 'x' })), E('BadJwtSub'))
    await forged('for a record URI', () => sign(authorityKey, ch, cp({ sub: `at://${authority.did}/com.example.post/x` })), E('BadJwtSub'))
    await forged('by another authority, for its own', () => sign(strangerKey, ch, cp({ iss: stranger.did })), E('BadJwtIss'))
    await forged('bound to a secp256k1 key', () => sign(authorityKey, ch, cp({ cnf: { kid: k256.did() } })), SIG)
    await forged('bound to another P-256 key', () => sign(authorityKey, ch, cp({ cnf: { kid: newP256().did } })), SIG)
    await forged('with a bad signature encoding', async () => (await sign(authorityKey, ch, cp())).slice(0, -3) + '!!!', E('BadJwt'))
    await forged('of two parts', () => 'a.b', E('BadJwt'))
    await forged('abc', () => 'abc', E('BadJwt'))
    await forged('with a header not JSON', () => sign(authorityKey, 'eyJ', b64(cp())), E('BadJwt'))
    {
      const never = `at://${authority.did}/space/${T}/never`
      await read('signed for a space never made, in that space', {}, async (s) => withSig(s, await sign(authorityKey, ch, cp({ sub: never }))), 200, never)
    }

    // Revocation: service auth signed with the authority's key
    // (spec/SPACES-CREDENTIALS.md, "Revocation").
    const sh = { alg: 'ES256K', typ: 'JWT' }
    const sp2 = (side, o = {}) => ({ iss: authority.did, aud: side.writer.did, lxm: R, iat: now(), exp: now() + 60, jti: jti(), ...o })
    const revoke = (kind, request, headersOf, body, want) => both(sides, `notifyCredentialsRevoked: ${kind}`, request, async (side) => call(side.base, R, { headers: await headersOf(side), body: typeof body === 'function' ? body(side) : body }), { want })
    const svc = (kind, make, want, body = { space: other, credentials: ['unused'] }) => revoke(kind, { token: kind }, async (s) => bearer(await make(s)), body, want)
    const FORBIDDEN = { status: 403, error: 'Forbidden' }
    await svc('as an authority signs it', (s) => sign(authorityKey, sh, sp2(s)), 200)
    await svc('from another account', (s) => sign(strangerKey, sh, sp2(s, { iss: stranger.did })), FORBIDDEN)
    await svc('from the authority with a fragment', (s) => sign(authorityKey, sh, sp2(s, { iss: `${authority.did}#atproto_pds` })), FORBIDDEN)
    await svc('to an account elsewhere', () => sign(authorityKey, sh, sp2({ writer: authority })), FORBIDDEN)
    await svc('to the writer with a fragment', (s) => sign(authorityKey, sh, sp2(s, { aud: `${s.writer.did}#atproto_pds` })), FORBIDDEN)
    await svc('to a DID no one has', (s) => sign(authorityKey, sh, sp2(s, { aud: HOLE })), FORBIDDEN)
    await svc('for another method', (s) => sign(authorityKey, sh, sp2(s, { lxm: 'com.atproto.space.notifyRepoUpdate' })), E('BadJwtLexiconMethod'))
    await svc('with no lxm', (s) => sign(authorityKey, sh, sp2(s, { lxm: undefined })), E('BadJwtLexiconMethod'))
    await svc('past exp', (s) => sign(authorityKey, sh, sp2(s, { exp: now() - 2 })), E('JwtExpired'))
    await svc('with no exp', (s) => sign(authorityKey, sh, sp2(s, { exp: undefined })), E('BadJwt'))
    await svc('with no alg', (s) => sign(authorityKey, { typ: 'JWT' }, sp2(s)), E('BadJwt'))
    await svc('of typ at+jwt', (s) => sign(authorityKey, { ...sh, typ: 'at+jwt' }, sp2(s)), E('BadJwtType'))
    await svc('of typ refresh+jwt', (s) => sign(authorityKey, { ...sh, typ: 'refresh+jwt' }, sp2(s)), E('BadJwtType'))
    await svc('of typ dpop+jwt', (s) => sign(authorityKey, { ...sh, typ: 'dpop+jwt' }, sp2(s)), E('BadJwtType'))
    await svc('of no typ', (s) => sign(authorityKey, { alg: 'ES256K' }, sp2(s)), 200)
    await svc('of a delegation token\'s typ', (s) => sign(authorityKey, { ...sh, typ: 'atproto-space-delegation+jwt' }, sp2(s)), 200)
    await svc('with kid #atproto_kem', (s) => sign(authorityKey, { ...sh, kid: '#atproto_kem' }, sp2(s)), 200)
    await svc('with no jti or iat', (s) => sign(authorityKey, sh, sp2(s, { jti: undefined, iat: undefined })), 200)
    await svc('living a year', (s) => sign(authorityKey, sh, sp2(s, { exp: now() + 31536000 })), 200)
    await svc('high-S', (s) => sign(authorityKey, sh, sp2(s), { highS: true }), 200)
    await svc('from no DID', (s) => sign(authorityKey, sh, sp2(s, { iss: 'authority' })), E('BadJwtIss'))
    await svc('from a DID the directory lacks', (s) => sign(authorityKey, sh, sp2(s, { iss: HOLE })), E('AuthenticationRequired'))
    await svc('by another key', (s) => sign(strangerKey, sh, sp2(s)), E('BadJwtSignature'))
    await svc('a session token', (s) => s.writer.token, E('BadJwtType'))
    {
      const once = {}
      for (const n of [1, 2]) await svc(`sent twice (${n})`, async (s) => (once[s.label] ??= await sign(authorityKey, sh, sp2(s))), 200)
    }
    for (const [what, headers, want] of [
      ['no token', {}, E('MissingJwt')],
      ['Basic', { authorization: 'Basic YWRtaW46eA==' }, E('MissingJwt')],
      ['DPoP', { authorization: 'DPoP abc' }, E('MissingJwt')],
      ['an unknown scheme', { authorization: 'Foo abc' }, BAD_TOKEN],
      ['Bearer alone', { authorization: 'Bearer' }, BAD_TOKEN],
    ]) await revoke(what, { headers }, () => headers, { space: other, credentials: ['unused'] }, want)
    await revoke('a credential', {}, (s) => withSig(s, credential), { space: other, credentials: ['unused'] }, E('MissingJwt'))
    await revoke('no token, and input the lexicon refuses', {}, () => ({}), { space: other, credentials: [] }, E('MissingJwt'))
    for (const [what, body, want] of [
      ['no jti', { space: other, credentials: [] }, BAD_REQ],
      ['101 jtis', { space: other, credentials: Array.from({ length: 101 }, (_, i) => `j${i}`) }, BAD_REQ],
      ['100 jtis', { space: other, credentials: Array.from({ length: 100 }, (_, i) => `j${i}`) }, 200],
      ['an empty jti', { space: other, credentials: [''] }, BAD_REQ],
      ['no space-ref', { space: 'x', credentials: ['a'] }, BAD_REQ],
      ['a space never made', { space: `at://${authority.did}/space/${T}/never`, credentials: ['a'] }, 200],
    ]) await svc(`with ${what}`, (s) => sign(authorityKey, sh, sp2(s)), want, body)
    await both(sides, 'notifyCredentialsRevoked: GET', {}, async (side) => call(side.base, R, { headers: bearer(await sign(authorityKey, sh, sp2(side))) }), { want: BAD_REQ })

    // A revoked credential is refused here, for every repo; another space's jti is not.
    const revoked = JSON.parse(Buffer.from(credential.split('.')[1], 'base64url')).jti
    await svc('of the alpha\'s credential', (s) => sign(authorityKey, sh, sp2(s)), 200, { space, credentials: [revoked] })
    await read('revoked', {}, (s) => withSig(s, credential), E('CredentialRevoked'))
    await read('revoked, unsigned', {}, (s) => ({ authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': s.writer.did }), SIG)
    await read('revoked, addressed to the authority', {}, (s) => withSig(s, credential, authority.did), E('CredentialRevoked'))
    {
      const elsewhere = jti()
      await svc('of a jti, in another space', (s) => sign(authorityKey, sh, sp2(s)), 200, { space: other, credentials: [elsewhere] })
      await forged('with a jti revoked in another space', () => sign(authorityKey, ch, cp({ jti: elsewhere })), 200)
      const viaNeighbour = jti()
      await svc('to the neighbour', (s) => sign(authorityKey, sh, sp2(s, { aud: s.neighbour.did })), 200, { space, credentials: [viaNeighbour] })
      await forged('with a jti revoked to the neighbour', () => sign(authorityKey, ch, cp({ jti: viaNeighbour })), E('CredentialRevoked'))
    }
    const cs = sides[1]
    // A revocation outlives a restart (spec/SPACES-CREDENTIALS.md, "Durability").
    h.afterRestart.push(async () => {
      const n = shape(cs, await list(cs, withSig(cs, credential)))
      if (!matches(E('CredentialRevoked'), n)) await fail(cs, 'listRecords with a credential revoked before a restart', {}, E('CredentialRevoked'), n)
      count('listRecords with a credential revoked before a restart')
    })

    // A rotated key: a credential by the new key is taken at once, though the old was kept
    // (spec/SPACES-CREDENTIALS.md, "Issuers' keys").
    const rotor = await account(alpha.url, '.test')
    const open = `at://${rotor.did}/space/${T}/rot`
    await call(alpha.url, 'com.atproto.space.createSpace', { headers: bearer(rotor.token), body: { spaceType: T, skey: 'rot', policy: { $type: MEMBERSPACE, publicRead: true } } })
    sides.forEach((s) => s.names.push([rotor.did, '<rotor>']))
    const rp = () => ({ iss: rotor.did, sub: open, cnf: { kid: kid.did }, iat: now(), exp: now() + 600, jti: jti() })
    const oldKey = await alphaKey(alpha, rotor.did)
    await read('by an authority\'s key', {}, async (s) => withSig(s, await sign(oldKey, ch, rp())), 200, open)
    const client = new plc.Client(plcUrl)
    const newKey = await Secp256k1Keypair.create()
    await client.sendOperation(rotor.did, await plc.updateAtprotoKeyOp(await client.getLastOp(rotor.did), alpha.ctx.plcRotationKey, newKey.did()))
    await read('by the authority\'s new key, just rotated to', {}, async (s) => withSig(s, await sign(newKey, ch, rp())), 200, open)
    await read('by its old key, once rotated', {}, async (s) => withSig(s, await sign(oldKey, ch, rp())), E('BadJwtSignature'), open)
  }
}