~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
408 lines · 30.2 KB Raw History
// OAuth `space:` permissions (spec/OAUTH-SCOPES.md, "Spaces"), and those a
// permission set grants (spec/OAUTH-PERMISSION-SETS.md, "What a set
// grants"), against the pinned alpha, which keeps them. The run's lexicon
// authority, a PDS of its own on the alpha's directory, publishes space type
// declarations and permission sets, and both sides resolve each from it
// (PDS_LEXICON_AUTHORITY_DID, the alpha's `lexicon.didAuthority`). Loopback
// clients asking for `atproto` and `space:` scopes, or `include:` scopes of
// those sets, sign in on both sides: PAR, the authorization page, sign-in
// and consent through the page's API, the redirect and the code grant, each
// side's answers compared. With each session's access token, a good proof
// and a nonce, the space methods are called on the account's own spaces and
// another's, and each answer compared: its status, its error, and a
// ScopeMissingError's message, each account's DID named alike.

import { createHash, randomBytes, webcrypto } from 'node:crypto'
import http from 'node:http'
import { isDeepStrictEqual } from 'node:util'
import { TestPds } from '@atproto/dev-env'

const { subtle } = webcrypto
const SCHEMA = 'com.atproto.lexicon.schema'
const REDIRECT = 'http://127.0.0.1/callback'
const STAR = 'application/vnd.dasl.star'
const PERSONAL = { $type: 'com.atproto.personalspace.policy' }
const MEMBERS = { $type: 'com.atproto.memberspace.policy' }

/// The space types: one declared with collections, one with none, one with a
/// `key` and collections of its own; documents that are no declaration (no
/// `key`, no `collections`, another type of definition); and an NSID with
/// no document (spec/OAUTH-SCOPES.md, "Space type declarations").
const W = 'com.example.workspace'
const EMPTY = 'com.example.emptyspace'
const TILED = 'com.example.tiled'
const NO_KEY = 'com.example.nokeyspace'
const NO_COLLECTIONS = 'com.example.barespace'
const NOT_SPACE = 'com.example.notspace'
const MISSING = 'com.example.nospace'
const OTHER = 'com.example.otherspace'
const TILE = 'com.example.tile'
const NOTE = 'com.example.note'
const DECLARATIONS = {
  [W]: { type: 'space', key: 'any', title: 'Workspace', collections: [TILE, NOTE] },
  [EMPTY]: { type: 'space', key: 'any', collections: [] },
  [TILED]: { type: 'space', key: 'tid', collections: [TILE] },
  [NO_KEY]: { type: 'space', collections: [TILE] },
  [NO_COLLECTIONS]: { type: 'space', key: 'any' },
  [NOT_SPACE]: { type: 'record', key: 'tid', record: { type: 'object', properties: {} } },
}

