// The space repo (spec/SPACES-REPO.md), in the spaces run: the server as the // repo host of its accounts' space repos, beside the alpha's own PDS as the // reference's, both writing into spaces an authority on the alpha's second // PDS created. Each step goes to both sides and the answers are compared; // on each side, the reference's too, every commit's `data` must be the // LtHash of the records the harness wrote, CIDs it computes itself, every // MAC the one lib/spec.mjs checks, and the operation log must replay to // the commit. import { readFileSync } from 'node:fs' import { isDeepStrictEqual } from 'node:util' import { COMMIT_PROFILE, Link, LtHash, RECORD_PROFILE, cidBytes, cidFromString, cidString, encapsulate, encode, formatMacRequest, headerNamesCommit, headerNamesRecord, parseDictionary, parseMacRequest, serializeDictionary, verifyMac } from './lib/spec.mjs' const SP = 'com.atproto.space.' const COLLECTIONS = ['com.example.note', 'com.example.todo', 'com.example.test.item'] const PUBLISHED = ['com.atproto.space.policy', 'com.atproto.memberspace.member'] const RKEYS = ['a', 'b', 'c', 'ab', 'b1', 'x-y', 'z~z', 'self', 'a.b', 'k_9', 'Ab', 'q:r'] const BAD_RKEYS = ['.', '..', 'a/b', 'a b', '#x', 'x'.repeat(513)] const TYPES = ['com.example.group', 'com.example.chat', 'com.example.other'] const TID = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/ /// The covered header of each profile (spec/SPACES.md, "MACs"). const COVERED = { [COMMIT_PROFILE]: 'atproto-space-commit', [RECORD_PROFILE]: 'atproto-space-record' } /// The headers of a MAC, as an answer's presence of them is compared. const MAC_HEADERS = ['atproto-space-commit', 'atproto-space-record', 'signature-input', 'signature'] /// The keys whose values are revs, named by rank across the sides. const REV_KEYS = ['rev', 'repoRev', 'spaceRev'] /// Cursors with no `/`, which no list method answers (spec/SPACES-REPO.md, /// "Cursors"). const BAD_CURSORS = ['garbage', '3mzzzzzzzzzz2', 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa', 'bafyreihn37cccblw3mmwmmm6jewugcohecjf5kpzuciirdvisasq7k3siu'] /// The `Accept-Signature` cases of spec/interop/spaces/mac.json read for a /// commit, as templates for either profile: the profile, the other one and /// the key share taken out, to be put back for the method and the share of /// a request. Each is refused, asks for no MAC, or asks for one, as the /// vector says (spec/SPACES.md, "MACs"). const VECTOR_SHARE = 'did:key:zDnaezs81wvXFqkKzFv2nVGKB5FNTLvwnokhyyJgT7p7Zh2dU' const ASK_CASES = JSON.parse(readFileSync(new URL('../../spec/interop/spaces/mac.json', import.meta.url), 'utf8')).accept_signature .filter((c) => c.profile === COMMIT_PROFILE) .map((c) => ({ comment: c.comment, refused: c.refused, asks: !c.refused && c.request !== null, template: c.header.replaceAll(VECTOR_SHARE, '\0K').replaceAll(COMMIT_PROFILE, '\0P').replaceAll(RECORD_PROFILE, '\0O') })) /// The checks, given the run's processes, accounts, random source and /// reporting (compare.mjs). export function spaceRepo(h) { /// The steps and whole-repo reads another part adds (export.mjs). let ext = { steps: [], whole: async () => {} } const { ref, cand, accounts, rand } = h const below = (n) => Math.floor(rand() * n) const chance = (p) => rand() < p const pick = (xs) => xs[below(xs.length)] const sides = [ref, cand] const sd = (acct, side) => acct.sides[side.name] const didOf = (acct, side) => sd(acct, side).did const knownCids = [] /// The accounts the model follows: those of the run's end. Accounts other /// parts make later (sync.mjs) write where the model does not look. let modelled = accounts // ---- requests ------------------------------------------------------------------ /// `contentType` is sent with a body (JSON's by default; null for none); /// the answer keeps its bytes as `buf`. async function call(side, nsid, { params, body, raw, token, headers = {}, contentType = 'application/json' } = {}) { const url = new URL(`${side.url}/xrpc/${nsid}`) for (const [k, v] of Object.entries(params ?? {})) if (v !== undefined) url.searchParams.set(k, String(v)) const hd = { ...headers } if (token) hd.authorization = `Bearer ${token}` const data = raw ?? (body === undefined ? undefined : JSON.stringify(body)) if (data !== undefined && contentType !== null) hd['content-type'] = contentType const res = await fetch(url, { method: data === undefined ? 'GET' : 'POST', headers: hd, body: data }) const buf = Buffer.from(await res.arrayBuffer()) const text = buf.toString('utf8') let parsed = null const json = (res.headers.get('content-type') ?? '').startsWith('application/json') || res.status >= 400 if (json) { try { parsed = text ? JSON.parse(text) : null } catch { parsed = { unparsed: text.slice(0, 200) } } } return { status: res.status, body: parsed, buf, headers: res.headers } } /// The token of a kind for the account on a side. const tokenOf = (acct, side, kind = 'access') => ({ access: sd(acct, side).token, app: sd(acct, side).appToken, refresh: sd(acct, side).refresh, bad: 'not-a-token', none: undefined })[kind] /// What the harness shows of a request: the server's, DIDs named, long /// strings cut. function shown(kind, opts) { const cut = (v) => (Buffer.isBuffer(v) ? `<${v.length} bytes>` : typeof v === 'string' ? (v.length > 300 ? `${v.slice(0, 120)}…(${v.length} chars)` : v) : Array.isArray(v) ? (v.length > 20 ? [...v.slice(0, 20).map(cut), `…(${v.length} items)`] : v.map(cut)) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, cut(x)])) : v) const { token, ...rest } = opts return { step: kind, ...h.normalize(cand, { status: 200, body: cut(rest) }).body } } /// An answer with what differs between sides taken out (spec/PDS.md, and /// spec/SPACES-REPO.md): DIDs and record keys the side made named by their /// order, `rev`s by their rank in time within the answer, `data` (checked on each /// side), cursors; and which MAC headers it has. function norm(acct, side, res) { const extra = (acct ? sd(acct, side).tids : []).map((t, i) => [t, ``]) const n = h.normalize(side, { status: res.status, body: res.body }, extra) if (n.status >= 400) return n // Revs are named by their rank among the answer's revs (TIDs sort by // time), so the names do not depend on the order of an object's keys. const found = new Set() const collect = (v) => { if (Array.isArray(v)) return v.forEach(collect) if (!v || typeof v !== 'object') return for (const [k, x] of Object.entries(v)) if (REV_KEYS.includes(k) && typeof x === 'string') found.add(x); else collect(x) } collect(n.body) const revs = new Map([...found].sort().map((r, i) => [r, ``])) const walk = (v) => { if (Array.isArray(v)) return v.map(walk) if (!v || typeof v !== 'object') return v return Object.fromEntries(Object.entries(v).map(([k, x]) => { if (REV_KEYS.includes(k) && typeof x === 'string') return [k, revs.get(x)] if (k === 'data' && x && typeof x === 'object' && '$bytes' in x) return [k, ''] if (k === 'cursor' && typeof x === 'string') return [k, ''] return [k, walk(x)] })) } return { ...n, body: walk(n.body), mac: MAC_HEADERS.filter((k) => res.headers.has(k)) } } /// One request to both sides, compared. `learn(side, res)` reads what a /// side made (record keys) before the answers are normalized. async function both(kind, acct, nsid, mk, learn) { const [a, b] = await Promise.all(sides.map((side) => call(side, nsid, mk(side)))) if (learn) { learn(ref, a); learn(cand, b) } const [na, nb] = [norm(acct, ref, a), norm(acct, cand, b)] if (!isDeepStrictEqual(na, nb)) await h.differ(nsid, shown(kind, mk(cand)), na, nb) h.count(kind) return [a, b] } const fail = (side, what, request, want, got) => h.fail(side, what, request, want, got) // ---- the harness's own model of each repo ------------------------------------------- /// A record's JSON as a DRISL value: `$bytes` as bytes, `$link` as a link. function drisl(v) { if (Array.isArray(v)) return v.map(drisl) if (v && typeof v === 'object') { const keys = Object.keys(v) if (keys.length === 1 && keys[0] === '$bytes') return new Uint8Array(Buffer.from(v.$bytes, 'base64')) if (keys.length === 1 && keys[0] === '$link') return new Link(cidFromString(v.$link)) return Object.fromEntries(keys.map((k) => [k, drisl(v[k])])) } return v } const typed = (record, collection) => (record.$type === undefined ? { ...record, $type: collection } : record) const cidOf = (record, collection) => cidString(cidBytes(encode(drisl(typed(record, collection))))) /// The model of the account's repo in a space on a side. function repoOf(acct, side, sp) { const s = sd(acct, side) s.repos ??= new Map() if (!s.repos.has(sp.id)) s.repos.set(sp.id, { records: new Map(), base: new Map(), rev: null, revs: [], exists: false }) return s.repos.get(sp.id) } function digestOf(m) { const lt = new LtHash() for (const [path, { cid }] of m.records) lt.add(`${path}/${cid}`) return lt.digest() } const byBytes = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)) const commitOf = (c) => ({ ...c, data: Buffer.from(c.data.$bytes, 'base64') }) // ---- spaces --------------------------------------------------------------------------- let spaces = [] let sizesSpace const own = { id: 'own', uri: (acct, side) => `at://${didOf(acct, side)}/space/com.example.group/own`, authority: (acct, side) => didOf(acct, side), type: 'com.example.group' } const fixed = (uri) => ({ id: uri, uri: () => uri, authority: () => uri.split('/')[2], type: uri.split('/')[4] }) // Space URIs that are no `space-ref`, the last an skey of 513 bytes // (spec/SPACES.md, "Addressing"). const MALFORMED = [ 'at://did:web:example.com/space/com.example.group', 'at://did:web:example.com/space/com.example.group/k/', 'at://handle.test/space/com.example.group/k', 'at://did:web:example.com/spaces/com.example.group/k', 'at://did:web:example.com/space/notnsid/k', 'at://did:web:example.com/space/com.example.group/..', `at://did:web:example.com/space/com.example.group/${'k'.repeat(513)}`, ] /// Authorities on the alpha's second PDS, each with spaces made by the /// alpha's createSpace, and spaces of authorities no PDS has, whose writes /// are taken unasked (spec/SPACES-REPO.md, "The space"), one with an skey /// of 512 bytes, the longest (spec/SPACES.md, "Addressing"). async function setup() { const host = h.net.extraPdses[0] const made = [] for (let i = 0; i < 2; i++) { const f = h.front() const acc = await call(host, 'com.atproto.server.createAccount', { body: { handle: `${f}.test2`, email: `${f}@example.com`, password: `pw-${f}` } }) if (acc.status !== 200) await h.differ('createAccount of an authority on the alpha space host', { handle: `${f}.test2` }, 'an account', acc.body, 'the harness cannot set up its spaces') for (const [type, skey] of i === 0 ? [['com.example.group', h.front()], ['com.example.chat', h.front()], ['com.example.group', 'sizes']] : [['com.example.group', h.front()]]) { const res = await call(host, `${SP}createSpace`, { token: acc.body.accessJwt, body: { spaceType: type, skey, policy: { $type: 'com.atproto.memberspace.policy', publicRead: true } } }) if (res.status !== 200) await h.differ('createSpace on the alpha space host', { type, skey }, 'a space', res.body, 'the harness cannot set up its spaces') made.push(res.body.space) } } sizesSpace = fixed(made.pop()) let plc = 'did:plc:' for (let i = 0; i < 24; i++) plc += 'abcdefghijklmnopqrstuvwxyz234567'[below(32)] spaces = [...made.map(fixed), fixed(`at://${plc}/space/com.example.group/u1`), fixed('at://did:web:example.com/space/com.example.chat/u2'), fixed(`at://did:web:example.com/space/com.example.group/${'k'.repeat(512)}`)] for (const acct of accounts) { for (const side of sides) { const s = sd(acct, side) s.tids = [] const pw = await call(side, 'com.atproto.server.createAppPassword', { token: s.token, body: { name: 'spaces' } }) const sess = await call(side, 'com.atproto.server.createSession', { body: { identifier: s.did, password: pw.body?.password } }) if (sess.status !== 200) await fail(side, 'app password session', { name: 'spaces' }, 'a session', sess.body) s.appToken = sess.body.accessJwt s.publicCommit = (await call(side, 'com.atproto.sync.getLatestCommit', { params: { did: s.did } })).body } } } /// A space for a step: mostly one of the authorities', sometimes the /// caller's own (never created), rarely a malformed one /// (spec/SPACES-REPO.md, "The space"). function pickSpace({ malformed = 0.03, ownP = 0.05 } = {}) { const r = rand() if (r < malformed) { const uri = pick(MALFORMED); return { id: 'malformed', uri: () => uri, malformed: true } } if (r < malformed + ownP) return own return pick(spaces) } const spaceUri = (sp, acct, side) => sp.uri(acct, side) // ---- records ------------------------------------------------------------------------ const word = () => pick(['hi', 'héllo', 'note', '', 'a longer string with spaces', '日本語', '🙂']) function value(depth = 0) { const r = below(depth > 1 ? 4 : 7) if (r === 0) return word() if (r === 1) return below(2000) - 1000 if (r === 2) return chance(0.5) if (r === 3) return null if (r === 4) return Array.from({ length: below(4) }, () => value(depth + 1)) if (r === 5) return { $bytes: pick(['aGVsbG8', 'AAEC/w', 'AQ']) } return Object.fromEntries(Array.from({ length: below(4) }, () => [pick(['k', 'title', 'n', 'zz', 'a1']), value(depth + 1)])) } /// A record for `collection`, usually good, sometimes not /// (spec/SPACES-REPO.md, "Records"). function record(collection) { const rec = { $type: collection, text: word(), n: below(100) } if (chance(0.3)) rec.extra = value() if (chance(0.15) && knownCids.length) rec.ref = { $link: pick(knownCids) } const r = rand() if (r < 0.04) delete rec.$type else if (r < 0.07) rec.$type = pick(COLLECTIONS.filter((c) => c !== collection)) else if (r < 0.1) rec.ratio = 1.5 return rec } const goodRecord = (collection) => ({ $type: collection, text: word(), n: below(100), ...(chance(0.3) ? { extra: value() } : {}) }) /// A record key and a collection, rarely a bad key or a published /// collection (spec/SPACES-REPO.md, "Records"). const rkey = () => (chance(0.04) ? pick(BAD_RKEYS) : pick(RKEYS)) const collection = () => (chance(0.04) ? pick(PUBLISHED) : pick(COLLECTIONS)) /// The `repo` of a step: the caller's, or rarely another account's or a /// DID no account has (spec/SPACES-REPO.md, "Who may call"). const repoFor = (acct, kind) => (side) => { if (kind === 'self') return didOf(acct, side) const other = accounts.find((a) => a !== acct) return other && kind === 'other' ? didOf(other, side) : 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa' } const repoKind = () => (chance(0.04) ? pick(['other', 'unknown']) : 'self') const validateFlag = () => (chance(0.1) ? chance(0.5) : undefined) const lastSegment = (uri) => uri?.split('/').at(-1) /// A record key as a side names it: a key the reference made (a TID) is /// the one the server made at the same place, and any other is itself. const keyOn = (acct, side, key) => { const i = sd(acct, ref).tids.indexOf(key); return i === -1 ? key : sd(acct, side).tids[i] } // ---- checks on each side --------------------------------------------------------------- function hasToken(header, name) { return (header ?? '').split(',').map((s) => s.trim().toLowerCase()).includes(name.toLowerCase()) } /// An `Accept-Signature` for a read answering `profile`, drawn: none, one /// as a syncer formats it (a label of its own, `alg` or not), or one of the /// vectors' cases, refused, asking for no MAC, or asking for one /// (spec/SPACES.md, "MACs"; spec/SPACES-REPO.md, "MACs on request"). function macAsk(profile, { none = 0.35, good = 0.4 } = {}) { const r = rand() if (r < none) return { name: 'none', asks: false, refused: false, profile, header: () => undefined } if (r < none + good) { const label = pick(['mac', 'sig', 'm1', 'anything']) const alg = chance(0.3) return { name: 'good', asks: true, refused: false, profile, header: (share) => formatMacRequest(profile, share.keyShare, { label, alg }) } } const c = pick(ASK_CASES) const other = profile === COMMIT_PROFILE ? RECORD_PROFILE : COMMIT_PROFILE return { name: c.comment, asks: c.asks, refused: c.refused, profile, header: (share) => c.template.replaceAll('\0K', share.keyShare).replaceAll('\0P', profile).replaceAll('\0O', other) } } /// The request headers of a drawn `Accept-Signature`, for a key share. const askHeaders = (w, share) => { const v = w.header(share); return v === undefined ? {} : { 'accept-signature': v } } /// What a step's name says of its `Accept-Signature`. const askName = (w) => (w.name === 'none' ? '' : ` (Accept-Signature: ${w.name})`) /// The headers of a `200` of a method that answers a MAC: `Vary` naming /// `Accept-Signature` always; with a MAC asked for, the profile's covered /// header, `Signature-Input` with the request's label and Inner List, and /// `Signature`, which lib/spec.mjs must verify with the harness's key /// share, the covered header naming what the answer holds (`names`), and /// `Access-Control-Expose-Headers` naming the three; with none asked for, /// none of them (spec/SPACES-REPO.md, "MACs on request"; spec/SPACES.md, /// "MACs"). async function checkMacHeaders(side, res, request, w, share, names) { if (!hasToken(res.headers.get('vary'), 'accept-signature')) await fail(side, 'Vary', request, 'naming Accept-Signature', res.headers.get('vary')) const present = MAC_HEADERS.filter((k) => res.headers.has(k)) const got = Object.fromEntries(present.map((k) => [k, res.headers.get(k)])) if (!w.asks) { if (present.length) await fail(side, 'MAC headers, with none asked for', request, 'none', got) return } const covered = COVERED[w.profile] if (present.length !== 3 || !present.includes(covered)) await fail(side, 'MAC headers', request, `${covered}, signature-input and signature`, got) let dict try { dict = verifyMac(w.profile, Object.fromEntries(res.headers), share) } catch (e) { await fail(side, 'the MAC, checked by lib/spec.mjs with the harness\'s key share', request, 'a MAC that checks', { why: e.message, ...got }); return } if (!names(dict)) await fail(side, `${covered}: what it names, against the answer`, request, 'the answer\'s commit or record', got[covered]) const asked = parseMacRequest(w.header(share), w.profile) let input = null try { input = serializeDictionary(parseDictionary(got['signature-input'])) } catch {} if (input !== `${asked.label}=${asked.signatureParams}`) await fail(side, 'Signature-Input, against the request', request, `${asked.label}=${asked.signatureParams}`, got['signature-input']) const expose = res.headers.get('access-control-expose-headers') if (![covered, 'signature-input', 'signature'].every((k) => hasToken(expose, k))) await fail(side, 'Access-Control-Expose-Headers', request, `naming ${covered}, Signature-Input and Signature`, expose) } /// A read whose `Accept-Signature` is refused, or one with a credential /// that asks for no MAC where one is needed, is `400 InvalidSpaceMac` on /// each side, whether or not the repo or record is there /// (spec/SPACES-REPO.md, "MACs on request"; spec/SPACES-EXPORT.md, "Who /// may read"). async function holdInvalidMac(a, b, request, what) { for (const [side, res] of [[ref, a], [cand, b]]) if (res.status !== 400 || res.body?.error !== 'InvalidSpaceMac') await fail(side, `${what}: its Accept-Signature`, request, { status: 400, error: 'InvalidSpaceMac' }, { status: res.status, error: res.body?.error ?? null }) } /// A commit answered on `side` must be the model's: its repo and space, a /// TID `rev`, `data` the LtHash of the model's records /// (spec/SPACES-REPO.md, "A space repo"). async function checkCommit(side, acct, sp, c, request, what) { const m = repoOf(acct, side, sp) const want = { ver: 1, repo: didOf(acct, side), space: spaceUri(sp, acct, side), rev: TID.test(c?.rev ?? '') ? c.rev : '', data: { $bytes: digestOf(m).toString('base64').replace(/=+$/, '') } } const got = c && { ...c, data: c.data?.$bytes !== undefined ? { $bytes: c.data.$bytes.replace(/=+$/, '') } : c.data } if (!isDeepStrictEqual(got, want)) await fail(side, `${what}: the commit, against the records the harness wrote`, request, want, c ?? null) } /// The repo's commit on both sides, which must follow from the last /// write: a new `rev` when it made a commit, the same one when not, and /// no repo where no write made one (spec/SPACES-REPO.md, "A space repo", /// "Each write", "Each read"). async function latestCommit(acct, sp, expect, kind = 'getLatestCommit', tokenKind = 'access', w = macAsk(COMMIT_PROFILE, { none: 0.5, good: 0.5 })) { const shares = {} const shareOf = (side) => (shares[side.name] ??= encapsulate(sd(acct, side).kem)) const mk = (side) => ({ token: tokenOf(acct, side, tokenKind), params: { space: spaceUri(sp, acct, side), repo: didOf(acct, side) }, headers: askHeaders(w, shareOf(side)) }) const [a, b] = await both(`${kind}${askName(w)}`, acct, `${SP}getLatestCommit`, mk) const request = shown(kind, mk(cand)) if (w.refused && tokenKind === 'access' && !sp.malformed) return holdInvalidMac(a, b, request, kind) if (a.status !== 200 && a.body?.error !== 'RepoNotFound') return for (const [side, res] of [[ref, a], [cand, b]]) { const m = repoOf(acct, side, sp) if (!m.exists) { if (res.status !== 400 || res.body?.error !== 'RepoNotFound') await fail(side, `${kind} of a repo never written`, request, { status: 400, error: 'RepoNotFound' }, res.body) continue } if (res.status !== 200) { await fail(side, kind, request, 'the commit', res.body); continue } const c = res.body.commit await checkCommit(side, acct, sp, c, request, kind) if (expect === 'commit' && m.rev !== null && !(c.rev > m.rev)) await fail(side, `${kind}: rev after a write that makes a commit`, request, `a rev later than ${m.rev}`, c.rev) if (expect === 'none' && c.rev !== m.rev) await fail(side, `${kind}: rev after a write that makes no commit`, request, m.rev, c.rev) if (c.rev !== m.rev) { m.rev = c.rev; m.revs.push(c.rev) } await checkMacHeaders(side, res, request, w, shareOf(side), (d) => headerNamesCommit(d, commitOf(c))) } } // ---- writes ---------------------------------------------------------------------------------- /// After a write both sides answered alike: the model takes it (`apply` /// answers whether it made a commit), and the commit is read /// (spec/SPACES-REPO.md, "Each write"). async function after(kind, acct, sp, a, b, apply) { if (sp.malformed) return if (a.status !== 200) { if (chance(0.3)) await latestCommit(acct, sp, 'none', `getLatestCommit after a refused ${kind}`) return } let made = false for (const [side, res] of [[ref, a], [cand, b]]) made = await apply(side, res) await latestCommit(acct, sp, made ? 'commit' : 'none', `getLatestCommit after ${kind}`) } /// A record written on `side`: its CID must be the harness's, of the /// record with `$type` its collection where it had none /// (spec/SPACES-REPO.md, "A space repo"). async function put(side, acct, sp, coll, key, rec, cid, request, what) { const want = cidOf(rec, coll) if (cid !== want) await fail(side, `${what}: the record's CID`, request, want, cid) const m = repoOf(acct, side, sp) m.records.set(`${coll}/${key}`, { cid: want, value: typed(rec, coll) }) m.exists = true if (side === ref && !knownCids.includes(want)) knownCids.push(want) } async function createRecord(acct, tokenKind = 'access') { const sp = pickSpace() const coll = collection() const key = chance(0.12) ? undefined : rkey() const rec = record(coll) const rk = repoKind() const validate = validateFlag() const mk = (side) => ({ token: tokenOf(acct, side, tokenKind), body: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), collection: coll, ...(key === undefined ? {} : { rkey: key }), record: rec, ...(validate === undefined ? {} : { validate }) } }) const learn = (side, res) => { if (key === undefined && res.status === 200) sd(acct, side).tids.push(lastSegment(res.body?.uri)) } const [a, b] = await both(`createRecord${tokenKind === 'access' ? '' : ` (${tokenKind} token)`}`, acct, `${SP}createRecord`, mk, learn) await after('createRecord', acct, sp, a, b, async (side, res) => { const k = key ?? lastSegment(res.body.uri) if (key === undefined && !TID.test(k)) await fail(side, 'createRecord without rkey', shown('createRecord', mk(side)), 'a TID record key', k) await put(side, acct, sp, coll, k, rec, res.body.cid, shown('createRecord', mk(cand)), 'createRecord') return true }) } async function putRecord(acct) { const sp = pickSpace() const coll = collection() const key = rkey() const m = repoOf(acct, ref, sp.malformed ? spaces[0] : sp) const last = m.records.get(`${coll}/${key}`)?.value const rec = last && chance(0.3) ? last : record(coll) const rk = repoKind() const validate = validateFlag() const mk = (side) => ({ token: tokenOf(acct, side), body: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), collection: coll, rkey: key, record: rec, ...(validate === undefined ? {} : { validate }) } }) const [a, b] = await both('putRecord', acct, `${SP}putRecord`, mk) await after('putRecord', acct, sp, a, b, async (side, res) => { await put(side, acct, sp, coll, key, rec, res.body.cid, shown('putRecord', mk(cand)), 'putRecord') return true }) } async function deleteRecord(acct) { const sp = pickSpace() const coll = collection() const existing = sp.malformed ? [] : [...repoOf(acct, ref, sp).records.keys()].filter((p) => p.startsWith(`${coll}/`)) const key = existing.length && chance(0.6) ? pick(existing).slice(coll.length + 1) : rkey() const rk = repoKind() const mk = (side) => ({ token: tokenOf(acct, side), body: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), collection: coll, rkey: keyOn(acct, side, key) } }) const [a, b] = await both('deleteRecord', acct, `${SP}deleteRecord`, mk) await after('deleteRecord', acct, sp, a, b, async (side) => repoOf(acct, side, sp).records.delete(`${coll}/${keyOn(acct, side, key)}`)) } /// A batch every write of which should succeed, against the model. function goodBatch(acct, sp) { const records = new Set(repoOf(acct, ref, sp).records.keys()) const writes = [] for (let i = 0; i < 1 + below(5); i++) { const coll = pick(COLLECTIONS) const kind = chance(0.15) ? 'create-tid' : pick(['create', 'update', 'delete']) if (kind === 'create-tid') { writes.push({ $type: `${SP}applyWrites#create`, collection: coll, value: goodRecord(coll) }); continue } const there = RKEYS.filter((k) => records.has(`${coll}/${k}`)) const free = RKEYS.filter((k) => !records.has(`${coll}/${k}`)) if (kind === 'create' || !there.length) { if (!free.length) continue const k = pick(free) records.add(`${coll}/${k}`) writes.push({ $type: `${SP}applyWrites#create`, collection: coll, rkey: k, value: goodRecord(coll) }) } else { const k = pick(there) if (kind === 'delete') records.delete(`${coll}/${k}`) writes.push({ $type: `${SP}applyWrites#${kind}`, collection: coll, rkey: k, ...(kind === 'update' ? { value: goodRecord(coll) } : {}) }) } } return writes } function anyWrite() { const coll = collection() const kind = pick(['create', 'update', 'delete']) const w = { $type: chance(0.03) ? `com.atproto.repo.applyWrites#${kind}` : `${SP}applyWrites#${kind}`, collection: coll } if (kind !== 'create' || chance(0.8)) w.rkey = rkey() if (kind !== 'delete') w.value = record(coll) return w } /// A batch: of any writes, of good ones, empty, or of 201 /// (spec/SPACES-REPO.md, "Writes", "The order of the checks", "Each /// write"). async function applyWrites(acct) { const sp = pickSpace() const r = rand() const writes = r < 0.03 ? [] : r < 0.05 ? Array.from({ length: 201 }, (_, i) => ({ $type: `${SP}applyWrites#create`, collection: 'com.example.todo', rkey: `m${i}`, value: { n: i } })) : sp.malformed || r < 0.6 ? Array.from({ length: 1 + below(5) }, anyWrite) : goodBatch(acct, sp) const rk = repoKind() const validate = validateFlag() const mk = (side) => ({ token: tokenOf(acct, side), body: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), writes, ...(validate === undefined ? {} : { validate }) } }) const learn = (side, res) => { if (res.status !== 200) return writes.forEach((w, i) => { if (w.$type.endsWith('#create') && w.rkey === undefined) sd(acct, side).tids.push(lastSegment(res.body?.results?.[i]?.uri)) }) } const [a, b] = await both('applyWrites', acct, `${SP}applyWrites`, mk, learn) await after('applyWrites', acct, sp, a, b, async (side, res) => { const m = repoOf(acct, side, sp) for (const [i, w] of writes.entries()) { const result = res.body.results?.[i] if (w.$type.endsWith('#delete')) { m.records.delete(`${w.collection}/${w.rkey}`); continue } const k = w.rkey ?? lastSegment(result?.uri) await put(side, acct, sp, w.collection, k, w.value, result?.cid, shown('applyWrites', mk(cand)), `applyWrites, write ${i}`) } if (writes.length) m.exists = true return writes.length > 0 }) } async function clearRecords(acct, sp = pickSpace({ malformed: 0.02, ownP: 0.05 })) { const rk = repoKind() const mk = (side) => ({ token: tokenOf(acct, side), body: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side) } }) const [a, b] = await both('clearRecords', acct, `${SP}clearRecords`, mk) await after('clearRecords', acct, sp, a, b, async (side) => { const m = repoOf(acct, side, sp) const had = m.records.size > 0 m.records.clear() if (had) m.base = new Map() return had }) } // ---- reads ----------------------------------------------------------------------------------- /// getRecord, against the model, its `uri` the record's /// (spec/SPACES.md, "Addressing"; spec/SPACES-REPO.md, "A space repo", /// "MACs on request"). async function getRecord(acct) { const sp = pickSpace({ malformed: 0.02, ownP: 0.03 }) const existing = sp.malformed ? [] : [...repoOf(acct, ref, sp).records.keys()] const path = existing.length && chance(0.7) ? pick(existing) : `${pick(COLLECTIONS)}/${rkey()}` const [coll, key] = [path.slice(0, path.indexOf('/')), path.slice(path.indexOf('/') + 1)] const w = macAsk(RECORD_PROFILE) const rk = chance(0.05) ? 'other' : 'self' const shares = {} const shareOf = (side) => (shares[side.name] ??= encapsulate(sd(acct, side).kem)) const mk = (side) => ({ token: tokenOf(acct, side), params: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), collection: coll, rkey: keyOn(acct, side, key) }, headers: askHeaders(w, shareOf(side)) }) const [a, b] = await both(`getRecord${askName(w)}`, acct, `${SP}getRecord`, mk) const request = shown('getRecord', mk(cand)) if (w.refused && rk === 'self' && !sp.malformed && !BAD_RKEYS.includes(key)) return holdInvalidMac(a, b, request, 'getRecord') if (a.status !== 200) return for (const [side, res] of [[ref, a], [cand, b]]) { const sidePath = `${coll}/${keyOn(acct, side, key)}` const m = repoOf(acct, side, sp).records.get(sidePath) const uri = `${spaceUri(sp, acct, side)}/${didOf(acct, side)}/${sidePath}` const want = { uri, cid: m?.cid, value: m?.value } if (!isDeepStrictEqual(res.body, want)) await fail(side, 'getRecord, against the record the harness wrote', request, want, res.body) await checkMacHeaders(side, res, request, w, shareOf(side), (d) => headerNamesRecord(d, uri, m?.cid)) } } /// Page through a list method on both sides, each with its own cursors; /// answers each side's items in order, or null if it was refused, after /// `onRefused(a, b)` (spec/SPACES-REPO.md, "Reads", "Each read"). async function pages(kind, acct, nsid, mk, items, limit, onPage, onRefused) { const cursors = {} const got = { reference: [], server: [] } for (let page = 0; ; page++) { const [a, b] = await both(kind, acct, nsid, (side) => mk(side, cursors[side.name])) if (a.status !== 200) { await onRefused?.(a, b, shown(kind, mk(cand, cursors.server))); return null } for (const [side, res] of [[ref, a], [cand, b]]) { const its = items(res.body) ?? [] got[side.name].push(...its) await onPage?.(side, res, its, shown(kind, mk(side, cursors[side.name]))) cursors[side.name] = res.body.cursor } if (!a.body.cursor) return got if (page > 2000) await h.differ(nsid, shown(kind, mk(cand)), 'an end to the pages', 'more than 2000 pages') } } /// listRecords, every page, against the model: always in descending /// order, a `reverse` sent ignored (spec/SPACES-REPO.md, "Each read"). async function listRecords(acct) { const sp = pickSpace({ malformed: 0.02, ownP: 0.03 }) const coll = chance(0.3) ? pick(COLLECTIONS) : undefined const limit = chance(0.6) ? 1 + below(6) : undefined const reverse = chance(0.3) ? pick([true, false, 'maybe']) : undefined const excludeValues = chance(0.3) ? chance(0.7) : undefined const rk = chance(0.05) ? 'other' : 'self' const mk = (side, cursor) => ({ token: tokenOf(acct, side), params: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), collection: coll, limit, reverse, excludeValues, cursor } }) const uriOf = (side, r) => `${spaceUri(sp, acct, side)}/${repoFor(acct, rk)(side)}/${r.collection}/${r.rkey}` const onPage = async (side, res, its, request) => { if (Boolean(res.body.cursor) !== (its.length === (limit ?? 50))) await fail(side, 'listRecords cursor', request, its.length === (limit ?? 50) ? 'a cursor, as the page is full' : 'no cursor, as the page is not full', res.body.cursor ?? null) // A cursor is the URI of the page's last record, as getRecord answers it. if (res.body.cursor && its.length && res.body.cursor !== uriOf(side, its.at(-1))) await fail(side, 'listRecords cursor, the URI of the page\'s last record (spec/SPACES-REPO.md, "Each read")', request, uriOf(side, its.at(-1)), res.body.cursor) } const got = await pages(`listRecords${reverse === undefined ? '' : ' (reverse sent)'}`, acct, `${SP}listRecords`, mk, (b) => b.records, limit, onPage) if (!got) return const shape = ([p, r]) => ({ collection: p.slice(0, p.indexOf('/')), rkey: p.slice(p.indexOf('/') + 1), cid: r.cid, ...(excludeValues ? {} : { value: r.value }) }) for (const side of sides) { const m = repoOf(acct, side, sp) const want = [...m.records].filter(([p]) => !coll || p.startsWith(`${coll}/`)).sort(([x], [y]) => byBytes(y, x)).map(shape) if (!isDeepStrictEqual(got[side.name], want)) await fail(side, 'listRecords, every page, against the records the harness wrote', shown('listRecords', mk(side)), want, got[side.name]) } // A cursor a client builds for a key, a record URI whose record need not // exist, starts the page below it (spec/SPACES-REPO.md, "Each read"): the // path of a record written, with `~` after it, which sorts above it and // below the next. const own = !sp.malformed && rk === 'self' && repoOf(acct, ref, sp).records.size if (!own) return const paths = [...repoOf(acct, ref, sp).records.keys()].filter((p) => !coll || p.startsWith(`${coll}/`)) if (!paths.length) return const at = pick(paths) const built = (side) => `${spaceUri(sp, acct, side)}/${repoFor(acct, rk)(side)}/${at}~` const [a, b] = await both('listRecords from a built cursor', acct, `${SP}listRecords`, (side) => mk(side, built(side))) for (const [side, res] of [[ref, a], [cand, b]]) { const m = repoOf(acct, side, sp) const want = [...m.records].filter(([p]) => (!coll || p.startsWith(`${coll}/`)) && byBytes(p, `${at}~`) < 0).sort(([x], [y]) => byBytes(y, x)).slice(0, limit ?? 50).map(shape) if (res.status !== 200 || !isDeepStrictEqual(res.body.records, want)) await fail(side, 'listRecords from a cursor built for a key, the page below it (spec/SPACES-REPO.md, "Each read")', shown('listRecords', mk(side, built(side))), want, res.status === 200 ? res.body.records : res.body) } } /// listRepoOps, every page with the repo's commit and its MAC, and a /// cursor when full; a repo never written `RepoNotFound` /// (spec/SPACES-REPO.md, "Each read", "MACs on request"). Read `whole`, /// from the start, it asks for a MAC or none. async function listRepoOps(acct, sp = pickSpace({ malformed: 0.02, ownP: 0.03 }), whole = false) { const limit = !whole && chance(0.6) ? 1 + below(8) : undefined const sinceAt = !whole && chance(0.3) && !sp.malformed && repoOf(acct, ref, sp).revs.length ? below(repoOf(acct, ref, sp).revs.length) : undefined const excludeValues = chance(0.3) ? chance(0.7) : undefined const w = whole ? macAsk(COMMIT_PROFILE, { none: 0.5, good: 0.5 }) : macAsk(COMMIT_PROFILE) const rk = !whole && chance(0.05) ? 'other' : 'self' const shares = {} const shareOf = (side) => (shares[side.name] ??= encapsulate(sd(acct, side).kem)) const mk = (side, cursor) => { const since = sinceAt === undefined ? undefined : repoOf(acct, side, sp).revs[sinceAt] return { token: tokenOf(acct, side), params: { space: spaceUri(sp, acct, side), repo: repoFor(acct, rk)(side), since, limit, excludeValues, cursor }, headers: askHeaders(w, shareOf(side)) } } const onPage = async (side, res, ops, request) => { const m = repoOf(acct, side, sp) const full = ops.length === (limit ?? 100) const c = res.body.commit if (!c || Boolean(res.body.cursor) !== full) await fail(side, 'listRepoOps page', request, full ? 'the commit and a cursor, as the page is full' : 'the commit and no cursor', { cursor: res.body.cursor ?? null, commit: c ?? null }) if (!m.exists) await fail(side, 'listRepoOps of a repo never written', request, { status: 400, error: 'RepoNotFound' }, res.body) if (c) { await checkCommit(side, acct, sp, c, request, 'listRepoOps') if (c.rev !== m.rev) await fail(side, 'listRepoOps commit', request, m.rev, c.rev) } await checkMacHeaders(side, res, request, w, shareOf(side), (d) => Boolean(c) && headerNamesCommit(d, commitOf(c))) } const onRefused = async (a, b, request) => { if (rk !== 'self' || sp.malformed) return if (w.refused) return holdInvalidMac(a, b, request, 'listRepoOps') for (const [side, res] of [[ref, a], [cand, b]]) if (!repoOf(acct, side, sp).exists && (res.status !== 400 || res.body?.error !== 'RepoNotFound')) await fail(side, 'listRepoOps of a repo never written', request, { status: 400, error: 'RepoNotFound' }, { status: res.status, error: res.body?.error ?? null }) } const got = await pages(`listRepoOps${askName(w)}`, acct, `${SP}listRepoOps`, mk, (b) => b.ops, limit, onPage, onRefused) if (!got) return for (const side of sides) { const m = repoOf(acct, side, sp) const request = shown('listRepoOps', mk(side)) const ops = got[side.name] const since = sinceAt === undefined ? undefined : m.revs[sinceAt] let last = '' for (const op of ops) { if (!TID.test(op.rev) || op.rev < last || (since && !(op.rev > since)) || (m.rev && op.rev > m.rev)) await fail(side, 'listRepoOps, the revs of the operations', request, `TIDs in order, after ${since ?? 'the start'}, none after the commit's`, ops.map((o) => o.rev)) last = op.rev const now = m.records.get(`${op.collection}/${op.rkey}`) const wantValue = !excludeValues && op.cid !== null && now?.cid === op.cid ? now.value : undefined if (!isDeepStrictEqual(op.value, wantValue)) await fail(side, 'listRepoOps, an operation\'s value', request, wantValue ?? 'none: excludeValues, a delete, or a record changed since', op) } if (since === undefined && m.exists) { // The log starts at the repo's last clearRecords or importRepo, whose // records it starts from (spec/SPACES-REPO.md, "A space repo"). const lt = new LtHash() for (const [path, { cid }] of m.base) lt.add(`${path}/${cid}`) for (const op of ops) { if (op.prev) lt.remove(`${op.collection}/${op.rkey}/${op.prev}`); if (op.cid) lt.add(`${op.collection}/${op.rkey}/${op.cid}`) } if (!lt.digest().equals(digestOf(m))) await fail(side, 'listRepoOps from the start, replayed from its start', request, digestOf(m).toString('base64'), lt.digest().toString('base64')) } } } /// listSpaces, every page, against the repos written: each `{space, /// repoRev, data}`, the repo's commit's, with `spaceDid` only those of /// that authority; a `did` sent is ignored (spec/SPACES-REPO.md, "Each /// read"). async function listSpaces(acct, tokenKind = 'access') { const spaceType = chance(0.3) ? pick(TYPES) : undefined const didKind = chance(0.3) ? pick(['authority', 'unknown', 'own']) : undefined const authority = didKind === 'authority' ? pick(spaces).authority() : didKind === 'unknown' ? 'did:web:example.com' : undefined const ignored = chance(0.1) ? 'did:web:example.com' : undefined const limit = chance(0.5) ? 1 + below(4) : undefined const mk = (side, cursor) => ({ token: tokenOf(acct, side, tokenKind), params: { spaceType, spaceDid: didKind === 'own' ? didOf(acct, side) : authority, did: ignored, limit, cursor } }) const onPage = async (side, res, its, request) => { if (Boolean(res.body.cursor) !== (its.length === (limit ?? 50))) await fail(side, 'listSpaces cursor', request, its.length === (limit ?? 50) ? 'a cursor' : 'no cursor', res.body.cursor ?? null) } const got = await pages(`listSpaces${tokenKind === 'access' ? '' : ` (${tokenKind} token)`}`, acct, `${SP}listSpaces`, mk, (b) => b.spaces, limit, onPage) if (!got) return const unpad = (v) => (v && typeof v === 'object' && typeof v.$bytes === 'string' ? { $bytes: v.$bytes.replace(/=+$/, '') } : v) for (const side of sides) { const did = didKind === 'own' ? didOf(acct, side) : authority const want = [...spaces, own, sizesSpace].filter((sp) => repoOf(acct, side, sp).exists) .filter((sp) => (!spaceType || sp.type === spaceType) && (!did || sp.authority(acct, side) === did)) .map((sp) => ({ space: sp.uri(acct, side), repoRev: repoOf(acct, side, sp).rev, data: { $bytes: digestOf(repoOf(acct, side, sp)).toString('base64').replace(/=+$/, '') } })) .sort((x, y) => byBytes(x.space, y.space)) const answered = got[side.name].map((s) => (s && typeof s === 'object' ? { ...s, data: unpad(s.data) } : s)) if (!isDeepStrictEqual(answered, want)) await fail(side, 'listSpaces, every page, against the repos written', shown('listSpaces', mk(side)), want, got[side.name]) } } /// A cursor with no `/`, which no list method answers, is `400 /// InvalidCursor` on each side, whether or not the repo is there /// (spec/SPACES-REPO.md, "Cursors"). async function badCursor(acct) { const sp = pick([...spaces, own]) const cursor = pick(BAD_CURSORS) const nsid = pick(['listRecords', 'listRepoOps', 'listSpaces']) const mk = (side) => ({ token: tokenOf(acct, side), params: nsid === 'listSpaces' ? { cursor } : { space: spaceUri(sp, acct, side), repo: didOf(acct, side), cursor } }) const [a, b] = await both(`${nsid} with a cursor it never answered`, acct, `${SP}${nsid}`, mk) for (const [side, res] of [[ref, a], [cand, b]]) if (res.status !== 400 || res.body?.error !== 'InvalidCursor') await fail(side, `${nsid} with a cursor it never answered`, shown(nsid, mk(side)), { status: 400, error: 'InvalidCursor' }, { status: res.status, error: res.body?.error ?? null }) } /// Calls with no token, a bad one, a refresh token, or an app password's /// (spec/SPACES-REPO.md, "Who may call"). async function tokens(acct) { const kind = pick(['none', 'bad', 'refresh', 'app', 'app']) const r = rand() if (r < 0.5) return createRecord(acct, kind) if (r < 0.75) return listSpaces(acct, kind) return latestCommit(acct, pick(spaces), 'none', `getLatestCommit (${kind} token)`, kind) } // ---- the size limits ------------------------------------------------------------------------------ /// A body of exactly `n` bytes: `base` with its `field` padded. function padded(n, base, pad) { const bare = JSON.stringify(pad(base, '')) return JSON.stringify(pad(base, 'x'.repeat(n - bare.length))) } async function sizes(acct) { const sp = sizesSpace const env = (side, rkey) => ({ space: sp.uri(), repo: didOf(acct, side), collection: 'com.example.note', rkey }) const raw = (kind, nsid, mkRaw) => both(kind, acct, nsid, (side) => ({ token: tokenOf(acct, side), raw: mkRaw(side) })) // the body limit of createRecord, putRecord and applyWrites // (spec/SPACES-REPO.md, "The order of the checks") for (const n of [1000000, 1000001]) { const mkRaw = (side) => padded(n, env(side, `body${n}`), (b, s) => ({ ...b, record: { $type: 'com.example.note', s } })) const [a, b] = await raw(`createRecord of a ${n}-byte body`, `${SP}createRecord`, mkRaw) await after('createRecord', acct, sp, a, b, async (side, res) => { const rec = JSON.parse(mkRaw(side)).record; await put(side, acct, sp, 'com.example.note', `body${n}`, rec, res.body.cid, { body: `${n} bytes` }, `createRecord of a ${n}-byte body`); return true }) } // the record limit, with whole numbers written as exponents // (spec/SPACES-REPO.md, "Records") for (const d of [1048576, 1048577]) { const count = Math.floor((d - 2000) / 9) const nums = new Array(count).fill(9e15) const bare = encode({ $type: 'com.example.note', a: nums, s: '' }).length let m = d - bare - 4 while (encode({ $type: 'com.example.note', a: nums, s: 'x'.repeat(m) }).length < d) m++ const rec = { $type: 'com.example.note', a: nums, s: 'x'.repeat(m) } const json = `{"$type":"com.example.note","a":[${new Array(count).fill('9e15').join(',')}],"s":"${rec.s}"}` const mkRaw = (side) => `${JSON.stringify(env(side, `drisl${d}`)).slice(0, -1)},"record":${json}}` const [a, b] = await raw(`createRecord of a record of ${d} bytes of DRISL`, `${SP}createRecord`, mkRaw) await after('createRecord', acct, sp, a, b, async (side, res) => { await put(side, acct, sp, 'com.example.note', `drisl${d}`, rec, res.body.cid, { record: `${d} bytes of DRISL` }, `createRecord of ${d} bytes of DRISL`); return true }) } { const json = '{"n":1e3,"m":1000.0,"e":2E2,"z":-0}' const rec = { n: 1000, m: 1000, e: 200, z: 0 } const mkRaw = (side) => `${JSON.stringify(env(side, 'exponents')).slice(0, -1)},"record":${json}}` const [a, b] = await raw('createRecord of whole numbers written as exponents', `${SP}createRecord`, mkRaw) await after('createRecord', acct, sp, a, b, async (side, res) => { await put(side, acct, sp, 'com.example.note', 'exponents', rec, res.body.cid, { record: json }, 'createRecord of whole numbers written as exponents'); return true }) } // the body limit of deleteRecord and clearRecords (spec/SPACES-REPO.md, // "The order of the checks") for (const n of [153600, 153601]) { const [a, b] = await raw(`deleteRecord of a ${n}-byte body`, `${SP}deleteRecord`, (side) => padded(n, env(side, 'absent'), (b, s) => ({ ...b, pad: s }))) await after('deleteRecord', acct, sp, a, b, async () => false) } for (const n of [153600, 153601]) { const [a, b] = await raw(`clearRecords of a ${n}-byte body`, `${SP}clearRecords`, (side) => padded(n, { space: sp.uri(), repo: didOf(acct, side) }, (b, s) => ({ ...b, pad: s }))) await after('clearRecords', acct, sp, a, b, async (side) => { const m = repoOf(acct, side, sp); const had = m.records.size > 0; m.records.clear(); if (had) m.base = new Map(); return had }) } } // ---- whole repos, and the run ------------------------------------------------------------------------ /// Every repo of the account, read whole: its commit, its records and its /// operation log, each against the reference and the model. async function readWhole(acct, kind) { for (const sp of [...spaces, own, sizesSpace]) { if (!repoOf(acct, ref, sp).exists && !repoOf(acct, cand, sp).exists) continue await latestCommit(acct, sp, 'none', `getLatestCommit ${kind}`) await listRepoOps(acct, sp, true) await ext.whole(acct, sp, kind) } await listSpaces(acct) } /// The public repository is not touched by any of it /// (spec/SPACES-REPO.md, "A space repo"). async function publicUntouched() { for (const acct of modelled) for (const side of sides) { const now = (await call(side, 'com.atproto.sync.getLatestCommit', { params: { did: didOf(acct, side) } })).body if (!isDeepStrictEqual(now, sd(acct, side).publicCommit)) await fail(side, 'the public repository after space writes', { account: `` }, sd(acct, side).publicCommit, now) } h.count('public repository untouched by space writes') } let STEPS = [ [14, createRecord], [10, putRecord], [7, deleteRecord], [9, applyWrites], [2, (a) => clearRecords(a)], [9, getRecord], [6, listRecords], [6, (a) => latestCommit(a, pickSpace({ malformed: 0.02, ownP: 0.03 }), 'none', 'getLatestCommit', 'access', macAsk(COMMIT_PROFILE))], [7, (a) => listRepoOps(a)], [3, (a) => listSpaces(a)], [4, tokens], [1, badCursor], ] return { /// The steps, then the size limits, then every repo read whole. async run(steps, extension) { if (extension) { ext = extension; STEPS = [...STEPS, ...ext.steps] } const TOTAL = STEPS.reduce((n, [w]) => n + w, 0) await setup() await ext.setup?.() for (let i = 0; i < steps; i++) { const acct = pick(accounts) let r = below(TOTAL) for (const [w, step] of STEPS) { if (r < w) { await step(acct); break } r -= w } } await sizes(accounts[0]) await ext.fixed?.() modelled = [...accounts] for (const acct of modelled) await readWhole(acct, 'before a restart') await publicUntouched() }, /// After the server is killed and started again: every repo as it was, /// and a write's `rev` later than every one before (spec/SPACES-REPO.md, /// "Durability"). async afterRestart() { for (const acct of modelled) await readWhole(acct, 'after a restart') for (const acct of modelled) { const sp = spaces[0] const rec = goodRecord('com.example.note') const key = `after-restart` const mk = (side) => ({ token: tokenOf(acct, side), body: { space: sp.uri(), repo: didOf(acct, side), collection: 'com.example.note', rkey: key, record: rec } }) const [a, b] = await both('putRecord after a restart', acct, `${SP}putRecord`, mk) await after('putRecord after a restart', acct, sp, a, b, async (side, res) => { await put(side, acct, sp, 'com.example.note', key, rec, res.body.cid, shown('putRecord', mk(cand)), 'putRecord after a restart'); return true }) } await publicUntouched() }, /// What another part's checks build on: the requests, the model and the /// checks of each answer. internals: { SP, COLLECTIONS, RKEYS, TID, call, both, norm, shown, fail, tokenOf, sd, didOf, repoOf, digestOf, put, after, latestCommit, pickSpace, keyOn, cidOf, drisl, typed, below, chance, pick, checkMacHeaders, holdInvalidMac, checkCommit, commitOf, byBytes, knownCids, readWhole, macAsk, askHeaders, askName, hasToken, get spaces() { return spaces }, get sizesSpace() { return sizesSpace }, own, }, } }