chadtmiller.com/monolith
An atproto PDS
0
0
// Identity: resolveHandle, updateHandle and the operation it posts to the
// PLC directory, /.well-known/atproto-did, and getRecommendedDidCredentials
// (spec/IDENTITY.md). Each is held to the reference.
import http from 'node:http'
import { isDeepStrictEqual } from 'node:util'
import { cborEncode, cidForCbor } from '@atproto/common'
import { verifySignature } from '@atproto/crypto'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { cand, net, plcUrl, ref } from '../lib/processes.mjs'
import { begin, end, now } from '../lib/observe.mjs'
import { checkDidDoc, fail, plcDocument, plcLog } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { both, normalize, shown, strip, xrpcHttp } from '../lib/xrpc.mjs'
import { can, own } from '../lib/server.mjs'
import { DISALLOWED_TLDS, RESERVABLE, freshFront, mixCase } from './accounts.mjs'
const RESOLVE = 'com.atproto.identity.resolveHandle'
const UPDATE = 'com.atproto.identity.updateHandle'
const CREDENTIALS = 'com.atproto.identity.getRecommendedDidCredentials'
/// Handles an account had and changed, which no account has now.
const freed = []
/// Domains whose names resolve to nothing in DNS (RFC 2606), for external
/// handles: the reference looks those up, and must find no DID.
const EXTERNAL = ['.example.com', '.example.net', '.example.org']
const external = (f) => `${chance(0.3) ? 'zz.' : ''}${f}${pick(EXTERNAL)}`
/// updateHandle on both sides, compared. It answers no body, which
/// COMMANDS.md gives no tool or command form, so it goes over XRPC.
async function bothHttp(kind, nsid, request) {
const [a, b] = await Promise.all([ref, cand].map((side) => xrpcHttp(side, nsid, request)))
const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
if (!isDeepStrictEqual(na, nb)) await differ(nsid, shown(request), na, nb)
count(kind, a.status < 400)
return [a, b]
}
/// Each side's PLC log for the account's DID, by side name.
async function logs(acct) {
const out = {}
for (const side of [ref, cand]) {
const log = await plcLog(didOf(side, acct))
out[side.name] = Array.isArray(log.body) ? log.body : []
}
return out
}
/// `alsoKnownAs` with its first `at://` entry made `at://<handle>`, or with
/// that first if it has none (spec/IDENTITY.md, "updateHandle").
function withHandle(aka, handle) {
const i = aka.findIndex((u) => u.startsWith('at://'))
return i < 0 ? [`at://${handle}`, ...aka] : aka.map((u, j) => (j === i ? `at://${handle}` : u))
}
/// The side's log for the account must be `before` and one operation more:
/// the update that gives it `handle`, on the last one before, signed with
/// the side's rotation key. The reference is held to it too
/// (spec/IDENTITY.md, "updateHandle").
async function checkOperation(side, acct, before, handle, request) {
const log = await plcLog(didOf(side, acct))
if (log.status !== 200 || !Array.isArray(log.body) || log.body.length !== before.length + 1 || !isDeepStrictEqual(log.body.slice(0, -1), before)) {
return fail(side, 'PLC log after a handle change', request, `the ${before.length} operations before, and one more`, log)
}
const last = before.at(-1)
const { sig: _, ...prev } = last
const { sig, ...op } = log.body.at(-1)
const want = { ...prev, alsoKnownAs: withHandle(prev.alsoKnownAs ?? [], handle), prev: (await cidForCbor(last)).toString() }
if (!isDeepStrictEqual(op, want)) return fail(side, 'PLC update operation', request, want, op)
let ok = false
try {
ok = typeof sig === 'string' && (await verifySignature(side.rotationKey, cborEncode(op), Buffer.from(sig, 'base64url')))
} catch {}
if (!ok) await fail(side, 'PLC update operation', request, `a signature by the side's rotation key, ${side.rotationKey}`, { sig })
}
/// The side's log for the account must still be `before`: a refused change
/// posts no operation (spec/IDENTITY.md, "updateHandle").
async function checkNoOperation(side, acct, before, request) {
const log = await plcLog(didOf(side, acct))
if (!isDeepStrictEqual(log.body, before)) await fail(side, 'PLC log after a refused handle change', request, `the ${before.length} operations before, and no more`, log)
}
/// Have the reference resolve the account's DID document again: it keeps
/// the ones it resolved for an hour, and its describeRepo must answer the
/// directory's (spec/IDENTITY.md, "describeRepo's didDoc and
/// handleIsCorrect").
const refresh = (acct) => net.pds.ctx.idResolver.did.resolve(didOf(ref, acct), true)
/// Note that `side` gave the account `handle`.
function gave(side, acct, handle) {
acct.handles[side.name].push(handle)
}
/// After both sides gave the account `handle`: what the harness knows of
/// it, and every way of naming it, by the new handle and the old
/// (spec/IDENTITY.md, "updateHandle", "describeRepo's didDoc and
/// handleIsCorrect", "/.well-known/atproto-did").
async function changed(acct, handle, { checkOld = true } = {}) {
const old = acct.handle
acct.handle = handle
const i = freed.indexOf(handle)
if (i >= 0) freed.splice(i, 1)
if (old !== handle && !freed.includes(old)) freed.push(old)
await refresh(acct)
await both('getSession after a handle change', 'com.atproto.server.getSession', { token: acct })
const [a, b] = await both('describeRepo after a handle change', 'com.atproto.repo.describeRepo', { params: { repo: handle } })
for (const [side, res] of [[ref, a], [cand, b]]) if (res.status === 200) await checkDidDoc(side, didOf(side, acct), res.body.didDoc, 'describeRepo after a handle change', { repo: handle })
await both('resolveHandle after a handle change', RESOLVE, { params: { handle: chance(0.5) ? mixCase(handle) : handle } })
await wellKnownBoth('well-known after a handle change', handle)
if (!checkOld || old === handle) return
await both('describeRepo by an old handle', 'com.atproto.repo.describeRepo', { params: { repo: old } })
await both('resolveHandle of an old handle', RESOLVE, { params: { handle: old } })
await wellKnownBoth('well-known of an old handle', old)
}
/// Change the account's handle to `handle` on both sides, which both must
/// do, and check what follows.
async function change(acct, handle, kind, opts) {
const before = await logs(acct)
const body = { handle }
const [a, b] = await bothHttp(kind, UPDATE, { body, token: acct })
if (a.status !== 200) await differ(UPDATE, body, 'a change', a.body, 'the reference refuses a change the harness means to make')
const want = handle.toLowerCase()
const request = shown({ body, token: acct })
for (const side of [ref, cand]) await checkOperation(side, acct, before[side.name], want, request)
for (const side of [ref, cand]) gave(side, acct, want)
await changed(acct, want, opts)
}
/// An operation the side did not post, as another holder of a rotation key
/// might: the account's last one with an `https://` entry added to
/// `alsoKnownAs`, signed with the side's rotation key. The next handle
/// change must build on it and keep the entry (spec/IDENTITY.md,
/// "updateHandle", "describeRepo's didDoc and handleIsCorrect"). Not made
/// where the harness has no rotation key of the server's to sign with
/// (spec/COMPAT.md).
async function outsideOperation(acct) {
const entry = `https://${freshFront()}.example.com`
const first = chance(0.5)
for (const side of [ref, cand]) {
const did = didOf(side, acct)
const log = await plcLog(did)
const last = log.body.at(-1)
const { sig: _, ...fields } = last
const op = { ...fields, alsoKnownAs: first ? [entry, ...fields.alsoKnownAs] : [...fields.alsoKnownAs, entry], prev: (await cidForCbor(last)).toString() }
const signed = { ...op, sig: Buffer.from(await side.plcSigner.sign(cborEncode(op))).toString('base64url') }
const r = await fetch(`${plcUrl}/${did}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(signed) })
if (!r.ok) await differ('an operation of the harness\'s own', { did: `<did:${acct.n}>` }, 'the directory takes it', { status: r.status, body: await r.text() }, 'the harness fails its own step')
}
await refresh(acct)
const [a, b] = await both('describeRepo after an operation the server did not post', 'com.atproto.repo.describeRepo', { params: { repo: acct.handle } })
for (const [side, res] of [[ref, a], [cand, b]]) if (res.status === 200) await checkDidDoc(side, didOf(side, acct), res.body.didDoc, 'describeRepo after an operation the server did not post', { repo: acct.handle })
}
/// updateHandle that both sides must make: to a new handle, sometimes in
/// mixed case; to the account's own, in mixed case; or to one another
/// account had before. Sometimes after an operation the server did not
/// post (spec/IDENTITY.md, "updateHandle").
export async function updateHandle(acct) {
if (chance(0.15) && acct.handles.server.length < 6 && can('rotationKey')) await outsideOperation(acct)
const r = rand()
if (r < 0.15) return change(acct, mixCase(acct.handle), 'updateHandle to its own handle')
if (r < 0.3 && freed.length) return change(acct, pick(freed), 'updateHandle to a handle an account had')
const handle = `${freshFront()}.test`
await change(acct, chance(0.3) ? mixCase(handle) : handle, 'updateHandle')
}
/// Faults in updateHandle's handle, each refused alone: `[name, handle of
/// a fresh front part]`. A handle another account has needs one.
const FAULTS = [
['handle missing', () => undefined],
['handle not a string', () => pick([5, null, true, ['x.test']])],
['handle syntax', (f) => pick([`-${f}.test`, `${f}..test`, `${f}_x.test`, `${f} x.test`, f, `${f}.test.`, `${f}.1test`])],
['disallowed TLD', (f) => `${f}${pick(DISALLOWED_TLDS)}`],
['external handle', (f) => external(f)],
['dot in front part', (f) => `${pick(['a', 'x1', f])}.${f}.test`],
['too short', () => `${pick(['a', 'ab', 'x9', 'q'])}.test`],
['reserved and too short', () => `${pick(['ad', 'me', 'go', 'js'])}.test`],
['too long', (f) => `${f}${'z'.repeat(19 - f.length + below(8))}.test`],
['reserved', () => {
const w = pick(RESERVABLE)
return `${chance(0.3) ? mixCase(w) : w}.test`
}],
['handle taken', (f, acct) => mixCase(pick(accounts.filter((a) => a !== acct)).handle)],
]
/// updateHandle refused: one fault in its handle, sometimes with no token
/// or one never given out, which come first. Each side must refuse it as
/// the reference does, and post no operation (spec/IDENTITY.md,
/// "updateHandle").
export async function updateHandleRefused(acct) {
const [name, make] = pick(accounts.length > 1 ? FAULTS : FAULTS.filter(([n]) => n !== 'handle taken'))
const handle = make(freshFront(), acct)
const r = rand()
const token = r < 0.15 ? undefined : r < 0.3 ? 'never-given-out' : acct
const body = handle === undefined ? {} : { handle }
const kind = `updateHandle refused: ${name}${token === acct ? '' : token ? ', bad token' : ', no token'}`
const before = await logs(acct)
const [a] = await bothHttp(kind, UPDATE, { body, token })
if (a.status === 200) await differ(UPDATE, { fault: name, body }, 'refused', 'a change', 'both sides make a change the spec refuses')
const request = shown({ body, token })
for (const side of [ref, cand]) await checkNoOperation(side, acct, before[side.name], request)
}
/// Faults with a handle that would do: no token, or one never given out
/// (spec/IDENTITY.md, "updateHandle").
export async function updateHandleNoToken(acct) {
const body = { handle: `${freshFront()}.test` }
const token = chance(0.5) ? undefined : 'never-given-out'
const before = await logs(acct)
await bothHttp(`updateHandle with ${token ? 'a bad token' : 'no token'}`, UPDATE, { body, token })
for (const side of [ref, cand]) await checkNoOperation(side, acct, before[side.name], shown({ body, token }))
}
/// resolveHandle of the account's handle in mixed case, of handles under
/// the server's domains no account has, of external ones, and of ones the
/// lexicon refuses. Compared whole (spec/IDENTITY.md, "resolveHandle").
export async function resolveHandle(acct) {
const f = freshFront()
const r = rand()
let kind, handle
if (r < 0.35) [kind, handle] = ['resolveHandle', mixCase(acct.handle)]
else if (r < 0.45 && freed.length) [kind, handle] = ['resolveHandle of an old handle', pick(freed)]
else if (r < 0.65) [kind, handle] = ['resolveHandle, no such account', pick([`${f}.test`, `${f}.example`, `a.${f}.test`, 'ab.test', `${pick(RESERVABLE)}.test`, `x.${acct.handle}`])]
else if (r < 0.85) [kind, handle] = ['resolveHandle of an external handle', pick([external(f), `${f}.invalid`, mixCase(external(f))])]
else [kind, handle] = ['resolveHandle refused', pick([undefined, `${f}..test`, `-${f}.test`, f, `${f}.test.`, 'test'])]
await both(kind, RESOLVE, { params: { handle } })
}
/// GET /.well-known/atproto-did on `side` with `host` as its Host.
function wellKnown(side, host) {
const u = new URL(side.url)
const headers = { host }
const rec = side === cand ? begin('GET', `${side.url}/.well-known/atproto-did`, headers) : null
return new Promise((ok) => {
const req = http.request({ host: u.hostname, port: u.port, path: '/.well-known/atproto-did', headers }, (res) => {
let body = ''
res.setEncoding('utf8')
res.on('data', (c) => (body += c))
res.on('end', () => {
if (rec) end(rec, res.statusCode, body)
ok({ status: res.statusCode, type: res.headers['content-type'] ?? null, body })
})
})
req.on('error', (err) => {
if (rec) rec.ended = now()
ok({ status: 0, type: null, body: err.message })
})
req.end()
})
}
/// /.well-known/atproto-did with `host` on both sides: the status, and for
/// a 200 the content type and the body, with DIDs named alike.
async function wellKnownBoth(kind, host) {
const [a, b] = await Promise.all([ref, cand].map((side) => wellKnown(side, host)))
const shape = (side, r) => (r.status === 200 ? { status: 200, type: r.type, body: strip(side, r.body) } : { status: r.status })
const [na, nb] = [shape(ref, a), shape(cand, b)]
if (!isDeepStrictEqual(na, nb)) await differ('/.well-known/atproto-did', { host }, na, nb)
count(kind, a.status === 200)
}
/// /.well-known/atproto-did by the account's handle, with a port, in mixed
/// case, and by hosts that are no account's handle (spec/IDENTITY.md,
/// "/.well-known/atproto-did").
export async function wellKnownHandle(acct) {
const f = freshFront()
const r = rand()
if (r < 0.35) return wellKnownBoth('well-known', acct.handle)
if (r < 0.5) return wellKnownBoth('well-known with a port', `${acct.handle}:${1 + below(65535)}`)
if (r < 0.6) return wellKnownBoth('well-known in mixed case', acct.handle.toUpperCase())
if (r < 0.7 && freed.length) return wellKnownBoth('well-known of an old handle', pick(freed))
await wellKnownBoth('well-known, no such account', pick([`${f}.test`, `${f}.example`, external(f), 'localhost', '127.0.0.1', 'test', `${acct.handle}.`]))
}
/// getRecommendedDidCredentials with the account's token, none, or one
/// never given out (spec/IDENTITY.md, "getRecommendedDidCredentials"); on
/// each side, the keys and URL must be its own, and on Monolith the KEM key
/// its genesis operation has (spec/SPACES.md, "The KEM key"), which the
/// `latest` reference has not; on another implementation, the one its
/// genesis operation has, if it has one (spec/COMPAT.md).
export async function recommendedCredentials(acct) {
const r = rand()
const token = r < 0.7 ? acct : r < 0.85 ? undefined : 'never-given-out'
const [a, b] = await both('getRecommendedDidCredentials', CREDENTIALS, { token })
if (token !== acct) return
for (const [side, res] of [[ref, a], [cand, b]]) {
if (res.status !== 200) continue
const verificationMethods = { atproto: acct.sides[side.name].key }
if (side === cand && (own() || acct.sides[side.name].kem !== undefined)) verificationMethods.atproto_kem = acct.sides[side.name].kem
const want = {
alsoKnownAs: [`at://${acct.handle}`],
verificationMethods,
rotationKeys: [side.recoveryKey, side.rotationKey],
services: { atproto_pds: { type: 'AtprotoPersonalDataServer', endpoint: side.publicUrl } },
}
if (!isDeepStrictEqual(res.body, want)) await fail(side, 'getRecommendedDidCredentials', { token: `<token of did:${acct.n}>` }, want, res.body)
}
}
/// Two accounts changing to the same new handle at once, on each side: as
/// many changes land on each, at most one, and on the server the other is
/// refused as taken; each account's handle is then the one its DID
/// document names (spec/IDENTITY.md, "At once"). Which wins may differ
/// between the sides, so both accounts are then given new handles on both,
/// which makes events the other side has not: compare.mjs sends it only
/// without --firehose.
export async function handleRace(acct) {
const other = pick(accounts.filter((a) => a !== acct))
const pair = [acct, other]
const handle = `${freshFront()}.test`
const answers = await Promise.all([ref, cand].map((side) => Promise.all(pair.map((x) => xrpcHttp(side, UPDATE, { body: { handle }, token: x })))))
const request = { handle, accounts: pair.map((x) => `<did:${x.n}>`), sent: 'at once' }
const [won, ours] = answers.map((rs) => rs.map((r, i) => [r, i]).filter(([r]) => r.status === 200))
if (won.length > 1) await differ(UPDATE, request, 'one change at most', `${won.length} changes`, 'the reference fails the check it is held to')
if (ours.length > 1) await differ(UPDATE, request, 'one change at most', `${ours.length} changes`)
if (won.length !== ours.length) await differ(UPDATE, request, `${won.length} change(s)`, `${ours.length} change(s)`, 'the changes made differ')
count('updateHandle race', won.length === 1)
for (const [side, rs] of [[ref, answers[0]], [cand, answers[1]]]) {
const winner = rs.findIndex((r) => r.status === 200)
if (winner >= 0) gave(side, pair[winner], handle)
if (side === cand && winner >= 0) {
const loser = rs[1 - winner]
if (loser.status !== 400 || loser.body?.error !== 'HandleNotAvailable') await differ(UPDATE, request, 'the change that lost: 400 HandleNotAvailable', normalize(cand, loser, UPDATE))
}
if (side !== cand) continue
for (const [i, x] of pair.entries()) {
const s = await xrpcHttp(cand, 'com.atproto.server.getSession', { token: x })
const doc = await plcDocument(didOf(cand, x))
const named = (doc.body?.alsoKnownAs ?? []).find((u) => u.startsWith('at://'))
const has = i === winner ? handle : x.handle
if (s.body?.handle !== has || named !== `at://${has}`) await differ(UPDATE, request, { account: `<did:${x.n}>`, handle: has, document: `at://${has}` }, { handle: s.body?.handle, document: named ?? null }, 'after the race, each account\'s handle, and the one its DID document names')
}
const resolved = await xrpcHttp(cand, RESOLVE, { params: { handle } })
const want = winner >= 0 ? didOf(cand, pair[winner]) : undefined
if (resolved.body?.did !== want) await differ(RESOLVE, { handle }, want ?? 'HandleNotFound', normalize(cand, resolved, RESOLVE), 'the handle the race was for')
}
// Both accounts carry on with new handles of their own, on both sides.
for (const x of pair) {
const old = x.handle
await change(x, `${freshFront()}.test`, 'updateHandle after a race', { checkOld: false })
if (!freed.includes(old)) freed.push(old)
}
if (!freed.includes(handle)) freed.push(handle)
}
/// A handle change of the account on its way to the server when it is
/// killed (spec/IDENTITY.md, "Crashes"): once it serves again, either the
/// directory's log is as it was and the account keeps its handle, or the
/// log has the change's operation and the server takes the handle within 3
/// seconds. One that landed is then made on the reference too. Answers once
/// the request is on its way.
export async function inFlightHandle(acct) {
const handle = `${freshFront()}.test`
const body = { handle }
const before = (await plcLog(didOf(cand, acct))).body
return {
sent: xrpcHttp(cand, UPDATE, { body, token: acct }),
async settle() {
const request = shown({ body, token: acct })
const log = await plcLog(didOf(cand, acct))
const session = async () => (await xrpcHttp(cand, 'com.atproto.server.getSession', { token: acct })).body?.handle
if (isDeepStrictEqual(log.body, before)) {
const now = await session()
if (now !== acct.handle) await differ('a handle change the process was killed during', request, { handle: acct.handle, why: 'the directory never took its operation' }, { handle: now })
// The handle it would have had is no account's.
await both('resolveHandle of a handle change that did not land', RESOLVE, { params: { handle } })
return count('handle change in flight', false)
}
await checkOperation(cand, acct, before, handle, request)
const started = Date.now()
let now = await session()
while (now !== handle && Date.now() - started < 3000) {
await new Promise((ok) => setTimeout(ok, 20))
now = await session()
}
if (now !== handle) await differ('a handle change the process was killed during', request, { handle, why: 'the directory took its operation', within: '3s' }, { handle: now })
gave(cand, acct, handle)
const refBefore = (await plcLog(didOf(ref, acct))).body
const a = await xrpcHttp(ref, UPDATE, { body, token: acct })
if (a.status !== 200) await differ('a handle change the process was killed during', body, 'the change', a.body, 'the reference refuses it')
await checkOperation(ref, acct, refBefore, handle, request)
gave(ref, acct, handle)
await changed(acct, handle)
count('handle change in flight', true)
},
}
}