/// Permission sets granting `space` permissions, each under `com.example.`
/// as the space types are (spec/OAUTH-PERMISSION-SETS.md, "What a set
/// grants"): kept as a bare type, managing every authority, with a key and
/// actions, with collections of another namespace and `*`, of a type with
/// no collections declared and of one with no document, beside `repo`;
/// and dropped, each for one reason.
const SP = (o) => ({ type: 'permission', resource: 'space', ...o })
const SET_BARE = 'com.example.wsBare'
const SET_MANAGE = 'com.example.wsManage'
const SET_KEYED = 'com.example.wsKeyed'
const SET_FOREIGN = 'com.example.wsForeign'
const SET_EMPTY = 'com.example.wsEmpty'
const SET_MISSING = 'com.example.wsMissing'
const SET_MIXED = 'com.example.wsMixed'
const SET_DROPPED = 'com.example.wsDropped'
const PERMISSION_SETS = {
  [SET_BARE]: { title: 'Workspaces', permissions: [SP({ spaceType: W })] },
  [SET_MANAGE]: { permissions: [SP({ spaceType: W, authority: '*', manage: ['update', 'create', 'delete'] })] },
  [SET_KEYED]: { permissions: [SP({ spaceType: W, authority: 'self', skey: 'main', collection: [TILE], action: ['create', 'read_self'], manage: ['create'] })] },
  [SET_FOREIGN]: {
    permissions: [
      SP({ spaceType: W, collection: ['org.other.thing', NOTE, NOTE], action: ['create'] }),
      SP({ spaceType: W, collection: [TILE, '*'], action: ['update', 'read', 'delete'], manage: ['delete'] }),
    ],
  },
  [SET_EMPTY]: { permissions: [SP({ spaceType: EMPTY, manage: ['create'] })] },
  [SET_MISSING]: { permissions: [SP({ spaceType: MISSING }), SP({ spaceType: W })] },
  [SET_MIXED]: {
    permissions: [
      { type: 'permission', resource: 'repo', collection: [NOTE] },
      SP({ spaceType: TILED, action: ['read', 'create'] }),
      { type: 'permission', resource: 'rpc', lxm: ['com.example.ping'], inheritAud: true },
    ],
  },
  [SET_DROPPED]: {
    permissions: [
      SP({ spaceType: W, action: ['read'] }),
      SP({ spaceType: '*', manage: ['create'] }),
      SP({ spaceType: 'org.other.space', manage: ['create'] }),
      SP({ spaceType: W, authority: 'me', manage: ['create'] }),
      SP({ spaceType: W, manage: ['create'], inheritAud: true }),
      SP({ spaceType: W, manage: 'create' }),
      SP({ spaceType: [W], manage: ['create'] }),
      SP({ spaceType: W, collection: [], manage: ['create'] }),
      SP({ spaceType: W, action: ['write'] }),
      SP({ manage: ['create'] }),
    ],
  },
}

