chadtmiller.com/monolith
An atproto PDS
0
0
// OAuth access tokens on every method, and what scopes allow
// (spec/OAUTH-SCOPES.md): accounts sign in through checks/oauth.mjs's flow
// with clients whose scopes mix `atproto`, the transitional scopes and
// granular permissions, and their sessions call each kind of method, with a
// good proof or with one thing wrong.
//
// Writes that land on both sides are noted as checks/records.mjs notes
// its own, so the repository checks see them.
import { ref } from '../lib/processes.mjs'
import { COLLECTIONS, RKEYS, below, chance, goodRecord, pick, rand } from '../lib/random.mjs'
import { accounts, cids, didOf, exists, nextBatch, noteCommit, noteKeys, noteWrite } from '../lib/state.mjs'
import { normalize } from '../lib/xrpc.mjs'
import { newKey, proof, wwwError } from '../lib/oauth.mjs'
import { issuer } from '../lib/server.mjs'
import { DPOP_FAULTS, compare, dpops, freshNonce, handleOf, login, oauthOf, pickSession, sides } from './oauth.mjs'
const REDIRECT = 'http://127.0.0.1/callback'
/// Loopback clients whose scopes mix the permissions the methods served
/// need; each request asks a random part of its client's scope
/// (spec/OAUTH-SCOPES.md, "What a scope allows").
const SCOPED_CLIENTS = [
'atproto repo:com.example.note?action=create blob:image/* identity:handle transition:email',
'atproto repo:com.example.note repo:com.example.todo?action=update&action=delete blob:text/plain identity:*',
'atproto repo?collection=com.example.todo&collection=com.example.test.item&action=create repo:*?action=delete blob:*/* account:email?action=manage',
'atproto transition:generic repo:com.example.note?action=create identity:handle',
'atproto repo:* blob:image/png blob:video/* account:email account:repo?action=manage',
'atproto repo:com.example.note?action=update repo:com.example.test.item?action=create&action=update blob:TEXT/Plain account?attr=email',
].map((scope) => ({ scope, redirects: [REDIRECT] }))
/// Media types `uploadBlob` is sent with (spec/BLOBS.md takes each, or
/// refuses none); `null` sends no `Content-Type`.
const MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml', 'text/plain', 'text/plain; charset=utf-8', 'TEXT/Plain', 'video/mp4', 'application/json', '*/*', 'image/*', 'a/b/c', null]
/// Methods whose success is compared by status alone: CAR files, bytes, and
/// bodies with each side's own commits.
const STATUS_ONLY = ['com.atproto.server.checkAccountStatus', 'com.atproto.sync.getRepo', 'com.atproto.sync.getLatestCommit', 'com.atproto.sync.getRecord', 'com.atproto.sync.getBlocks', 'com.atproto.sync.listBlobs', 'com.atproto.sync.getBlob', 'com.atproto.sync.listRepos', 'com.atproto.sync.getRepoStatus']
const WRITES = ['com.atproto.repo.createRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.deleteRecord', 'com.atproto.repo.applyWrites']
let serial = 0
const bytesOf = (n) => new TextEncoder().encode(`spec-pds blob oauth-scopes ${n}`)
// ---------------------------------------------------------------- answers
/// An answer to a call with a token, as compared (spec/OAUTH-SCOPES.md,
/// "The token and its proof", "What each method needs").
function rsView(side, res, nsid) {
const v = { status: res.status }
if (res.status >= 400 || res.status === 0) {
v.error = res.body?.error ?? null
if (v.error === 'ScopeMissingError') v.message = res.body?.message ?? null
} else if (!STATUS_ONLY.some((n) => n.toLowerCase() === nsid.toLowerCase())) v.body = normalize(side, res, nsid).body
v.nonce = Boolean(res.headers?.['dpop-nonce'])
const w = wwwError(res.headers?.['www-authenticate'])
if (w) v.www = w
const exposed = String(res.headers?.['access-control-expose-headers'] ?? '').toLowerCase().split(',').map((x) => x.trim())
v.exposes = ['dpop-nonce', 'www-authenticate'].filter((n) => exposed.includes(n))
return v
}
// --------------------------------------------------------------- requests
/// A call to `side`'s XRPC `nsid`. `c` is `{method, params, body, bytes,
/// type, headers}`; `with` says how it carries the token: `{accessToken,
/// scheme, dpop (a Dpop), proofOpts, header (the DPoP header as given, or
/// null for none), retry}`.
function send(side, nsid, c, w) {
const url = new URL(`${issuer(side)}/xrpc/${nsid}`)
for (const [k, v] of Object.entries(c.params ?? {})) for (const x of Array.isArray(v) ? v : [v]) if (x !== undefined) url.searchParams.append(k, x)
const headers = { ...(c.headers ?? {}) }
let body
if (c.bytes) {
body = c.bytes
if (c.type !== null && c.type !== undefined) headers['content-type'] = c.type
} else if (c.body !== undefined) {
body = JSON.stringify(c.body)
headers['content-type'] = 'application/json'
}
const method = c.method ?? (body === undefined ? 'GET' : 'POST')
return w.dpop.send(url.href, { method, headers, body, accessToken: w.accessToken, scheme: w.scheme ?? 'DPoP', retry: w.retry ?? true, proofOpts: w.proofOpts ?? {}, dpop: w.header })
}
/// Note, on both sides, what a write that may have landed changed.
function noteWrites(acct, nsid, call, res) {
if (!WRITES.includes(nsid)) return
for (const side of sides()) {
noteKeys(side, nsid, call(side).body, res[side.name])
noteCommit(side, acct, res[side.name])
}
const a = res.reference
const body = call(ref).body ?? {}
if (a.status >= 400) return
if (nsid.endsWith('deleteRecord')) acct.records.delete(`${body.collection}/${body.rkey}`)
else if (nsid.endsWith('applyWrites')) {
body.writes.forEach((w, i) => {
const k = `${w.collection}/${w.rkey}`
if (w.$type.endsWith('#delete')) acct.records.delete(k)
else if (a.body.results?.[i]?.cid) {
acct.records.set(k, a.body.results[i].cid)
cids.push(a.body.results[i].cid)
}
})
} else noteWrite(acct, body.collection, body.rkey, a)
}
/// The same call on both sides with the session's token, compared.
async function both(kind, acct, s, nsid, call, how = (side) => ({ dpop: s.dpop[side.name], accessToken: s.tokens[side.name].access }), request = {}) {
const res = await compare(`scopes: ${kind}`, { nsid, scope: s.scope, ...request, call: shownCall(call(ref)) }, (side) => send(side, nsid, call(side), how(side)), (side, r) => rsView(side, r, nsid))
noteWrites(acct, nsid, call, res)
return res
}
const shownCall = (c) => ({ ...c, ...(c.bytes ? { bytes: `${c.bytes.length} bytes` } : {}) })
// ------------------------------------------------------------------ calls
/// A key of the collection that exists in the account's repository, or
/// does not, as `want` says, if there is one.
function keyOf(acct, collection, want) {
const ks = RKEYS.filter((k) => exists(acct, collection, k) === want)
return ks.length ? pick(ks) : pick(RKEYS)
}
/// A write of the harness's collections, mostly good, sometimes with its
/// input, `repo` or record wrong (the order of spec/OAUTH-SCOPES.md,
/// "What each method needs").
function write(acct) {
const nsid = pick(WRITES)
const collection = pick(COLLECTIONS)
const r = rand()
const f = r < 0.06 ? 'another account' : r < 0.1 ? 'no account' : r < 0.14 ? 'bad input' : r < 0.18 ? 'bad $type' : null
// A delete has no record to give a wrong `$type`.
const fault = f === 'bad $type' && nsid.endsWith('deleteRecord') ? null : f
const others = accounts.filter((a) => a !== acct && handleOf(a))
const repo = (side) => (fault === 'another account' && others.length ? pick(others).handle : fault === 'no account' ? 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa' : acct.handle)
const value = () => ({ ...goodRecord(collection), batch: nextBatch(), ...(fault === 'bad $type' ? { $type: pick(COLLECTIONS.filter((c) => c !== collection)) } : {}) })
let body
if (nsid.endsWith('createRecord')) body = { collection, rkey: keyOf(acct, collection, chance(0.2)), record: value() }
else if (nsid.endsWith('putRecord')) body = { collection, rkey: keyOf(acct, collection, chance(0.5)), record: value() }
else if (nsid.endsWith('deleteRecord')) body = { collection, rkey: keyOf(acct, collection, chance(0.8)) }
else {
const used = new Set()
const writes = []
for (let i = 0; i < 1 + below(4); i++) {
const c = pick(COLLECTIONS)
const kind = pick(['create', 'create', 'update', 'delete'])
const k = keyOf(acct, c, kind !== 'create')
if (used.has(`${c}/${k}`)) continue
used.add(`${c}/${k}`)
writes.push({ $type: `com.atproto.repo.applyWrites#${kind}`, collection: c, rkey: k, ...(kind === 'delete' ? {} : { value: { ...goodRecord(c), batch: nextBatch() } }) })
}
const w = writes.find((x) => x.value)
if (fault === 'bad $type' && w) w.value.$type = pick(COLLECTIONS.filter((c) => c !== w.collection))
body = { writes }
}
if (fault === 'bad input') delete body[nsid.endsWith('applyWrites') ? 'writes' : 'collection']
// One value for both sides: the other account is drawn once.
const r0 = repo(ref)
return { nsid, kind: `${nsid.split('.').pop()}${fault ? ` (${fault})` : ''}`, call: () => ({ body: { repo: r0, ...body } }) }
}
/// The calls the step draws: `{nsid, kind, call(side)}`, of every kind of
/// method (spec/OAUTH-SCOPES.md, "Which methods take a token", "What each
/// method needs").
const CALLS = [
[write, 8],
[() => {
const type = pick(MEDIA_TYPES)
const bytes = bytesOf(++serial)
return { nsid: 'com.atproto.repo.uploadBlob', kind: `uploadBlob (${type ?? 'no Content-Type'})`, call: () => ({ bytes, type }) }
}, 4],
[() => {
const body = chance(0.5) ? { handle: 'not a handle!' } : {}
return { nsid: 'com.atproto.identity.updateHandle', kind: 'updateHandle (a handle that does not parse)', call: () => ({ body }) }
}, 2],
[() => ({ nsid: 'com.atproto.server.getSession', kind: 'getSession', call: () => ({}) }), 1],
[() => ({ nsid: 'com.atproto.identity.getRecommendedDidCredentials', kind: 'getRecommendedDidCredentials', call: () => ({}) }), 1],
[() => {
const [nsid, body] = pick([['createAppPassword', { name: `oauth ${serial}` }], ['createAppPassword', {}], ['listAppPasswords', undefined], ['revokeAppPassword', { name: 'x' }], ['revokeAppPassword', {}], ['getAccountInviteCodes', undefined]])
return { nsid: `com.atproto.server.${nsid}`, kind: nsid, call: () => (body === undefined ? {} : { body }) }
}, 2],
[(acct) => {
// The email and lifecycle methods (spec/OAUTH-SCOPES.md, "What each
// method needs"), none of which changes the account's state here: a
// deactivation's input is wrong, and an activation and the email's
// change are refused to OAuth tokens. The emails a request sends are
// compared by the next email step.
const [nsid, body] = pick([
['server.requestEmailConfirmation', undefined],
['server.confirmEmail', { email: acct.email, token: 'AAAAA-BBBBB' }],
['server.requestEmailUpdate', undefined],
['server.updateEmail', { email: acct.email }],
['server.checkAccountStatus', undefined],
['server.requestAccountDelete', undefined],
['server.deactivateAccount', { deleteAfter: 'tomorrow' }],
['server.activateAccount', undefined],
['server.deleteAccount', { did: 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa', password: 'x', token: 'AAAAA-BBBBB' }],
['server.resetPassword', { token: 'AAAAA-BBBBB', password: 'x' }],
['admin.getSubjectStatus', null],
])
const nsidFull = `com.atproto.${nsid}`
if (body === null) return { nsid: nsidFull, kind: nsid, call: (side) => ({ params: { did: didOf(side, acct) } }) }
const procedure = !['server.checkAccountStatus'].includes(nsid)
return { nsid: nsidFull, kind: nsid, call: () => (body !== undefined ? { body } : procedure ? { method: 'POST' } : {}) }
}, 2],
[(acct) => {
const keys = [...acct.records.keys()]
const [collection, rkey] = keys.length ? pick(keys).split('/') : [pick(COLLECTIONS), pick(RKEYS)]
const cid = acct.records.size ? pick([...acct.records.values()]) : cids.length ? pick(cids) : undefined
const [nsid, params] = pick([
['getRepo', (side) => ({ did: didOf(side, acct) })],
['getLatestCommit', (side) => ({ did: didOf(side, acct) })],
['getRecord', (side) => ({ did: didOf(side, acct), collection, rkey })],
['getBlocks', (side) => ({ did: didOf(side, acct), cids: cid })],
['listBlobs', (side) => ({ did: didOf(side, acct) })],
['getBlob', (side) => ({ did: didOf(side, acct), cid })],
])
return { nsid: `com.atproto.sync.${nsid}`, kind: `sync.${nsid}`, call: (side) => ({ params: params(side) }) }
}, 3],
[(acct) => {
const [nsid, params] = pick([
['server.describeServer', () => ({})],
['repo.describeRepo', (side) => ({ repo: didOf(side, acct) })],
['identity.resolveHandle', () => ({ handle: acct.handle })],
['repo.getRecord', () => ({ repo: acct.handle, collection: pick(COLLECTIONS), rkey: pick(RKEYS) })],
['repo.listRecords', () => ({ repo: acct.handle, collection: pick(COLLECTIONS) })],
['sync.listRepos', () => ({})],
['sync.getRepoStatus', (side) => ({ did: didOf(side, acct) })],
])
const p = params(ref)
return { nsid: `com.atproto.${nsid}`, kind: `${nsid} (takes no token)`, call: (side) => ({ params: nsid.endsWith('describeRepo') || nsid.endsWith('getRepoStatus') ? params(side) : p }) }
}, 2],
[() => {
const n = ++serial
return { nsid: 'com.atproto.server.createAccount', kind: 'createAccount', call: () => ({ body: { handle: `oauth-scopes${n}.test`, email: `oauth-scopes${n}@example.com`, password: 'oauth-scopes' } }) }
}, 1],
]
const totalWeight = CALLS.reduce((n, [, w]) => n + w, 0)
function drawCall(acct) {
let r = below(totalWeight)
for (const [f, w] of CALLS) if ((r -= w) < 0) return f(acct)
}
/// A session of the account to call with: one of its sessions, or a new
/// one with a client of SCOPED_CLIENTS.
async function sessionFor(acct) {
if (!handleOf(acct)) return null
const s = await pickSession(acct)
if (s && chance(0.7)) return s
return (await login(acct, { client: pick(SCOPED_CLIENTS), reject: false, narrow: false })) ?? s
}
// ------------------------------------------------------------------ steps
/// A call of a random method with a session's access token and a good proof.
export async function oauthScopedCall(acct) {
const s = await sessionFor(acct)
if (!s) return
const c = drawCall(acct)
await both(c.kind, acct, s, c.nsid, c.call)
}
/// The calls a refusal step makes: a method of each kind that takes a
/// token, with its call good but for the one thing wrong.
const TARGETS = [
(acct) => ({ nsid: 'com.atproto.server.getSession', call: () => ({}) }),
(acct) => ({ nsid: 'com.atproto.identity.getRecommendedDidCredentials', call: () => ({}) }),
(acct) => ({ nsid: 'com.atproto.server.listAppPasswords', call: () => ({}) }),
(acct) => ({ nsid: 'com.atproto.identity.updateHandle', call: () => ({ body: { handle: 'not a handle!' } }) }),
(acct) => {
const bytes = bytesOf(++serial)
const type = pick(['image/png', 'text/plain'])
return { nsid: 'com.atproto.repo.uploadBlob', call: () => ({ bytes, type }) }
},
(acct) => write(acct),
(acct) => ({ nsid: 'com.atproto.sync.getLatestCommit', call: (side) => ({ params: { did: didOf(side, acct) } }) }),
(acct) => ({ nsid: 'com.atproto.sync.listBlobs', call: (side) => ({ params: { did: didOf(side, acct) } }) }),
]
/// A call that takes a token, with one thing wrong in its proof, its token,
/// its scheme, or with a bad proof and bad parameters or input
/// (spec/OAUTH-SCOPES.md, "Which methods take a token", "The token and its
/// proof").
export async function oauthScopedRefused(acct) {
const s = await sessionFor(acct)
if (!s) return
const t = pick(TARGETS)(acct)
const { nsid } = t
let call = t.call
const at = (side) => s.tokens[side.name].access
const own = (side, extra = {}) => ({ dpop: s.dpop[side.name], accessToken: at(side), ...extra })
const r = rand()
if (r < 0.45) {
// A proof with one thing wrong, or replayed, with a fresh nonce.
const fault = chance(0.1) ? ['replayed'] : pick(DPOP_FAULTS)
for (const side of sides()) await freshNonce(side, s.dpop[side.name])
const proofs = {}
for (const side of sides()) {
const c = call(side)
const method = c.method ?? (c.bytes || c.body !== undefined ? 'POST' : 'GET')
const htu = `${issuer(side)}/xrpc/${nsid}`
proofs[side.name] = fault[0] === 'replayed' ? await proof(s.key, method, htu, { nonce: s.dpop[side.name].nonce, accessToken: at(side) }) : await fault[1](s.key, method, htu, s.dpop[side.name].nonce, at(side))
}
if (fault[0] === 'replayed') await both(`${nsid} (a proof, for a replay)`, acct, s, nsid, call, (side) => own(side, { header: proofs[side.name] }))
return void (await both(`${nsid}: proof ${fault[0]}`, acct, s, nsid, call, (side) => own(side, { header: proofs[side.name] })))
}
let how
let name
const tr = rand()
if (tr < 0.1) [name, how] = ['no DPoP header', (side) => own(side, { header: null })]
else if (tr < 0.2 && s.old.reference.length) [name, how] = ['a replaced access token', (side) => own(side, { accessToken: s.old[side.name].at(-1).access })]
else if (tr < 0.3) [name, how] = ['a token never given out', (side) => own(side, { accessToken: 'garbage' })]
else if (tr < 0.38) [name, how] = ['the refresh token', (side) => own(side, { accessToken: s.tokens[side.name].refresh })]
else if (tr < 0.46) [name, how] = ["a password session's token", (side) => own(side, { accessToken: acct.sides[side.name].token })]
else if (tr < 0.56) {
const other = dpops(await newKey())
;[name, how] = ['a proof by another key', (side) => own(side, { dpop: other[side.name] })]
} else if (tr < 0.66) [name, how] = ['the Bearer scheme', (side) => own(side, { scheme: 'Bearer' })]
else if (tr < 0.72) [name, how] = ['the scheme in lower case', (side) => own(side, { scheme: 'dpop' })]
else if (tr < 0.78) [name, how] = ['a header of one word', (side) => ({ dpop: s.dpop[side.name], accessToken: undefined, scheme: 'DPoP' })]
else if (tr < 0.84) [name, how] = ['a header of three words', (side) => own(side, { accessToken: `${at(side)} x` })]
else if (tr < 0.92) {
// Bad parameters or input, and a proof without a nonce: a query's
// parameters are checked first, a procedure's token first.
const proc = chance(0.5)
name = proc ? 'bad input and no nonce' : 'bad parameters and no nonce'
const bad = proc ? { nsid: 'com.atproto.repo.createRecord', call: () => ({ body: { repo: acct.handle } }) } : { nsid: pick(['com.atproto.sync.getLatestCommit', 'com.atproto.sync.listBlobs', 'com.atproto.sync.getRepo']), call: () => ({ params: { did: 'not-a-did' } }) }
return void (await both(`${bad.nsid}: ${name}`, acct, s, bad.nsid, bad.call, (side) => own(side, { retry: false, proofOpts: { nonce: undefined } })))
} else {
name = 'the wrong HTTP method'
const target = pick([['com.atproto.server.getSession', 'POST'], ['com.atproto.repo.createRecord', 'GET']])
return void (await both(`${target[0]}: ${name}`, acct, s, target[0], () => ({ method: target[1] })))
}
if (name === 'a header of one word') call = (side) => ({ ...t.call(side), headers: { authorization: 'DPoP' } })
await both(`${nsid}: ${name}`, acct, s, nsid, call, how)
}
/// A session of the account whose only permission is `blob:image/*`, kept
/// for the edge cases below with the account's other OAuth sessions, so
/// that a password reset, which ends them on the server (spec/EMAIL.md,
/// "resetPassword"), ends it too.
const IMAGES_ONLY = { scope: 'atproto blob:image/*', redirects: [REDIRECT] }
/// The cases spec/OAUTH-SCOPES.md settles at the edges, each drawn every
/// time: a media type with a tab in it, and one with a byte outside ASCII,
/// as the scope and its refusal read them; `createAccount` with an
/// `Authorization` of the `DPoP` scheme that is not two words, or names no
/// token; and a method named in another case, with its proof's `htu` the
/// path as sent and as the lexicon spells it.
export async function oauthScopedEdges(acct) {
if (!handleOf(acct)) return
const st = oauthOf(acct)
let s = st.imagesOnly
if (!s) {
s = await login(acct, { client: IMAGES_ONLY, reject: false, narrow: false, whole: true })
if (!s) return
st.imagesOnly = s
}
const own = (side, extra = {}) => ({ dpop: s.dpop[side.name], accessToken: s.tokens[side.name].access, ...extra })
// A tab is not a space: `image/png\t` is a type and subtype that
// `blob:image/*` allows. A byte outside ASCII is read as the Latin-1
// character it is, lowercased as Unicode lowercases it, then encoded as
// UTF-8: `É` (0xC9) is `%C3%A9`; `Ã` and 0x89, the bytes of `É` in
// UTF-8, are `%C3%A3%C2%89` (spec/OAUTH-SCOPES.md, "What a scope allows",
// "What each method needs").
const types = ['image/png\t; q=1', 'image/p\tng', 'im\tage/png', 'TEXT/PLA\u00c9N', 'TEXT/PLA\u00c3\u0089N', 'IMAGE/P\u00c9NG']
for (const type of types) {
const bytes = bytesOf(++serial)
await both(`uploadBlob (${JSON.stringify(type)}), with blob:image/*`, acct, s, 'com.atproto.repo.uploadBlob', () => ({ bytes, type }), own)
}
// createAccount refuses the DPoP scheme whatever follows it
// (spec/OAUTH-SCOPES.md, "Which methods take a token").
const n = ++serial
const body = { handle: 'not a handle!', email: `oauth-edges${n}@example.com`, password: 'oauth-edges' }
const auths = [['DPoP', 'one word'], ['DPoP a b', 'three words'], ['DPoP abc', 'a token never given out, and no proof'], ['dpop abc', 'the scheme in lower case, and no proof']]
for (const [authorization, what] of auths) await both(`createAccount with a DPoP header of ${what}`, acct, s, 'com.atproto.server.createAccount', () => ({ body, headers: { authorization } }), (side) => ({ dpop: s.dpop[side.name], accessToken: undefined, header: null, retry: false }))
// A method named in another case: `htu` is the path as sent
// (spec/OAUTH-SCOPES.md, "The token and its proof").
for (const [nsid, lexicon] of [['COM.ATPROTO.SERVER.GETSESSION', 'com.atproto.server.getSession'], ['com.atproto.sync.GetLatestCommit', 'com.atproto.sync.getLatestCommit']]) {
const call = (side) => (lexicon.endsWith('getLatestCommit') ? { params: { did: didOf(side, acct) } } : {})
await both(`${nsid}, its proof's htu as sent`, acct, s, nsid, call, own)
for (const side of sides()) await freshNonce(side, s.dpop[side.name])
const proofs = {}
for (const side of sides()) proofs[side.name] = await proof(s.key, 'GET', `${issuer(side)}/xrpc/${lexicon}`, { nonce: s.dpop[side.name].nonce, accessToken: s.tokens[side.name].access })
await both(`${nsid}, its proof's htu as the lexicon spells it`, acct, s, nsid, call, (side) => own(side, { header: proofs[side.name], retry: false }))
}
}
// What checks/permission-sets.mjs shares with these checks.
export { both, rsView, send, write }