~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

harness: SMTP, requests out, MCP lifecycle and spaces OAuth checked

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:harness/unchecked
harness/checks/backup.mjs+1−1
@@ -23,7 +23,7 @@ const PUTS = 8
/// nothing, serves no metrics, writes no mail, and its guard keeps it from
/// the harness's services (spec/PROXY.md); with no crawlers too, nothing it
/// does reaches what the run checks.
const APART = ['PDS_METRICS_PORT', 'OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS', 'PDS_DEV_MAIL_DIR', 'PDS_DISABLE_SSRF_PROTECTION']
const APART = ['PDS_METRICS_PORT', 'OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_HEADERS', 'PDS_DEV_MAIL_DIR', 'PDS_EMAIL_SMTP_URL', 'PDS_EMAIL_FROM', 'PDS_DISABLE_SSRF_PROTECTION']
const broke = (what, request, want, got) => differ(`a server started on a snapshot: ${what}`, request, want, got, 'spec/DURABILITY.md, "Backups"')
harness/checks/crashes.mjs+3−0
@@ -18,6 +18,7 @@ import { blobsSurvive, uploadInFlight } from './blobs.mjs'
import { afterRestart, orphanUpload } from './blobstore.mjs'
import { oauthAfterCrash, oauthBeforeCrash } from './oauth.mjs'
import { oauthClientsAfterCrash, oauthClientsBeforeCrash } from './oauth-clients.mjs'
import { mcpAfterCrash, mcpBeforeCrash } from './oauth-mcp.mjs'
import { invitesSurvive } from './limits.mjs'
import { preferencesAfterCrash } from './proxy.mjs'
@@ -34,6 +35,7 @@ export const crashes = { count: 0, inFlight: 0, landed: 0, restartMs: [], reorga
export async function crash({ lead, accountsMade = true } = {}) {
await oauthBeforeCrash()
await oauthClientsBeforeCrash()
await mcpBeforeCrash()
const now = lead ? await lead() : false
const op = !now && rand() < 0.6 ? await (chance(0.25) ? inFlightHandle : inFlightPut)(pick(accounts)) : null
if (op) await wait(below(8))
@@ -64,6 +66,7 @@ export async function crash({ lead, accountsMade = true } = {}) {
await blobsSurvive()
await oauthAfterCrash()
await oauthClientsAfterCrash()
await mcpAfterCrash()
await invitesSurvive()
await preferencesAfterCrash()
if (accountsMade && chance(0.3)) await createAccount()
harness/checks/email.mjs+51−0
@@ -14,6 +14,7 @@ import { both, normalize, shown, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { EDGE_BAD_EMAILS, EMOJI, edgeEmail, freshFront, mixCase } from './accounts.mjs'
import { Browser, wwwError } from '../lib/oauth.mjs'
import { CLIENTS, approved, getSessionOn, handleOf, loadPage, login as oauthLogin, newRequest, oauthOf, pageUrl, signIn, token as tokenEndpoint } from './oauth.mjs'
import { smtp } from '../lib/server.mjs'
const REQUEST_CONFIRM = 'com.atproto.server.requestEmailConfirmation'
const CONFIRM = 'com.atproto.server.confirmEmail'
@@ -471,3 +472,53 @@ export async function appPasswordEmail(acct) {
await call(`updateEmail with ${kind}`, UPDATE, (side) => ({ token: token(side), body: { email } }))
}
}
/// An email the SMTP server refuses: requestEmailConfirmation or
/// requestPasswordReset for the account, with the server's SMTP server
/// refusing each message for that one call. The reference sends its email;
/// the server, which keeps the token before sending, answers `500
/// InternalServerError`, held to the spec on the server alone, and its
/// development sink records the email as the reference's mailer does. Then
/// the token it could not send, given back, works as the reference's:
/// confirmEmail, then getSession; or resetPassword with a new password,
/// then createSession with the old and the new, as `passwordReset` after
/// a reset (spec/EMAIL.md, "SMTP").
export async function smtpRefused(acct) {
const sink = smtp()
if (!sink || !acct.password) return
await strays()
const reset = chance(0.4)
const [kind, nsid, request] = reset
? ['requestPasswordReset, the SMTP server refusing its email', REQUEST_RESET, { body: { email: acct.email } }]
: ['requestEmailConfirmation, the SMTP server refusing its email', REQUEST_CONFIRM, { method: 'POST', token: acct }]
sink.refusing = true
let a, b
try {
;[a, b] = await Promise.all([xrpcHttp(ref, nsid, request), xrpcHttp(cand, nsid, request)])
} finally {
sink.refusing = false
}
const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
const want = na.status === 200 ? { status: 500, error: 'InternalServerError' } : na
if (!isDeepStrictEqual(nb, want)) await differ(`${nsid}, the SMTP server refusing its email`, shown(request), want, nb, na.status === 200 ? 'held to spec/EMAIL.md ("SMTP") on the server alone: the reference sent its email' : undefined)
count(kind, false)
const sent = await checkMail(kind, shown(request))
keep(sent)
if (na.status !== 200 || !sent.server.length) return
if (!reset) {
const t = tokensOf(acct, 'confirm_email')
const i = t.reference.length - 1
const [c, d] = await call('confirmEmail with the token of an email the SMTP server refused', CONFIRM, (side) => ({ token: acct, body: { email: acct.email, token: t[side.name][i] } }))
if (c.status === 200 && d.status === 200) await both('getSession after confirmEmail', GET, { token: acct })
return
}
const t = tokensOf(acct, 'reset_password')
const i = t.reference.length - 1
const [old, password] = [acct.password, `pw-${freshFront()}`]
const [c, d] = await call('resetPassword with the token of an email the SMTP server refused', RESET, (side) => ({ body: { token: t[side.name][i], password } }))
if (c.status !== 200 || d.status !== 200) return
acct.password = password
await both('createSession with the old password, after resetPassword', LOGIN, { body: { identifier: acct.handle, password: old } })
await both('createSession with the new password, after resetPassword', LOGIN, login(acct))
await afterReset(acct, null)
}
harness/checks/limits.mjs+57−2
@@ -19,7 +19,7 @@ import { begin, end, now } from '../lib/observe.mjs'
import { count, differ } from '../lib/report.mjs'
import { takeMail } from '../lib/mail.mjs'
import { accounts, cids, didOf, nextBatch, noteCommit, noteKeys, tokenOf } from '../lib/state.mjs'
import { answerWith, ownHost, silentHost } from '../lib/services.mjs'
import { answerWith, ownHost, silentHost, takeRequests } from '../lib/services.mjs'
import { normalize, shown, xrpc } from '../lib/xrpc.mjs'
import { RESERVABLE, createAccount, freshFront, mixCase, newAccountInput, sendCreate } from './accounts.mjs'
import { describeServer } from './session.mjs'
@@ -944,6 +944,61 @@ async function outboundCaps() {
count('what the server reads of what it fetches', false)
}
/// The slots of requests out (spec/LIMITS.md, "Requests out"): 256 calls
/// forwarded to the AppView, held there, each answered with its headers at
/// once and then a byte of its body each second, so that none is given up
/// for want of an answer (spec/PROXY.md, "SSRF protection", "What is
/// answered"); a 257th never reaches it, and is `502 UpstreamFailure` once
/// it has waited 10 s; the 256 then ended, each is answered, and a call
/// forwarded after them is.
async function requestsOut() {
const acct = await serverAccount()
const ip = freshIp()
const call = () => send(cand, FORWARDED, { params: FORWARDED_PARAMS, token: acct.access, ip })
const ends = []
answerWith(() => ({
respond: (res) => {
res.on('error', () => {})
res.writeHead(200, { 'content-type': 'application/json' })
res.write('{')
const tick = setInterval(() => res.destroyed || res.write(' '), 1000)
ends.push(() => {
clearInterval(tick)
if (!res.destroyed) res.end('}')
})
},
}))
const release = () => {
answerWith()
for (const e of ends.splice(0)) e()
}
const fail = async (...args) => {
release()
await broke(...args)
}
let answered = 0
const held = Array.from({ length: 256 }, () => call().then((r) => ((answered += 1), r)))
const filling = Date.now()
while (ends.length < 256 && Date.now() - filling < 8000) await wait(20)
if (ends.length < 256) await fail('requests out', { forwarded: 256, to: 'an AppView that holds each open' }, '256 in flight at once, within 8 s', { reached: ends.length, answered })
const late = call()
const r = await Promise.race([late, wait(20000).then(() => null)])
const extra = ends.length - 256
const early = answered
if (r === null || extra || early || r.status !== 502 || r.body?.error !== 'UpstreamFailure' || r.ms < 9500 || r.ms > 13000) {
await fail(FORWARDED, { forwarded: 'a 257th', while: '256 requests out are held open' }, '502 UpstreamFailure after waiting 10 s for a slot (9.5 to 13 s), not sent, the 256 still held', { status: r?.status ?? 'no answer within 20 s', error: r?.body?.error, ms: r?.ms, sent: extra > 0, heldAnswered: early })
}
release()
const after = await Promise.all(held)
const bad = after.filter((a) => a.status !== 200)
if (bad.length) await broke(FORWARDED, { forwarded: 256, held: 'until the 257th was answered, then ended' }, 'each 200, the answer as it came', { notOk: bad.length, first: { status: bad[0].status, error: bad[0].body?.error, ms: bad[0].ms } })
takeRequests()
const again = await call()
const sent = takeRequests().filter((q) => q.service === 'appview' && q.path.startsWith(`/xrpc/${FORWARDED}`)).length
if (again.status !== 200 || sent !== 1 || again.ms > 5000) await broke(FORWARDED, { forwarded: 'one more', after: 'the 256 held were answered' }, '200, sent to the AppView once, within 5 s', { status: again.status, error: again.body?.error, sent, ms: again.ms })
count('requests out, 256 at once', true)
}
/// A subscription to `side`'s firehose from `ip`, live.
function subscribe(side, ip) {
const ws = new WebSocket(`${side.url.replace(/^http/, 'ws')}/xrpc/com.atproto.sync.subscribeRepos`, { headers: { 'x-forwarded-for': ip } })
@@ -1291,7 +1346,7 @@ async function fileModes() {
export async function limitsRun() {
const checks = [
signupLimit, loginLimit, handleLimit, uploadLimit, writeLimit, forwardedLimit, globalLimit, emailRequestLimits, passwordResetLimit, resetLimit, accountDeleteRequestLimit, deleteLimit, ...OAUTH_LIMIT_CHECKS,
sessionCap, appPasswordCap, ...OAUTH_SERVER_CHECKS, clientAddress, adminUnset, spacesPayFirst, didWebApart, outboundCaps,
sessionCap, appPasswordCap, ...OAUTH_SERVER_CHECKS, clientAddress, adminUnset, spacesPayFirst, didWebApart, outboundCaps, requestsOut,
firehoseMessages, firehoseSubscribers, plcDocuments, plcAtOnce, timeouts, diskFloor, blobQuota, blobTtl, openFiles, fileModes,
]
for (const check of checks) {
harness/checks/oauth-mcp.mjs+253−15
@@ -3,17 +3,24 @@
// the endpoint's 401 to tool calls with the bearer token it is given, its
// refresh and revocation; where else that token is refused; and what the
// MCP issuer refuses. The writes it makes are made on the reference too.
// Then MCP sessions on accounts of their own, through a takedown, two
// deactivations and a deletion, each change made on both sides alike; and,
// in a run with crashes, sessions made before each restart, after it.
import { isDeepStrictEqual } from 'node:util'
import { FIREHOSE } from '../lib/args.mjs'
import { ADMIN_PASSWORD } from '../lib/env.mjs'
import { checkMail } from '../lib/mail.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { serve } from '../lib/clients.mjs'
import { fail } from '../lib/plc.mjs'
import { count } from '../lib/report.mjs'
import { below } from '../lib/random.mjs'
import { accounts, didOf, nextBatch, noteCommit, noteWrite } from '../lib/state.mjs'
import { xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { count, differ } from '../lib/report.mjs'
import { below, pick } from '../lib/random.mjs'
import { accounts, didOf, nextBatch, noteCommit, noteWrite, tokenOf } from '../lib/state.mjs'
import { both, normalize, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { Browser, answer, form, fresh, pkce, target } from '../lib/oauth.mjs'
import { mcpPost } from '../lib/via.mjs'
import { createAccount } from './accounts.mjs'
import { approved } from './oauth.mjs'
/// The legacy revision Claude speaks, and the scope it is given.
@@ -76,12 +83,15 @@ function request(clientId, redirect, over = {}) {
}
/// Sign `acct` in through `/oauth/mcp/authorize` and the page, as `clientId`
/// to `redirect`: answers `{code, pk, redirect}` (spec/OAUTH-MCP.md, "The
/// authorization request").
async function signIn(acct, clientId, redirect, scope = SCOPE) {
/// to `redirect`: answers `{code, pk, redirect, b, page}`, `b` the browser,
/// the account signed in on it and remembered, and `page` the authorization
/// page (spec/OAUTH-MCP.md, "The authorization request"). On `device`, a
/// browser it is signed in on so, the page's consent alone (spec/OAUTH.md,
/// "The API").
async function signIn(acct, clientId, redirect, scope = SCOPE, device = null) {
const { issuer } = names()
const { pk, params } = request(clientId, redirect, { scope })
const b = new Browser()
const b = device ?? new Browser()
const start = await authorize(b, params)
const page = start.headers.location ? new URL(start.headers.location, cand.url).href : null
const p = page && new URL(page)
@@ -90,16 +100,18 @@ async function signIn(acct, clientId, redirect, scope = SCOPE) {
}
const shown = await b.navigate(page)
if (shown.status !== 200) return broke('the authorization page', { client_id: clientId }, 'the page', { status: shown.status, text: shown.text.slice(0, 200) })
const si = await b.api(page, '/sign-in', { locale: 'en', identifier: acct.handle, password: acct.password, remember: true })
if (si.status !== 200) return broke('sign-in', { client_id: clientId }, 'signed in', { status: si.status, body: si.json })
if (!device) {
const si = await b.api(page, '/sign-in', { locale: 'en', identifier: acct.handle, password: acct.password, remember: true })
if (si.status !== 200) return broke('sign-in', { client_id: clientId }, 'signed in', { status: si.status, body: si.json })
}
const c = await b.api(page, '/consent', { did: didOf(cand, acct) })
if (c.status !== 200 || !c.json?.url) return broke('consent', { client_id: clientId }, 'a url to the redirect', { status: c.status, body: c.json })
if (c.status !== 200 || !c.json?.url) return broke('consent', { client_id: clientId, device: Boolean(device) }, 'a url to the redirect', { status: c.status, body: c.json })
const back = await b.navigate(new URL(c.json.url, cand.url).href, { site: 'same-origin', referer: page })
const t = target(back.headers.location)
const want = { to: redirect, state: params.state, iss: issuer, code: true }
const got = { to: t?.to ?? null, state: t?.params?.state ?? null, iss: t?.params?.iss ?? null, code: Boolean(t?.params?.code) }
if (!isDeepStrictEqual(got, want)) await broke('the redirect back', { client_id: clientId, redirect_uri: redirect }, want, { ...got, status: back.status })
return { code: t.params.code, pk, redirect }
if (!isDeepStrictEqual(got, want)) await broke('the redirect back', { client_id: clientId, redirect_uri: redirect, device: Boolean(device) }, want, { ...got, error: t?.params?.error ?? null, status: back.status })
return { code: t.params.code, pk, redirect, b, page }
}
/// A form POST to one of the MCP issuer's endpoints.
@@ -129,6 +141,223 @@ async function challenged(what, access) {
if (r.http !== 401 || c?.error !== 'invalid_token' || c?.resource_metadata !== names().prm) await broke(`/mcp with ${what}`, {}, { http: 401, challenge: { error: 'invalid_token', resource_metadata: names().prm } }, { http: r.http, challenge: r.challenge, body: r.body })
}
/// The refresh grant at `/oauth/mcp/token` (spec/OAUTH-MCP.md, "The token
/// endpoint").
const refreshWith = (clientId, refresh) => post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: clientId, refresh_token: refresh })
/// A session signed in as the hosted apps and its code exchanged, held to
/// the spec: `{access, refresh, b, page}`, `b` the browser it signed in on.
async function session(what, acct, { scope = SCOPE, device = null } = {}) {
const s = await signIn(acct, HOSTED, HOSTED_REDIRECT, scope, device)
return { ...(await held(`token: code (${what})`, await exchange(HOSTED, s), acct, true)), b: s.b, page: s.page }
}
/// The access token works at the MCP endpoint: `server_get_session` is the
/// account's (spec/OAUTH-MCP.md, "Tokens at the MCP endpoint").
async function calls(what, acct, access) {
const me = await toolCall('server_get_session', {}, `Bearer ${access}`)
if (me.http !== 200 || me.result?.isError !== false || me.result?.structuredContent?.did !== didOf(cand, acct)) await broke(`/mcp with ${what}: server_get_session`, {}, { http: 200, did: '<the account>' }, me)
return me
}
/// The session ended: its access token the `invalid_token` challenge at
/// `/mcp`, its refresh token `400 invalid_grant` (spec/OAUTH-MCP.md, "The
/// token endpoint", "Tokens at the MCP endpoint").
async function ended(what, s) {
await challenged(`the access token of ${what}`, s.access)
const r = await refreshWith(HOSTED, s.refresh)
if (r.status !== 400 || r.body?.error !== 'invalid_grant') await broke(`token: the refresh token of ${what}`, {}, '400 invalid_grant', { status: r.status, body: r.body })
}
/// A code approved and not yet exchanged, refused: `400 invalid_grant`.
async function codeRefused(what, approval) {
const r = await exchange(HOSTED, approval)
if (r.status !== 400 || r.body?.error !== 'invalid_grant') await broke(`token: ${what}`, {}, '400 invalid_grant', { status: r.status, body: r.body })
}
const basic = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`
/// The admin's auth on each side.
const admin = (side) => (side === ref ? basic('admin', ADMIN_PASSWORD) : cand.admin)
/// The admin applies or lifts the account's takedown on both sides alike,
/// compared (spec/LIFECYCLE.md, "updateSubjectStatus").
async function takedownBoth(kind, acct, applied) {
const nsid = 'com.atproto.admin.updateSubjectStatus'
const send = async (side) => answer(await fetch(`${side.url}/xrpc/${nsid}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: admin(side) }, body: JSON.stringify({ subject: { $type: 'com.atproto.admin.defs#repoRef', did: didOf(side, acct) }, takedown: { applied } }) }))
const [a, b] = await Promise.all([ref, cand].map(send))
const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
if (!isDeepStrictEqual(na, nb)) await differ(nsid, { subject: `<did:${acct.n}>`, takedown: { applied } }, na, nb)
count(kind, a.status < 400)
}
/// activateAccount with the account's password session on both sides,
/// compared. Its `#identity` on the firehose carries the handle it has
/// (spec/LIFECYCLE.md, "The firehose").
async function activateBoth(kind, acct) {
await both(kind, 'com.atproto.server.activateAccount', { token: acct, method: 'POST' })
for (const side of [ref, cand]) acct.handles[side.name].push(acct.handles[side.name].at(-1))
}
/// The scope that lets an MCP session deactivate its account
/// (spec/OAUTH-SCOPES.md, "What each method needs").
const STATUS_SCOPE = `${SCOPE} account:status?action=manage`
/// A takedown ends every MCP session of the account at once, and every code
/// approved for it; lifted, they stay ended; and a lifting of an account not
/// down ends them too (spec/OAUTH-MCP.md, "Lifecycle and durability";
/// spec/LIFECYCLE.md, "OAuth sessions").
async function mcpTakedown() {
const acct = await createAccount({ withPassword: true })
if (!acct) return
const s = await session('before a takedown', acct)
await calls('a session before a takedown', acct, s.access)
const pending = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, s.b)
await takedownBoth('updateSubjectStatus takedown (MCP sessions)', acct, true)
await ended('a session whose account was taken down', s)
await takedownBoth('updateSubjectStatus lifting a takedown (MCP sessions)', acct, false)
await ended('a session whose account was taken down, the takedown lifted', s)
await codeRefused('a code approved before a takedown, exchanged after it is lifted', pending)
const after = await session('after a takedown is lifted', acct)
await calls('a session after a takedown is lifted', acct, after.access)
await takedownBoth('updateSubjectStatus lifting a takedown of an account not down (MCP sessions)', acct, false)
await ended('a session whose account had a takedown lifted while not down', after)
// Its password sessions ended with them, on both sides (spec/LIFECYCLE.md,
// "updateSubjectStatus"): it carries on with new ones.
const [a, b] = await both('createSession after a takedown is lifted', 'com.atproto.server.createSession', { body: { identifier: acct.handle, password: acct.password } })
if (a.status === 200 && b.status === 200) {
acct.sides.reference = { ...acct.sides.reference, token: a.body.accessJwt, refresh: a.body.refreshJwt }
acct.sides.server = { ...acct.sides.server, token: b.body.accessJwt, refresh: b.body.refreshJwt }
}
count('mcp oauth: a takedown, applied and lifted', true)
}
/// Signing out of the device the session signed in on ends no session: it
/// signs the account out of that device alone (spec/OAUTH.md, "The API").
/// A deactivation by the account's password session ends no MCP session,
/// which answers as that session does, and refreshes, but ends the codes
/// approved for it; one with an MCP session's own token ends every MCP
/// session of the account, after its activation too (spec/OAUTH-MCP.md,
/// "Lifecycle and durability"; spec/LIFECYCLE.md, "OAuth sessions").
async function mcpDeactivations() {
const acct = await createAccount({ withPassword: true })
if (!acct) return
let m1 = await session('before a deactivation', acct)
const pending = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, m1.b)
const out = await m1.b.api(m1.page, '/sign-out', { did: didOf(cand, acct) })
if (out.status !== 200 || out.json?.success !== true) await broke('sign-out on the page', {}, { status: 200, body: { success: true } }, { status: out.status, body: out.json })
await calls('a session whose account signed out of the device it signed in on', acct, m1.access)
count('mcp oauth: sign-out', true)
await both('deactivateAccount with its password session (MCP sessions)', 'com.atproto.server.deactivateAccount', { token: acct, body: {} })
const password = `Bearer ${tokenOf(cand, acct)}`
const record = { $type: 'com.example.note', text: 'not written: the account is deactivated' }
for (const [tool, args, whole] of [['server_check_account_status', {}, true], ['repo_create_record', { repo: didOf(cand, acct), collection: 'com.example.note', record }, false]]) {
const view = (r) => ({ http: r.http, isError: r.result?.isError ?? null, answer: whole ? r.result?.structuredContent ?? null : r.result?.structuredContent?.error ?? null })
const [mine, theirs] = [view(await toolCall(tool, args, `Bearer ${m1.access}`)), view(await toolCall(tool, args, password))]
if (!isDeepStrictEqual(mine, theirs)) await broke(`${tool} with an MCP session of a deactivated account, as with its password session`, { tool }, theirs, mine)
}
const me = await toolCall('server_get_session', {}, `Bearer ${m1.access}`)
const sc = me.result?.structuredContent
if (me.result?.isError !== false || sc?.did !== didOf(cand, acct) || sc?.active !== false || sc?.status !== 'deactivated') await broke('server_get_session with a session of a deactivated account', {}, { did: '<the account>', active: false, status: 'deactivated' }, me)
m1 = { ...m1, ...(await held('token: refresh, the account deactivated by its password session', await refreshWith(HOSTED, m1.refresh), acct, true)) }
await calls('a session refreshed while its account is deactivated', acct, m1.access)
await codeRefused('a code approved before a deactivation', pending)
await activateBoth('activateAccount after a deactivation by its password session', acct)
await calls('a session after its account is activated again', acct, m1.access)
count('mcp oauth: a deactivation by the password session', true)
const m2 = await session('with account:status?action=manage', acct, { scope: STATUS_SCOPE })
const pending2 = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, m2.b)
const d = await toolCall('server_deactivate_account', {}, `Bearer ${m2.access}`)
if (d.http !== 200 || d.result?.isError !== false) await broke('server_deactivate_account with an MCP session\'s token', { scope: STATUS_SCOPE }, 'the account deactivated', d)
// The reference's account deactivated too, so that both stay alike.
const r = await xrpcHttp(ref, 'com.atproto.server.deactivateAccount', { token: acct, body: {} })
if (r.status !== 200) await fail(ref, 'deactivateAccount, as the server\'s account was through MCP', {}, 200, r)
await ended('the session whose token deactivated its account', m2)
await ended('a session whose account another session deactivated', m1)
await codeRefused('a code approved before a deactivation with an MCP token', pending2)
await activateBoth('activateAccount after a deactivation with an MCP token', acct)
await ended('the session whose token deactivated its account, after its activation', m2)
await ended('a session whose account another session deactivated, after its activation', m1)
count('mcp oauth: a deactivation with an MCP token', true)
}
/// deleteAccount ends every MCP session of the account (spec/OAUTH-MCP.md,
/// "Lifecycle and durability"; spec/LIFECYCLE.md, "deleteAccount", "OAuth
/// sessions"). The account deleted is the run's no longer.
async function mcpDeletion() {
const acct = await createAccount({ withPassword: true })
if (!acct) return
const s = await session('before deleteAccount', acct)
await both('requestAccountDelete (MCP sessions)', 'com.atproto.server.requestAccountDelete', { token: acct, method: 'POST' })
const sent = await checkMail('requestAccountDelete (MCP sessions)', { account: `<did:${acct.n}>` })
const token = (side) => sent[side.name].filter((m) => m.to === acct.email.toLowerCase() && m.kind === 'deleteAccount').at(-1)?.token
if (!token(cand)) return void (await broke('requestAccountDelete', {}, 'a deleteAccount email', sent.server))
const [a, b] = await both('deleteAccount (MCP sessions)', 'com.atproto.server.deleteAccount', (side) => ({ body: { did: didOf(side, acct), password: acct.password, token: token(side) } }))
// It is the last account made, so no other's number is given again.
if (a.status === 200 && b.status === 200) accounts.splice(accounts.indexOf(acct), 1)
await ended('a session whose account was deleted', s)
count('mcp oauth: deleteAccount', true)
}
/// Whether checkMcpOAuth published the clients' documents, which the
/// sessions made before a restart sign in with.
let published = false
/// What `mcpBeforeCrash` made, for `mcpAfterCrash`.
let beforeRestart = null
/// Before the server is killed, on an account with a password and without
/// the email factor, as the hosted apps: a session refreshed, the access
/// token it replaced, a code approved and not exchanged, and a session
/// ended by revocation or by its replaced refresh token sent again; all on
/// one device, the account signed in on it (spec/OAUTH-MCP.md, "Lifecycle
/// and durability"; spec/OAUTH.md, "Durability").
export async function mcpBeforeCrash() {
beforeRestart = null
const some = accounts.filter((a) => a.password)
if (!published || !some.length) return
const acct = pick(some)
const now = await xrpcHttp(cand, 'com.atproto.server.getSession', { token: acct })
if (now.status !== 200 || now.body?.emailAuthFactor === true) return
const first = await session('before a restart', acct)
const live = await held('token: refresh, before a restart', await refreshWith(HOSTED, first.refresh), acct, true)
const code = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, first.b)
const how = pick(['revoked', 'ended by a replay'])
let gone = await session(`to be ${how} before a restart`, acct, { device: first.b })
if (how === 'revoked') {
const r = await post('/oauth/mcp/revoke', { client_id: HOSTED, token: gone.refresh })
if (r.status !== 200) await broke('revoke, before a restart', {}, 200, { status: r.status, body: r.body })
} else {
const replaced = gone.refresh
gone = await held('token: refresh, before a replay', await refreshWith(HOSTED, replaced), acct, true)
const replay = await refreshWith(HOSTED, replaced)
if (replay.status !== 400 || replay.body?.error !== 'invalid_grant') await broke('a replaced refresh token, before a restart', {}, '400 invalid_grant', { status: replay.status, body: replay.body })
}
beforeRestart = { acct, device: first.b, replaced: first.access, live, code, how, gone }
}
/// After the restart, what was made before it is as it was: the replaced
/// access token challenged, the refreshed session calling a tool and
/// refreshing, the code exchanged, the ended session still ended, and the
/// account still signed in on the device, which consents alone
/// (spec/OAUTH-MCP.md, "Lifecycle and durability"; spec/OAUTH.md,
/// "Durability").
export async function mcpAfterCrash() {
const s = beforeRestart
beforeRestart = null
if (!s) return
const { acct } = s
await challenged('an access token replaced before a restart', s.replaced)
await calls('a session refreshed before a restart', acct, s.live.access)
await held('token: refresh, after a restart', await refreshWith(HOSTED, s.live.refresh), acct, true)
const fromCode = await held('token: code approved before a restart', await exchange(HOSTED, s.code), acct, true)
await calls('a session from a code approved before a restart', acct, fromCode.access)
await ended(`a session ${s.how} before a restart`, s.gone)
const again = await session('on a device signed in on before a restart', acct, { device: s.device })
await calls('a session consented to on a device signed in on before a restart', acct, again.access)
count('mcp oauth: sessions across a restart', true)
}
/// The authorization request with one thing wrong after its client and
/// redirect URI: a redirect with the error, `iss` and `state`
/// (spec/OAUTH-MCP.md, "The authorization request").
@@ -156,6 +385,7 @@ export async function checkMcpOAuth() {
const acct = accounts.find((a) => a.password)
if (!acct) return
publish()
published = true
const { origin, resource, issuer, prm } = names()
// The challenge, and a tool that needs no account (spec/OAUTH-MCP.md,
@@ -223,11 +453,11 @@ export async function checkMcpOAuth() {
// Refresh: new tokens, the old access token challenged; the old refresh
// token refused, ending the session (spec/OAUTH-MCP.md, "The token
// endpoint").
const refreshed = await held('token: refresh', await post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: HOSTED, refresh_token: hosted.refresh }), acct, true)
const refreshed = await held('token: refresh', await refreshWith(HOSTED, hosted.refresh), acct, true)
await challenged('an access token replaced', hosted.access)
const works = await toolCall('server_get_session', {}, `Bearer ${refreshed.access}`)
if (works.result?.isError !== false) await broke('/mcp with the refreshed token', {}, 'the session', works)
const again = await post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: HOSTED, refresh_token: hosted.refresh })
const again = await refreshWith(HOSTED, hosted.refresh)
if (again.status !== 400 || again.body?.error !== 'invalid_grant') await broke('a replaced refresh token', {}, '400 invalid_grant', { status: again.status, body: again.body })
await challenged('the token of a session ended', refreshed.access)
count('mcp oauth: refresh', true)
@@ -290,4 +520,12 @@ export async function checkMcpOAuth() {
await refusedByPage('a document naming another client_id', OTHER_ID, HOSTED_REDIRECT)
await refusedByPage('a document with no token_endpoint_auth_method', NO_AUTH_METHOD, HOSTED_REDIRECT)
await refusedByPage('a redirect URI the document does not name', HOSTED, `${HOST}/elsewhere`)
// MCP sessions through their accounts' changes. A deletion leaves its
// account's events on a live firehose and takes them out of a replay,
// which the firehose's checks here do not model: with --firehose, no
// account is deleted.
await mcpTakedown()
await mcpDeactivations()
if (!FIREHOSE) await mcpDeletion()
}
harness/checks/oauth-scopes.mjs+28−0
@@ -12,6 +12,8 @@ import { COLLECTIONS, RKEYS, below, chance, goodRecord, pick, rand } from '../li
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 { fail } from '../lib/plc.mjs'
import { count } from '../lib/report.mjs'
import { issuer } from '../lib/server.mjs'
import { DPOP_FAULTS, compare, dpops, freshNonce, handleOf, login, pickSession, sides } from './oauth.mjs'
@@ -384,6 +386,32 @@ export async function oauthScopedEdges(acct) {
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 }))
}
await oauthSpaceScope(acct)
}
/// `space:` scopes a client may ask for; none is a permission the server
/// keeps.
const SPACE_SCOPES = ['space:com.example.forum', 'space:com.example.forum?action=read', 'space:com.example.forum?authority=self&skey=*', 'space:com.example.forum?collection=com.example.post&action=create', 'space:*']
/// A client asking for `atproto` and a `space:` scope signs in: its
/// token's `scope` holds no `space:` permission, compared with the
/// reference as the token answer is (spec/OAUTH.md, the permissions it
/// keeps); then a space method called with that token and a good proof
/// refuses it as a token the server did not give out, `400 InvalidToken`,
/// held to the spec on the server alone, as the reference serves no space
/// method (spec/OAUTH-SCOPES.md, "Spaces", "Which methods take a token").
async function oauthSpaceScope(acct) {
const client = { scope: `atproto ${pick(SPACE_SCOPES)}`, redirects: [REDIRECT] }
const s = await login(acct, { client, reject: false, narrow: false, whole: true })
if (!s) return
const request = { client: client.scope, scope: s.scope }
if (String(s.scope).split(' ').some((t) => t.startsWith('space'))) await fail(ref, 'a token with a space: permission (spec/OAUTH.md: not a permission kept)', request, 'no space: permission', s.scope)
const nsid = 'com.atproto.space.listSpaces'
const r = await send(cand, nsid, {}, { dpop: s.dpop[cand.name], accessToken: s.tokens[cand.name].access })
const want = { status: 400, error: 'InvalidToken' }
const got = { status: r.status, error: r.body?.error ?? null }
if (got.status !== want.status || got.error !== want.error) await fail(cand, `${nsid} with an OAuth token (spec/OAUTH-SCOPES.md, "Spaces")`, { nsid, ...request }, want, got)
count('scopes: a space method with an OAuth token, on the server alone', false)
}
// What checks/permission-sets.mjs shares with these checks.
harness/checks/operations.mjs+5−1
@@ -688,7 +688,10 @@ async function lifecycle() {
{ PDS_BLOBSTORE_S3_BUCKET: keep.PDS_BLOBSTORE_S3_BUCKET ?? 'b', PDS_BLOBSTORE_S3_ACCESS_KEY_ID: 'k', PDS_BLOBSTORE_S3_SECRET_ACCESS_KEY: '' },
elsewhere,
]
for (const bad of [{ PDS_LOG_LEVEL: 'loud' }, { OTEL_EXPORTER_OTLP_PROTOCOL: 'grpc' }, { OTEL_EXPORTER_OTLP_PROTOCOL: 'http/json' }, { PDS_METRICS_PORT: 'many' }, { PDS_METRICS_PORT: keep.PDS_PORT }, { PDS_BIND_ADDRESS: 'localhost' }, { PDS_BIND_ADDRESS: '[::1]' }, { PDS_BIND_ADDRESS: '203.0.113.1' }, { PDS_LEXICON_AUTHORITY_DID: 'not-a-did' }, ...blobstore]) {
// One of the two SMTP variables without the other, the other unset: exit
// 1, with `pds: ` and why on standard error (spec/EMAIL.md, "SMTP").
const smtpHalves = [{ PDS_EMAIL_SMTP_URL: 'smtp://127.0.0.1:2525', PDS_EMAIL_FROM: undefined }, { PDS_EMAIL_FROM: 'mailer@pds-harness.test', PDS_EMAIL_SMTP_URL: undefined }]
for (const bad of [{ PDS_LOG_LEVEL: 'loud' }, { OTEL_EXPORTER_OTLP_PROTOCOL: 'grpc' }, { OTEL_EXPORTER_OTLP_PROTOCOL: 'http/json' }, { PDS_METRICS_PORT: 'many' }, { PDS_METRICS_PORT: keep.PDS_PORT }, { PDS_BIND_ADDRESS: 'localhost' }, { PDS_BIND_ADDRESS: '[::1]' }, { PDS_BIND_ADDRESS: '203.0.113.1' }, { PDS_LEXICON_AUTHORITY_DID: 'not-a-did' }, ...blobstore, ...smtpHalves]) {
// Each start with this one bad value alone, not the last one's too.
for (const k of Object.keys(server.env)) delete server.env[k]
Object.assign(server.env, keep, bad)
@@ -699,6 +702,7 @@ async function lifecycle() {
if (exited?.code !== 1) await broke('start', bad, 'exit 1, with why on standard error', exited ?? 'it served')
const life = readLog().at(-1)
if (!life.stderr.trim()) await broke('start', bad, 'why it exited, on standard error', 'nothing')
if (smtpHalves.includes(bad) && !/^pds: \S/m.test(life.stderr)) await broke('start', { ...bad, unset: Object.keys(bad)[1] }, '`pds: ` and why, on standard error (spec/EMAIL.md, "SMTP")', life.stderr.slice(0, 300))
count(`a start with ${Object.keys(bad)[0]} ${Object.values(bad)[0]}`, false)
}
for (const k of Object.keys(server.env)) delete server.env[k]
harness/lib/adapters/spec-pds.mjs+8−2
@@ -1,6 +1,7 @@
// spec-pds: the harness as it always ran it, a process given spec-pds's
// `PDS_*` environment (compare.mjs's header), its mail read from
// PDS_DEV_MAIL_DIR, its traces and metrics where the harness reads them.
// PDS_DEV_MAIL_DIR and sent to the harness's SMTP server (lib/smtp.mjs),
// its traces and metrics where the harness reads them.
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -10,6 +11,7 @@ import { ADMIN_PASSWORD, serverEnv } from '../env.mjs'
import { noteSecret } from '../observe.mjs'
import { root, sh } from '../impls.mjs'
import { basic, child } from './common.mjs'
import { startSmtp } from '../smtp.mjs'
/// The server's PDS_DEV_MAIL_DIR: empty, the harness's own.
const MAIL_DIR = mkdtempSync(join(tmpdir(), 'pds-mail-'))
@@ -60,7 +62,11 @@ export default {
return { version: (await sh(`${root}target/release/pds`, ['--version'])) || '0.0.0 (workspace)', source: `this repository at ${await sh('git', ['rev-parse', '--short', 'HEAD'], root)}`, config: 'compare.mjs\'s header: every setting the harness has' }
},
async start(o) {
const { env, rotationKey } = await serverEnv({ port: o.port, dataDir: o.dataDir, plc: o.plc, recoveryKey: o.recoveryKey, crawlers: o.crawlers, appView: o.appView, clientFetch: o.clientFetch, handles: o.handles, limits: o.limits, invites: o.invites, backfillMs: o.backfillMs, cacheBytes: o.cacheBytes, lexiconAuthority: o.lexiconAuthority, blobstore: o.blobstore })
// The SMTP server the server sends each email through, signing in with
// a user and password that must be percent-encoded in its URL
// (spec/EMAIL.md, "SMTP").
const smtp = await startSmtp({ user: 'pds harness@mail', password: 'p:ss/w%rd#1', from: 'mailer@pds-harness.test' })
const { env, rotationKey } = await serverEnv({ port: o.port, dataDir: o.dataDir, plc: o.plc, recoveryKey: o.recoveryKey, crawlers: o.crawlers, appView: o.appView, clientFetch: o.clientFetch, handles: o.handles, limits: o.limits, invites: o.invites, backfillMs: o.backfillMs, cacheBytes: o.cacheBytes, lexiconAuthority: o.lexiconAuthority, blobstore: o.blobstore, smtp })
env.PDS_DEV_MAIL_DIR = MAIL_DIR
Object.assign(env, OTEL_ENV, { PDS_METRICS_PORT: String(o.metricsPort), OTEL_EXPORTER_OTLP_ENDPOINT: o.otlp.url, OTEL_EXPORTER_OTLP_HEADERS: `x-otlp-key=${OTLP_KEY}` })
return {
harness/lib/env.mjs+8−2
@@ -41,8 +41,10 @@ export const REFERENCE_TRUSTED_PROXIES = '127.0.0.0/8,::1/128,169.254.0.0/16,fe8
/// through it (spec/IDENTITY.md, "Environment"). With `blobstore`,
/// `{url, bucket, accessKeyId, secretAccessKey, timeoutMs}`, its blobs are
/// kept in that bucket of the S3 store at `url`, path-style, with that
/// timeout for uploads and every other request (spec/BLOBS.md).
export async function serverEnv({ port, dataDir, plc, recoveryKey, crawlers, appView, clientFetch, handles, limits = false, invites = false, backfillMs, cacheBytes, lexiconAuthority, blobstore }) {
/// timeout for uploads and every other request (spec/BLOBS.md). With
/// `smtp`, `{url, from}`, it sends each email through the SMTP server at
/// `url`, from the address `from` (spec/EMAIL.md, "SMTP").
export async function serverEnv({ port, dataDir, plc, recoveryKey, crawlers, appView, clientFetch, handles, limits = false, invites = false, backfillMs, cacheBytes, lexiconAuthority, blobstore, smtp }) {
const rotation = await Secp256k1Keypair.create({ exportable: true })
const env = {
PDS_PORT: String(port),
@@ -87,5 +89,9 @@ export async function serverEnv({ port, dataDir, plc, recoveryKey, crawlers, app
PDS_BLOBSTORE_S3_REQUEST_TIMEOUT_MS: String(blobstore.timeoutMs),
})
}
if (smtp) {
env.PDS_EMAIL_SMTP_URL = smtp.url
env.PDS_EMAIL_FROM = smtp.from
}
return { env, rotationKey: rotation.did() }
}
harness/lib/mail.mjs+69−6
@@ -2,15 +2,28 @@
// reference's are caught in its process, as its mailer is about to send
// them; the server's are read as its adapter reads them (lib/adapters/):
// spec-pds writes each to PDS_DEV_MAIL_DIR, which the harness reads and
// empties.
// empties, and sends each to the harness's SMTP server (lib/smtp.mjs),
// where each is held to what the development sink recorded.
import { isDeepStrictEqual } from 'node:util'
import { cand, ref } from './processes.mjs'
import { differ } from './report.mjs'
import { smtp } from './server.mjs'
import { addressOf, decodeWords, parseMessage } from './smtp.mjs'
/// A token's form.
export const TOKEN = /^[A-Z2-7]{5}-[A-Z2-7]{5}$/
/// Each kind of email's subject (spec/EMAIL.md, "The mailer").
export const SUBJECT = {
confirmEmail: 'Email Confirmation',
updateEmail: 'Email Update Requested',
resetPassword: 'Password Reset Requested',
signInAuthFactor: 'Sign-in Confirmation',
deleteAccount: 'Account Deletion Requested',
plcOperation: 'PLC Update Operation Requested',
}
/// The reference's emails not yet taken, oldest first.
const caught = []
@@ -26,9 +39,12 @@ export function catchReferenceMail(mailer) {
/// The emails `side` sent since they were last taken, oldest first, each
/// as the server wrote it: `{to, kind, token}` if it is right. For the
/// server, what its adapter's `takeMail` answers (a promise, for some).
/// server, what its adapter's `takeMail` answers (a promise, for some);
/// what reached the SMTP server it was given, if any, is taken too, and
/// let go with them.
export function takeMail(side) {
if (side.name === ref.name) return caught.splice(0)
smtp()?.take()
return cand.takeMail()
}
@@ -38,11 +54,14 @@ const shape = (m) => (m && typeof m === 'object' && !Array.isArray(m) ? { ...m,
/// Take the emails both sides sent since they were last taken, and compare
/// them: the same addresses and kinds, in order, each `{to, kind, token}`
/// and nothing else, with a token of the form spec/EMAIL.md gives
/// (spec/EMAIL.md, "Tokens", "The mailer"). `what` and `request` say what
/// sent them. Answers `{reference, server}`, each side's emails, to use
/// their tokens.
/// (spec/EMAIL.md, "Tokens", "The mailer"). Then, with the server sending
/// through an SMTP server, hold what reached it to those (`checkSmtp`).
/// `what` and `request` say what sent them. Answers `{reference, server}`,
/// each side's emails, to use their tokens.
export async function checkMail(what, request) {
const sent = { reference: takeMail(ref), server: await takeMail(cand) }
const sent = { reference: takeMail(ref), server: await cand.takeMail() }
// After the development sink's: each email is written there before it is sent.
const wire = smtp()?.take()
const want = { to: '', kind: '', token: '<token>' }
for (const side of [ref, cand]) {
const bad = sent[side.name].map(shape).find((m) => !m || typeof m !== 'object' || !isDeepStrictEqual(Object.keys(m).sort(), Object.keys(want).sort()) || m.token !== '<token>' || typeof m.to !== 'string' || typeof m.kind !== 'string')
@@ -50,5 +69,49 @@ export async function checkMail(what, request) {
}
const [a, b] = [sent.reference.map(shape), sent.server.map(shape)]
if (!isDeepStrictEqual(a, b)) await differ(`${what}: the emails sent`, request, a, b)
if (wire) await checkSmtp(what, request, sent.server, wire)
return sent
}
/// What reached the SMTP server (lib/smtp.mjs's `take()`), held to the
/// emails the development sink recorded meanwhile, `recorded`, on the
/// server alone, as the reference's are not sent: each recorded email
/// reached it, signed in with PDS_EMAIL_SMTP_URL's user and password, sent
/// to the account's email alone, from PDS_EMAIL_FROM in the envelope and
/// in its `From`, with its kind's subject, and a body that gives the token;
/// once, unless the SMTP server refused it (then maybe tried again); and
/// nothing reached it that the sink did not record, as the sink records
/// every email, sent through SMTP or not (spec/EMAIL.md, "SMTP", "The
/// development sink").
async function checkSmtp(what, request, recorded, wire) {
const sink = smtp()
const fail = (want, got) => differ(`${what}: an email over SMTP`, request, want, got, 'held to spec/EMAIL.md ("SMTP") on the server alone: the reference\'s emails are not sent')
const problem = wire.find((m) => m.problem)
if (problem) await fail('every email sent signed in with PDS_EMAIL_SMTP_URL\'s user and password, percent-decoded', problem)
const messages = wire.filter((m) => !m.problem).map((m) => {
const { headers, text } = parseMessage(m.data)
return { ...m, headers, text }
})
const matched = new Set()
for (const m of recorded) {
const subject = SUBJECT[m.kind]
const tries = messages.filter((x) => x.text.includes(m.token))
tries.forEach((x) => matched.add(x))
const kept = { to: m.to, kind: m.kind }
if (!tries.length) await fail({ ...kept, over: 'SMTP, with the token in its body' }, 'no message with the token reached the SMTP server')
for (const x of tries) {
const got = {
envelope: { from: x.from, to: x.to },
from: (x.headers.from ?? []).map(addressOf),
to: (x.headers.to ?? []).map(addressOf),
subject: (x.headers.subject ?? []).map(decodeWords),
}
const want = { envelope: { from: sink.from, to: [m.to] }, from: [sink.from], to: [m.to], subject: [subject] }
if (!isDeepStrictEqual(got, want)) await fail({ ...kept, ...want }, got)
}
const accepted = tries.filter((x) => !x.refused).length
if (accepted > 1) await fail({ ...kept, sent: 'once' }, `${accepted} messages accepted`)
}
const stray = messages.find((x) => !matched.has(x))
if (stray) await fail('no message but the emails the development sink recorded', { from: stray.from, to: stray.to, subject: stray.headers.subject ?? null, refused: stray.refused })
}
harness/lib/server.mjs+5−0
harness/lib/services.mjs+5−3
harness/lib/smtp.mjsnew+228−0
harness/compare.mjs+6−1
harness/gates.mjs+1−1
harness/spec-coverage.mjs+11−12
spec/EMAIL.md+19−2
spec/LIMITS.md+7−3
spec/OAUTH-MCP.md+24−3
spec/OAUTH-SCOPES.md+8−1
spec/PROXY.md+3−2