/// The run's lexicon authority: a PDS on the alpha's directory with one
/// account publishing the declarations and the sets. Answers `{pds, did}`.
export async function hostDeclarations(plcUrl) {
  const pds = await TestPds.create({ didPlcUrl: plcUrl, hostname: 'localhost', inviteRequired: false })
  const handle = `lex${randomBytes(4).toString('hex')}.test`
  const made = await fetch(`${pds.url}/xrpc/com.atproto.server.createAccount`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ handle, email: `${handle}@example.com`, password: 'lexicons' }) }).then((r) => r.json())
  const sets = Object.entries(PERMISSION_SETS).map(([id, main]) => [id, { type: 'permission-set', ...main }])
  for (const [id, main] of [...Object.entries(DECLARATIONS), ...sets]) {
    const r = await fetch(`${pds.url}/xrpc/com.atproto.repo.createRecord`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${made.accessJwt}` }, body: JSON.stringify({ repo: made.did, collection: SCHEMA, rkey: id, validate: false, record: { $type: SCHEMA, lexicon: 1, id, defs: { main } } }) })
    if (!r.ok) throw new Error(`the lexicon authority could not publish ${id}: ${r.status} ${await r.text()}`)
  }
  return { pds, did: made.did }
}

// ---- an OAuth client and a browser, without a browser -----------------------------

const b64u = (b) => Buffer.from(b).toString('base64url')
const sha256 = (s) => b64u(createHash('sha256').update(s).digest())

async function newKey() {
  const { privateKey, publicKey } = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
  const { kty, crv, x, y } = await subtle.exportKey('jwk', publicKey)
  return { privateKey, jwk: { kty, crv, x, y } }
}

/// A DPoP proof (RFC 9449) for `htm` `htu`, with the server's nonce and the
/// access token's hash when given.
async function proof(key, htm, htu, { nonce, access } = {}) {
  const header = { typ: 'dpop+jwt', alg: 'ES256', jwk: key.jwk }
  const claims = { jti: b64u(randomBytes(16)), htm, htu, iat: Math.floor(Date.now() / 1000), ...(nonce ? { nonce } : {}), ...(access ? { ath: sha256(access) } : {}) }
  const input = `${b64u(JSON.stringify(header))}.${b64u(JSON.stringify(claims))}`
  const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key.privateKey, Buffer.from(input))
  return `${input}.${b64u(sig)}`
}

/// One request with node:http (fetch sets `Sec-Fetch-Mode` itself), keeping
/// the cookies in `jar`. Answers its status, headers, body as a Buffer, and
/// the body as JSON when it is.
function request(url, { method = 'GET', headers = {}, body, jar } = {}) {
  return new Promise((resolve) => {
    const h = { ...headers }
    if (jar?.size) h.cookie = [...jar].map(([k, v]) => `${k}=${v}`).join('; ')
    const req = http.request(url, { method, headers: h }, (res) => {
      const chunks = []
      res.on('data', (c) => chunks.push(c))
      res.on('end', () => {
        for (const c of res.headers['set-cookie'] ?? []) {
          const [pair] = c.split(';')
          const i = pair.indexOf('=')
          jar?.set(pair.slice(0, i).trim(), pair.slice(i + 1).trim())
        }
        const buf = Buffer.concat(chunks)
        let json = null
        try { json = JSON.parse(buf.toString('utf8')) } catch {}
        resolve({ status: res.statusCode, headers: res.headers, buf, json })
      })
    })
    req.on('error', (e) => resolve({ status: 0, headers: {}, buf: Buffer.alloc(0), json: { error: `request failed: ${e.message}` } }))
    req.end(body)
  })
}

/// A client's DPoP state on one server: `send` proves each request, and
/// retries once with the nonce a `use_dpop_nonce` refusal gives, as
/// clients do.
class Dpop {
  constructor(key) { this.key = key; this.nonce = undefined }
  async send(url, { method = 'GET', headers = {}, body, access } = {}) {
    const u = new URL(url)
    for (let attempt = 0; ; attempt++) {
      const h = { ...headers, dpop: await proof(this.key, method, u.origin + u.pathname, { nonce: this.nonce, access }) }
      if (access) h.authorization = `DPoP ${access}`
      const res = await request(url, { method, headers: h, body })
      if (res.headers['dpop-nonce']) this.nonce = res.headers['dpop-nonce']
      const nonceAsked = res.json?.error === 'use_dpop_nonce' || /use_dpop_nonce/.test(String(res.headers['www-authenticate'] ?? ''))
      if (nonceAsked && attempt === 0) continue
      return res
    }
  }
}

const form = (p) => ({ headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(p).toString() })
const NAVIGATE = { 'sec-fetch-mode': 'navigate', 'sec-fetch-dest': 'document' }

/// A sign-in of `acct` on `side` by a loopback client asking for `scope`
/// (spec/OAUTH.md): PAR, the page, the API's sign-in and consent, the
/// redirect, and the code grant. Answers what is compared of each step
/// reached (`view`), and the session (`{dpop, access}`) when one was made.
async function signIn(side, acct, scope) {
  const origin = new URL(side.publicUrl).origin
  const clientId = `http://localhost?${new URLSearchParams([['scope', scope], ['redirect_uri', REDIRECT]])}`
  const dpop = new Dpop(await newKey())
  const verifier = b64u(randomBytes(32))
  const par = await dpop.send(`${origin}/oauth/par`, { method: 'POST', ...form({ client_id: clientId, response_type: 'code', redirect_uri: REDIRECT, scope, state: 'st', code_challenge: sha256(verifier), code_challenge_method: 'S256' }) })
  if (par.status !== 201) return { view: { par: par.status, error: par.json?.error ?? null } }
  const page = `${origin}/oauth/authorize?${new URLSearchParams({ client_id: clientId, request_uri: par.json.request_uri })}`
  const jar = new Map()
  const loaded = await request(page, { jar, headers: { ...NAVIGATE, 'sec-fetch-site': 'cross-site' } })
  if (loaded.status !== 200) {
    const to = loaded.headers.location ? new URL(loaded.headers.location) : null
    const again = await request(page, { jar, headers: { ...NAVIGATE, 'sec-fetch-site': 'cross-site' } })
    return { view: { par: 201, page: loaded.status, to: to && `${to.origin}${to.pathname}`, error: to?.searchParams.get('error') ?? null, state: to?.searchParams.get('state') ?? null, again: again.status } }
  }
  // The page's `spaces` and `spaceHandles` (spec/OAUTH-SCOPES.md, "On the
  // authorization page"), each `{}` when not there.
  const m = /window\["__authorizeData"\]\s*=\s*JSON\.parse\(("(?:[^"\\]|\\.)*")\)/.exec(loaded.buf.toString('utf8'))
  let d = {}
  try { d = m ? JSON.parse(JSON.parse(m[1])) : {} } catch {}
  const shown = { par: 201, page: 200, data: { spaces: d.spaces ?? {}, spaceHandles: d.spaceHandles ?? {} } }
  const api = (endpoint, input) => request(`${origin}/@atproto/oauth-provider/~api${endpoint}`, { method: 'POST', jar, body: JSON.stringify(input), headers: { origin, referer: page, 'sec-fetch-mode': 'same-origin', 'sec-fetch-site': 'same-origin', 'sec-fetch-dest': 'empty', 'x-csrf-token': jar.get('csrf-token'), 'content-type': 'application/json' } })
  const si = await api('/sign-in', { locale: 'en', identifier: acct.sides[side.name].handle ?? acct.handle, password: acct.password, remember: true })
  if (si.status !== 200) return { view: { ...shown, signIn: si.status, error: si.json?.error ?? null } }
  const c = await api('/consent', { did: acct.sides[side.name].did })
  if (c.status !== 200) return { view: { ...shown, signIn: 200, consent: c.status, error: c.json?.error ?? null } }
  const back = await request(new URL(c.json.url, origin).href, { jar, headers: { ...NAVIGATE, 'sec-fetch-site': 'same-origin', referer: page } })
  const code = back.headers.location ? new URL(back.headers.location).searchParams.get('code') : null
  const t = await dpop.send(`${origin}/oauth/token`, { method: 'POST', ...form({ grant_type: 'authorization_code', client_id: clientId, redirect_uri: REDIRECT, code: code ?? '', code_verifier: verifier }) })
  if (t.status !== 200) return { view: { ...shown, signIn: 200, consent: 200, token: t.status, error: t.json?.error ?? null } }
  return { view: { ...shown, signIn: 200, consent: 200, token: 200, scope: t.json.scope }, session: { dpop, access: t.json.access_token, origin } }
}

/// An XRPC call with an OAuth session's access token and a proof: `params`
/// in the query; `body`, JSON; `raw`, an archive.
function oauthCall(s, nsid, { params, body, raw } = {}) {
  const u = new URL(`${s.origin}/xrpc/${nsid}`)
  for (const [k, v] of Object.entries(params ?? {})) u.searchParams.set(k, v)
  if (raw !== undefined) return s.dpop.send(u.href, { method: 'POST', access: s.access, headers: { 'content-type': STAR }, body: raw })
  if (body !== undefined) return s.dpop.send(u.href, { method: 'POST', access: s.access, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
  return s.dpop.send(u.href, { access: s.access })
}

/// An XRPC call with a password session's access token.
function passwordCall(side, token, nsid, { params, body } = {}) {
  const u = new URL(`${side.url}/xrpc/${nsid}`)
  for (const [k, v] of Object.entries(params ?? {})) u.searchParams.set(k, v)
  const headers = { authorization: `Bearer ${token}` }
  if (body !== undefined) headers['content-type'] = 'application/json'
  return request(u.href, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) })
}

// ---- the check -----------------------------------------------------------------------

export async function checkSpaceScopes(h) {
  const { ref, cand, accounts, createAccount, rand, differ, count } = h
  const sides = [ref, cand]
  const skey = (p) => `${p}${Math.floor(rand() * 1e6)}`
  const alice = await createAccount()
  const bob = await createAccount()
  const did = (side, acct) => acct.sides[side.name].did
  const sp = (side, acct, key, type = W) => `at://${did(side, acct)}/space/${type}/${key}`

  /// Each account's DID named alike; a space key the server made (a TID) as `<tid>`.
  const named = (side, s) => {
    for (const a of accounts) s = s.split(a.sides[side.name].did).join(`<did:${a.n}>`)
    return s.replace(/skey=[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}\b/g, 'skey=<tid>')
  }
  /// What is compared of an answer: its status and error, and the message of
  /// a ScopeMissingError, which names the scope that would allow the call.
  const answer = (side, r) => (r.status === 200 ? { status: 200 } : { status: r.status, error: r.json?.error ?? null, ...(r.json?.error === 'ScopeMissingError' ? { message: named(side, String(r.json.message)) } : {}) })

  /// Clients' scopes, each a function of the side for those naming a DID,
  /// with what each case is for.
  const other = (side) => did(side, bob)
  const CASES = [
    ['a bare type', () => `atproto space:${W}`],
    ['manage=create', () => `atproto space:${W}?manage=create`],
    ['every authority, managing', () => `atproto space:${W}?authority=*&manage=create&manage=update&manage=delete`],
    ['the positional as a parameter, actions out of order', () => `atproto space?spaceType=${W}&action=delete&action=read`],
    ['read alone', () => `atproto space:${W}?action=read`],
    ['read_self alone', () => `atproto space:${W}?action=read_self`],
    ['read_self and managing', () => `atproto space:${W}?authority=*&action=read_self&manage=update&manage=delete`],
    ['a collection outside the declaration', () => `atproto space:${W}?collection=${NOTE}&collection=com.example.zz&collection=${NOTE}&action=create&action=update`],
    ['every collection', () => `atproto space:${W}?collection=*&collection=${TILE}&manage=create`],
    ['one key', (side) => `atproto space:${W}?skey=main&authority=self&manage=create`],
    ['another authority', (side) => `atproto space:${W}?authority=${other(side)}&manage=update`],
    ['a declaration with no collections', () => `atproto space:${EMPTY}?manage=create`],
    ['another declared type beside', () => `atproto space:${TILED} space:${W}?action=read_self`],
    ['every type', () => 'atproto space:*'],
    ['every type and authority, reading', () => 'atproto space:*?authority=*&action=read_self'],
    ['every type with a collection', () => `atproto space:*?collection=${TILE}&manage=create`],
    ['transition:generic alone', () => 'atproto transition:generic'],
    ['tokens that do not parse', () => `atproto space:forum space:${W}?action=write space:${W}?authority=me space:${W}?spaceType=${W}`],
    ['a declaration with no key', () => `atproto space:${NO_KEY}`],
    ['a declaration with no collections field', () => `atproto space:${NO_COLLECTIONS}`],
    ['a document that is no declaration', () => `atproto space:${NOT_SPACE}`],
    ['a type with no document', () => `atproto space:${MISSING} space:${W}`],
    // Sets granting `space` permissions (spec/OAUTH-PERMISSION-SETS.md,
    // "What a set grants", "The token's scope").
    ['a set of a bare type', () => `atproto include:${SET_BARE}`],
    ['a set managing every authority', () => `atproto include:${SET_MANAGE}`],
    ['a set with a key and actions, beside a space: token', () => `atproto include:${SET_KEYED} space:${TILED}?action=read_self`],
    ['a set with collections of another namespace and every collection', () => `atproto include:${SET_FOREIGN}`],
    ['a set of a type declaring no collections', () => `atproto include:${SET_EMPTY}`],
    ['a set of a type with no document', () => `atproto include:${SET_MISSING}`],
    ['a set whose space permissions are dropped but one', () => `atproto include:${SET_DROPPED}`],
    ['sets with an aud, twice, beside repo', () => `atproto include:${SET_MIXED}?aud=did:web:api.example.com%23svc include:${SET_BARE} repo:${NOTE} include:${SET_BARE}`],
  ]

  // The account's spaces, made with its password session on each side: a
  // personalspace and a memberspace of the declared type, with a record in
  // the first; and another's, a personalspace of the other account.
  async function made(kind, side, token, nsid, body) {
    const r = await passwordCall(side, token, nsid, { body })
    if (r.status !== 200) await differ(`space scopes: ${kind}`, body, 'made', answer(side, r), `the ${side.name} refuses what the check needs`)
  }
  const tok = (side, acct) => acct.sides[side.name].token

  for (const [what, scopeOf] of CASES) {
    const own = skey('own')
    const mem = skey('mem')
    const theirs = skey('their')
    for (const side of sides) {
      await made('createSpace', side, tok(side, alice), 'com.atproto.space.createSpace', { spaceType: W, skey: own, policy: PERSONAL })
      await made('createSpace', side, tok(side, alice), 'com.atproto.space.createSpace', { spaceType: W, skey: mem, policy: MEMBERS })
      await made('putRecord', side, tok(side, alice), 'com.atproto.space.putRecord', { space: sp(side, alice, own), repo: did(side, alice), collection: TILE, rkey: 'a', record: { $type: TILE, n: 1 } })
      await made('createSpace', side, tok(side, bob), 'com.atproto.space.createSpace', { spaceType: W, skey: theirs, policy: PERSONAL })
    }
    const signed = {}
    for (const side of sides) signed[side.name] = await signIn(side, alice, scopeOf(side))
    const views = sides.map((side) => {
      const v = { ...signed[side.name].view }
      if (v.scope !== undefined) v.scope = named(side, v.scope)
      if (v.data) {
        let s = named(side, JSON.stringify(v.data))
        for (const a of accounts) if (a.sides[side.name].handle) s = s.split(a.sides[side.name].handle).join(`<handle:${a.n}>`)
        v.data = JSON.parse(s)
      }
      return v
    })
    const request = { client: named(ref, scopeOf(ref)) }
    const cites = /include:/.test(scopeOf(ref)) ? '; spec/OAUTH-PERMISSION-SETS.md, "What a set grants", "The token\'s scope"' : ''
    if (!isDeepStrictEqual(views[0], views[1])) await differ(`space scopes: a sign-in asking for ${what} (spec/OAUTH-SCOPES.md, "Spaces", "Space type declarations", "On the authorization page", "The token's scope"${cites})`, request, views[0], views[1])
    count(`space scopes: sign-in, ${what}`)
    if (!signed.reference.session) continue
    const sessions = { reference: signed.reference.session, server: signed.server.session }

    const mine = (side, key = own, type = W) => sp(side, alice, key, type)
    // Drawn once, for both sides alike.
    const [fresh, otherKey, badKey] = [skey('new'), skey('o'), skey('b')]
    const calls = [
      ['createSpace', 'com.atproto.space.createSpace', () => ({ body: { spaceType: W, skey: fresh, policy: PERSONAL } })],
      ['createSpace of another type', 'com.atproto.space.createSpace', () => ({ body: { spaceType: OTHER, skey: otherKey, policy: PERSONAL } })],
      ['createSpace with no skey', 'com.atproto.space.createSpace', () => ({ body: { spaceType: W, policy: PERSONAL } })],
      ['createSpace with key main', 'com.atproto.space.createSpace', () => ({ body: { spaceType: W, skey: 'main', policy: PERSONAL } })],
      ['createSpace with a bad spaceType', 'com.atproto.space.createSpace', () => ({ body: { spaceType: 'nope', skey: badKey, policy: PERSONAL } })],
      ['getSpace', 'com.atproto.space.getSpace', (side) => ({ params: { space: mine(side) } })],
      ['getSpace of another\'s', 'com.atproto.space.getSpace', (side) => ({ params: { space: sp(side, bob, theirs) } })],
      ['listSpaces', 'com.atproto.space.listSpaces', () => ({})],
      ['listSpaces of a type', 'com.atproto.space.listSpaces', () => ({ params: { spaceType: W } })],
      ['listSpaces of its own authority', 'com.atproto.space.listSpaces', (side) => ({ params: { spaceDid: did(side, alice) } })],
      ['listSpaces of a type and another authority', 'com.atproto.space.listSpaces', (side) => ({ params: { spaceType: W, spaceDid: did(side, bob) } })],
      ['putRecord of a record there', 'com.atproto.space.putRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'a', record: { $type: TILE, n: 2 } } })],
      ['putRecord of a new record', 'com.atproto.space.putRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'b', record: { $type: TILE, n: 3 } } })],
      ['createRecord of a declared collection', 'com.atproto.space.createRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: NOTE, rkey: 'n', record: { $type: NOTE } } })],
      ['createRecord of another collection', 'com.atproto.space.createRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: 'com.example.zz', rkey: 'z', record: { $type: 'com.example.zz' } } })],
      ['createRecord in another\'s space', 'com.atproto.space.createRecord', (side) => ({ body: { space: sp(side, bob, theirs), repo: did(side, alice), collection: TILE, rkey: 't', record: { $type: TILE } } })],
      ['createRecord of a record of another type', 'com.atproto.space.createRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'x', record: { $type: NOTE } } })],
      ['createRecord of a published collection', 'com.atproto.space.createRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: 'com.atproto.space.policy', rkey: 'self', record: { $type: 'com.atproto.space.policy' } } })],
      ['createRecord in another\'s repo', 'com.atproto.space.createRecord', (side) => ({ body: { space: mine(side), repo: did(side, bob), collection: TILE, rkey: 'r', record: { $type: TILE } } })],
      ['createRecord in a space never made', 'com.atproto.space.createRecord', (side) => ({ body: { space: mine(side, 'never'), repo: did(side, alice), collection: TILE, rkey: 'v', record: { $type: TILE } } })],
      ['putRecord of a record of another type', 'com.atproto.space.putRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'a', record: { $type: NOTE } } })],
      ['putRecord in a space never made', 'com.atproto.space.putRecord', (side) => ({ body: { space: mine(side, 'never'), repo: did(side, alice), collection: TILE, rkey: 'a', record: { $type: TILE } } })],
      ['deleteRecord of a record not there', 'com.atproto.space.deleteRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'none' } })],
      ['deleteRecord', 'com.atproto.space.deleteRecord', (side) => ({ body: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'a' } })],
      ['applyWrites with a bad write', 'com.atproto.space.applyWrites', (side) => ({ body: { space: mine(side), repo: did(side, alice), writes: [{ $type: 'com.atproto.space.applyWrites#create', collection: TILE, rkey: 'd', value: { $type: TILE } }, { $type: 'com.atproto.space.applyWrites#create', collection: TILE, rkey: 'e', value: { $type: NOTE } }] } })],
      ['applyWrites with no writes', 'com.atproto.space.applyWrites', (side) => ({ body: { space: mine(side), repo: did(side, alice), writes: [] } })],
      ['getRecord in a space never made', 'com.atproto.space.getRecord', (side) => ({ params: { space: mine(side, 'never'), repo: did(side, alice), collection: TILE, rkey: 'a' } })],
      ['getSpace of a space never made', 'com.atproto.space.getSpace', (side) => ({ params: { space: mine(side, 'never') } })],
      ['getSpace of a bad space', 'com.atproto.space.getSpace', () => ({ params: { space: 'nope' } })],
      ['applyWrites', 'com.atproto.space.applyWrites', (side) => ({ body: { space: mine(side), repo: did(side, alice), writes: [{ $type: 'com.atproto.space.applyWrites#create', collection: TILE, rkey: 'c', value: { $type: TILE } }, { $type: 'com.atproto.space.applyWrites#update', collection: NOTE, rkey: 'n', value: { $type: NOTE, v: 2 } }, { $type: 'com.atproto.space.applyWrites#delete', collection: TILE, rkey: 'b' }] } })],
      ['getRecord', 'com.atproto.space.getRecord', (side) => ({ params: { space: mine(side), repo: did(side, alice), collection: TILE, rkey: 'a' } })],
      ['getRecord of another\'s repo', 'com.atproto.space.getRecord', (side) => ({ params: { space: mine(side), repo: did(side, bob), collection: TILE, rkey: 'a' } })],
      ['listRecords', 'com.atproto.space.listRecords', (side) => ({ params: { space: mine(side), repo: did(side, alice), collection: TILE } })],
      ['getLatestCommit', 'com.atproto.space.getLatestCommit', (side) => ({ params: { space: mine(side), repo: did(side, alice) } })],
      ['listRepoOps', 'com.atproto.space.listRepoOps', (side) => ({ params: { space: mine(side), repo: did(side, alice) } })],
      ['getRepo', 'com.atproto.space.getRepo', (side) => ({ params: { space: mine(side), repo: did(side, alice) } })],
      ['listBlobs', 'com.atproto.space.listBlobs', (side) => ({ params: { space: mine(side), repo: did(side, alice) } })],
      ['getDelegationToken', 'com.atproto.space.getDelegationToken', (side) => ({ params: { space: mine(side) } })],
      ['getDelegationToken of another\'s space', 'com.atproto.space.getDelegationToken', (side) => ({ params: { space: sp(side, bob, theirs) } })],
      ['putMembers', 'com.atproto.memberspace.putMembers', (side) => ({ body: { space: mine(side, mem), members: [{ did: did(side, bob), read: true, write: false }] } })],
      ['listMembers', 'com.atproto.memberspace.listMembers', (side) => ({ params: { space: mine(side, mem) } })],
      ['removeMembers', 'com.atproto.memberspace.removeMembers', (side) => ({ body: { space: mine(side, mem), dids: [did(side, bob)] } })],
      ['removeWriter', 'com.atproto.space.removeWriter', (side) => ({ body: { space: mine(side, mem), did: did(side, bob) } })],
      ['updateSpace', 'com.atproto.space.updateSpace', (side) => ({ body: { space: mine(side, mem), policy: MEMBERS } })],
      ['updateSpace of another\'s', 'com.atproto.space.updateSpace', (side) => ({ body: { space: sp(side, bob, theirs), policy: PERSONAL } })],
      ['exportSpaceMeta', 'com.atproto.space.exportSpaceMeta', (side) => ({ params: { space: mine(side, mem) } })],
      ['clearRecords', 'com.atproto.space.clearRecords', (side) => ({ body: { space: mine(side), repo: did(side, alice) } })],
      ['deleteSpace', 'com.atproto.space.deleteSpace', (side) => ({ body: { space: mine(side) } })],
      ['deleteSpace of another\'s', 'com.atproto.space.deleteSpace', (side) => ({ body: { space: sp(side, bob, theirs) } })],
    ]
    for (const [name, nsid, input] of calls) {
      const got = []
      for (const side of sides) got.push(answer(side, await oauthCall(sessions[side.name], nsid, input(side))))
      if (!isDeepStrictEqual(got[0], got[1])) await differ(`space scopes: ${name} with a session asking for ${what} (spec/OAUTH-SCOPES.md, "Spaces", "What it allows", "What each method needs", "The refusal")`, { nsid, client: request.client, scope: views[0].scope, input: input(ref) }, got[0], got[1])
      count(`space scopes: ${name}, ${got[0].status === 200 ? 'allowed' : got[0].error}`)
    }

    // importSpaceMeta of the memberspace's archive, exported with the
    // password session (spec/OAUTH-SCOPES.md, "What each method needs").
    const got = []
    for (const side of sides) {
      const archive = await passwordCall(side, tok(side, alice), 'com.atproto.space.exportSpaceMeta', { params: { space: mine(side, mem) } })
      if (archive.status !== 200) await differ('space scopes: exportSpaceMeta with the password session', {}, 200, answer(side, archive), `the ${side.name} refuses what the check needs`)
      got.push(answer(side, await oauthCall(sessions[side.name], 'com.atproto.space.importSpaceMeta', { raw: archive.buf })))
    }
    if (!isDeepStrictEqual(got[0], got[1])) await differ(`space scopes: importSpaceMeta with a session asking for ${what} (spec/OAUTH-SCOPES.md, "What each method needs")`, { client: request.client, scope: views[0].scope }, got[0], got[1])
    count(`space scopes: importSpaceMeta, ${got[0].status === 200 ? 'allowed' : got[0].error}`)
  }
}