~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
327 lines · 22.8 KB Raw History
// OAuth and the rate limits (spec/LIMITS.md, "OAuth access tokens"), in the --limits run:
// OAuth's endpoints, pages and metadata cost nothing and have no limits of
// their own; a call with an OAuth access token counts by its token's DID, in
// the buckets a password session's calls count in; a call refused for its
// proof, its token or a scope checked with the token costs nothing, and a
// write refused for its scope costs what a write costs; and a 429 to a call
// with the DPoP scheme. Each held to the reference.

import { isDeepStrictEqual } from 'node:util'
import { cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
import { didOf, tokenOf } from '../lib/state.mjs'
import { API, Browser, Dpop, answer, form, fresh, newKey, pkce, signInCall, target, wwwError } from '../lib/oauth.mjs'
import { ownHost } from '../lib/services.mjs'
import { RESERVABLE, createAccount, freshFront } from './accounts.mjs'
import { issuer } from '../lib/server.mjs'
import { handleOf, login } from './oauth.mjs'

const sides = () => [ref, cand]
const REDIRECT = 'http://127.0.0.1/callback'
/// A client address of its own for each check, as a proxy before the server
/// would report it, in a public range the other --limits checks do not use.
let ipSerial = 0
const freshIp = () => {
  ipSerial += 1
  return `198.18.${Math.floor(ipSerial / 250)}.${(ipSerial % 250) + 1}`
}

/// An answer as the rate limits show it: status, `error`, the RateLimit-*
/// headers, the headers `Access-Control-Expose-Headers` names (as a set),
/// and, for calls with the DPoP scheme, `DPoP-Nonce` and
/// `WWW-Authenticate`'s error. `reset` and `retry` apart: they are compared
/// to within 2 seconds.
function rlView(res) {
  const h = res.headers ?? {}
  const exposes = String(h['access-control-expose-headers'] ?? '').split(',').map((x) => x.trim().toLowerCase()).filter(Boolean).sort()
  const view = {
    status: res.status,
    error: res.status >= 400 ? (res.body?.error ?? null) : null,
    limit: h['ratelimit-limit'] ?? null,
    remaining: h['ratelimit-remaining'] ?? null,
    policy: h['ratelimit-policy'] ?? null,
    exposes,
    nonce: Boolean(h['dpop-nonce']),
    www: wwwError(h['www-authenticate']),
  }
  return { view, reset: h['ratelimit-reset'] === undefined ? null : Number(h['ratelimit-reset']), retry: h['retry-after'] === undefined ? null : Number(h['retry-after']) }
}

async function same(kind, request, a, b) {
  const [x, y] = [rlView(a), rlView(b)]
  if (!isDeepStrictEqual(x.view, y.view)) await differ(kind, request, x.view, y.view, 'rate limits with OAuth (spec/LIMITS.md)')
  for (const k of ['reset', 'retry']) {
    if ((x[k] === null) !== (y[k] === null) || (x[k] !== null && Math.abs(x[k] - y[k]) > 2)) await differ(kind, request, { [k]: x[k] }, { [k]: y[k] }, `rate limits: ${k === 'reset' ? 'RateLimit-Reset' : 'Retry-After'}, to within 2 s`)
  }
  count(`limits: ${kind}`, a.status < 400)
}

/// The same call on both sides, compared.
async function both(kind, request, send) {
  const [a, b] = await Promise.all(sides().map((side) => send(side)))
  await same(kind, request, a, b)
  return { reference: a, server: b }
}

/// `n` calls on each side, `at` at once, compared as multisets of their
/// views, as the order they land in may differ.
async function many(kind, request, n, at, send) {
  const got = { reference: [], server: [] }
  for (let i = 0; i < n; i += at) {
    const k = Math.min(at, n - i)
    const answers = await Promise.all(sides().map((side) => Promise.all(Array.from({ length: k }, (_, j) => send(side, i + j)))))
    sides().forEach((side, s) => got[side.name].push(...answers[s].map((r) => JSON.stringify(rlView(r).view))))
  }
  const sorted = (xs) => [...xs].sort()
  if (!isDeepStrictEqual(sorted(got.reference), sorted(got.server))) await differ(kind, { ...request, calls: n }, sorted(got.reference).slice(0, 20), sorted(got.server).slice(0, 20), 'rate limits with OAuth: each call')
  count(`limits: ${kind}`, true)
}

// ------------------------------------------------------------- requests

const fetchOn = async (side, path, init = {}) => {
  try {
    return await answer(await fetch(`${issuer(side)}${path}`, init))
  } catch (err) {
    return { status: 0, headers: {}, body: { error: `request failed: ${err.message}` } }
  }
}
const describeServer = (side, ip) => fetchOn(side, '/xrpc/com.atproto.server.describeServer', { headers: { 'x-forwarded-for': ip } })

/// A call to XRPC `nsid` on `side` with the account's password session.
function withPassword(side, acct, nsid, { body, bytes, type, ip }) {
  const headers = { authorization: `Bearer ${tokenOf(side, acct)}`, 'x-forwarded-for': ip }
  if (bytes) headers['content-type'] = type
  else if (body !== undefined) headers['content-type'] = 'application/json'
  return fetchOn(side, `/xrpc/${nsid}`, { method: body === undefined && !bytes ? 'GET' : 'POST', headers, body: bytes ?? (body === undefined ? undefined : JSON.stringify(body)) })
}

/// A call to XRPC `nsid` on `side` with the OAuth session `s`'s access
/// token and a proof of the call, as `Dpop.send` makes it (`opts` bends it).
function withOAuth(side, s, nsid, { body, bytes, type, ip, ...opts }) {
  const headers = { 'x-forwarded-for': ip }
  if (bytes) headers['content-type'] = type
  else if (body !== undefined) headers['content-type'] = 'application/json'
  const dpop = opts.dpop ?? s.dpop[side.name]
  return dpop.send(`${issuer(side)}/xrpc/${nsid}`, { method: body === undefined && !bytes ? 'GET' : 'POST', headers, body: bytes ?? (body === undefined ? undefined : JSON.stringify(body)), accessToken: opts.accessToken ?? s.tokens[side.name].access, retry: opts.retry ?? true, proofOpts: opts.proofOpts ?? {}, dpop: opts.header })
}

/// A new account with a password on both sides, and an OAuth session of it
/// for each scope given, asked whole, through OAUTH.md's flow. Null if the
/// account's handle differs between the sides or it cannot sign in.
async function accountWithSessions(scopes) {
  for (let tries = 0; tries < 4; tries++) {
    const acct = await createAccount({ withPassword: true })
    if (!acct || !handleOf(acct)) continue
    const sessions = []
    for (const scope of scopes) {
      let s = null
      for (let i = 0; i < 4 && !s; i++) s = await login(acct, { client: { scope, redirects: [REDIRECT] }, whole: true, reject: false, narrow: false, newDevice: true })
      if (!s) break
      sessions.push(s)
    }
    if (sessions.length === scopes.length) return { acct, sessions }
  }
  return null
}

// ---------------------------------------------------------------- checks

/// OAuth's endpoints, its pages and their API, and its metadata from one
/// address: no limit of their own, no headers, nothing of `global`; past
/// 3000 PARs, still none; then `describeServer` from that address
/// (spec/LIMITS.md, "OAuth access tokens"; spec/OAUTH.md, "Rate limits").
export async function oauthEndpointsUnlimited() {
  const ip = freshIp()
  const xff = { 'x-forwarded-for': ip }
  const paths = [
    ['/oauth/par', { method: 'POST', ...form({}), headers: { ...form({}).headers, ...xff } }],
    ['/oauth/token', { method: 'POST', ...form({ client_id: 'http://localhost', grant_type: 'refresh_token', refresh_token: 'x' }), headers: { ...form({}).headers, ...xff } }],
    ['/oauth/revoke', { method: 'POST', ...form({}), headers: { ...form({}).headers, ...xff } }],
    ['/oauth/authorize', { headers: xff }],
    ['/oauth/authorize/redirect', { headers: xff }],
    [`${API}/sign-in`, { method: 'POST', headers: xff }],
    ['/oauth/jwks', { headers: xff }],
    ['/.well-known/oauth-authorization-server', { headers: xff }],
    ['/.well-known/oauth-protected-resource', { headers: xff }],
  ]
  for (const [path, init] of paths) await many(`${init.method ?? 'GET'} ${path}, 50 from one address`, { path, ip }, 50, 25, (side) => fetchOn(side, path, init))
  const [path, init] = paths[0]
  await many('POST /oauth/par, 3100 from one address', { path, ip }, 3100, 100, (side) => fetchOn(side, path, init))
  await both('describeServer after OAuth\'s endpoints', { ip }, (side) => describeServer(side, ip))
}

/// The account-keyed limits with OAuth tokens: writes, uploads and handle
/// changes made with a password session and with OAuth tokens count in one
/// bucket; one refused for a scope checked with the token costs nothing,
/// and a write refused for its scope costs a write's points
/// (spec/LIMITS.md, "OAuth access tokens").
export async function oauthAccountBuckets() {
  const got = await accountWithSessions(['atproto transition:generic', 'atproto identity:handle blob:text/plain', 'atproto repo:com.example.todo'])
  if (!got) return
  const { acct, sessions: [generic, handleAndBlob, narrow] } = got
  const run = freshFront()
  const record = (i) => ({ $type: 'com.example.note', text: `oauth limits ${run} ${i}` })
  const batch = (j) => ({ repo: acct.handle, writes: Array.from({ length: 200 }, (_, i) => ({ $type: 'com.atproto.repo.applyWrites#create', collection: 'com.example.note', rkey: `ol${run}-${j}-${i}`, value: record(i) })) })
  // Writes: 2400 points by password, so the hour's bucket shows; then OAuth.
  for (let j = 0; j < 4; j++) {
    const ip = freshIp()
    await both(`applyWrites of 200 creates by password, ${j + 1}`, { by: 'password' }, (side) => withPassword(side, acct, 'com.atproto.repo.applyWrites', { body: batch(j), ip }))
  }
  const create = (s, collection = 'com.example.note') => (side) => withOAuth(side, s, 'com.atproto.repo.createRecord', { body: { repo: didOf(side, acct), collection, record: { ...record(collection), $type: collection } }, ip: freshIp() })
  await both('createRecord with an OAuth token', { by: 'transition:generic' }, create(generic))
  await both('createRecord refused for its scope', { by: 'repo:com.example.todo' }, create(narrow))
  await both('applyWrites refused for its scope', { by: 'repo:com.example.todo' }, (side) => withOAuth(side, narrow, 'com.atproto.repo.applyWrites', { body: { ...batch(9), writes: batch(9).writes.slice(0, 2) }, ip: freshIp() }))
  await both('createRecord by password after', { by: 'password' }, (side) => withPassword(side, acct, 'com.atproto.repo.createRecord', { body: { repo: acct.handle, collection: 'com.example.note', record: record('after') }, ip: freshIp() }))
  // Uploads.
  const bytes = (i) => new TextEncoder().encode(`spec-pds oauth limits ${run} ${i}`)
  await both('uploadBlob by password', { by: 'password' }, (side) => withPassword(side, acct, 'com.atproto.repo.uploadBlob', { bytes: bytes(1), type: 'text/plain', ip: freshIp() }))
  await both('uploadBlob with an OAuth token', { by: 'blob:text/plain' }, (side) => withOAuth(side, handleAndBlob, 'com.atproto.repo.uploadBlob', { bytes: bytes(2), type: 'text/plain', ip: freshIp() }))
  await both('uploadBlob refused for its scope', { by: 'repo:com.example.todo' }, (side) => withOAuth(side, narrow, 'com.atproto.repo.uploadBlob', { bytes: bytes(3), type: 'text/plain', ip: freshIp() }))
  await both('uploadBlob by password after', { by: 'password' }, (side) => withPassword(side, acct, 'com.atproto.repo.uploadBlob', { bytes: bytes(4), type: 'text/plain', ip: freshIp() }))
  // Handle changes, to a reserved handle, which changes nothing.
  const reserved = () => ({ handle: `${RESERVABLE[0]}.test` })
  await both('updateHandle by password', { by: 'password' }, (side) => withPassword(side, acct, 'com.atproto.identity.updateHandle', { body: reserved(), ip: freshIp() }))
  await both('updateHandle with an OAuth token', { by: 'identity:handle' }, (side) => withOAuth(side, handleAndBlob, 'com.atproto.identity.updateHandle', { body: reserved(), ip: freshIp() }))
  await both('updateHandle refused for its scope', { by: 'transition:generic' }, (side) => withOAuth(side, generic, 'com.atproto.identity.updateHandle', { body: reserved(), ip: freshIp() }))
  await both('updateHandle by password after', { by: 'password' }, (side) => withPassword(side, acct, 'com.atproto.identity.updateHandle', { body: reserved(), ip: freshIp() }))
}

/// Calls refused for their proof, their token or a scope checked with the
/// token cost nothing of `global`; a call that passes them does
/// (spec/LIMITS.md, "OAuth access tokens").
export async function oauthRefusedFree() {
  const got = await accountWithSessions(['atproto repo:com.example.todo'])
  if (!got) return
  const [s] = got.sessions
  const ip = freshIp()
  const call = (kind, nsid, opts = {}) => both(kind, { nsid, ip }, (side) => withOAuth(side, s, nsid, { ip, ...opts }))
  await both('describeServer before refused OAuth calls', { ip }, (side) => describeServer(side, ip))
  await call('getSession, a proof of another method', 'com.atproto.server.getSession', { proofOpts: { over: { htm: 'POST' } }, retry: false })
  await call('getSession, a proof without a nonce', 'com.atproto.server.getSession', { dpop: new Dpop(s.key), retry: false })
  await call('getSession, a token never given', 'com.atproto.server.getSession', { accessToken: 'garbage' })
  await call('getSession, no proof', 'com.atproto.server.getSession', { header: null })
  await call('listAppPasswords, never allowed to OAuth', 'com.atproto.server.listAppPasswords')
  await call('getAccountInviteCodes, never allowed to OAuth', 'com.atproto.server.getAccountInviteCodes')
  await call('uploadBlob refused for its scope', 'com.atproto.repo.uploadBlob', { bytes: new TextEncoder().encode('x'), type: 'text/plain' })
  await both('describeServer after refused OAuth calls', { ip }, (side) => describeServer(side, ip))
  await call('getSession with an OAuth token', 'com.atproto.server.getSession')
  await both('describeServer after an OAuth call', { ip }, (side) => describeServer(side, ip))
}

/// `global` past, with an OAuth token: 3000 getSessions from one address,
/// then the 3001st, and one refused for its proof; then a call forwarded,
/// with a token never given, to a did:web of the check's own: `429` on
/// both sides, with nothing fetched of that did:web (spec/LIMITS.md,
/// "Rate limits", "When", "OAuth access tokens"; spec/PROXY.md, "The
/// target"). Before `global` is past, the same call from another address
/// pays its point first, as a path not served.
export async function oauthGlobalLimit() {
  const got = await accountWithSessions(['atproto'])
  if (!got) return
  const [s] = got.sessions
  const ip = freshIp()
  const hosts = { reference: await ownHost(), server: await ownHost() }
  const forward = (side, from) => s.dpop[side.name].send(`${issuer(side)}/xrpc/com.example.forwarded.thing`, { headers: { 'x-forwarded-for': from, 'atproto-proxy': `${hosts[side.name].did}#x` }, accessToken: 'garbage' })
  await both('a call forwarded to a did:web with a DPoP token never given', { target: '<a did:web of its own>#x' }, (side) => forward(side, freshIp()))
  for (const h of Object.values(hosts)) h.requests.splice(0)
  await many('getSession with an OAuth token, 3000', { ip }, 3000, 50, (side) => withOAuth(side, s, 'com.atproto.server.getSession', { ip }))
  await both('getSession with an OAuth token, the 3001st', { ip }, (side) => withOAuth(side, s, 'com.atproto.server.getSession', { ip }))
  await both('getSession refused for its proof, past global', { ip }, (side) => withOAuth(side, s, 'com.atproto.server.getSession', { ip, proofOpts: { over: { htm: 'POST' } }, retry: false }))
  await both('a call forwarded to a did:web with a DPoP token never given, past global', { ip, target: '<a did:web of its own>#x' }, (side) => forward(side, ip))
  for (const side of sides()) {
    const fetched = hosts[side.name].requests
    if (fetched.length) await differ(`the ${side.name}'s forwarded call past global`, { ip, target: '<a did:web of its own>#x' }, 'nothing fetched of its target: the call is over its limit before its target is resolved', fetched, 'spec/LIMITS.md, "When"')
    await hosts[side.name].close()
  }
}

// ------------------------------------------------- the server alone

/// The server failing a rule of spec/OAUTH.md that the reference has no
/// counterpart for (its "Where the reference departs" rows).
const broke = (what, request, want, got) => differ(`the server's ${what}`, request, want, got, 'spec/OAUTH.md, held to the spec alone')

/// An account with a password on the server alone.
async function serverAccountWithPassword() {
  const front = freshFront()
  const input = { handle: `${front}.test`, email: `${front}@example.com`, password: `pw-${front}` }
  const r = await fetchOn(cand, '/xrpc/com.atproto.server.createAccount', { method: 'POST', headers: { 'content-type': 'application/json', 'x-forwarded-for': freshIp() }, body: JSON.stringify(input) })
  if (r.status !== 200) await broke('createAccount', { handle: input.handle }, 200, r)
  return { ...input, did: r.body.did }
}

/// A sign-in through OAuth's flow on the server alone, with a loopback
/// client of `scope`: PAR, the page, sign-in, consent, the redirect and the
/// code exchange. Answers `{dpop, access, refresh, clientId}`.
export async function serverSession(acct, scope = 'atproto transition:generic') {
  const redirect = 'http://127.0.0.1/callback'
  const clientId = `http://localhost?scope=${encodeURIComponent(scope)}&redirect_uri=${encodeURIComponent(redirect)}`
  const dpop = new Dpop(await newKey())
  const pk = pkce()
  const p = form({ client_id: clientId, response_type: 'code', redirect_uri: redirect, scope, state: fresh(), code_challenge: pk.challenge, code_challenge_method: 'S256' })
  const parred = await dpop.send(`${issuer(cand)}/oauth/par`, { method: 'POST', headers: p.headers, body: p.body })
  if (parred.status !== 201) return void (await broke('PAR', { scope }, 201, parred))
  const page = `${issuer(cand)}/oauth/authorize?client_id=${encodeURIComponent(clientId)}&request_uri=${encodeURIComponent(parred.body.request_uri)}`
  const b = new Browser()
  await b.navigate(page)
  const si = await b.api(page, '/sign-in', { locale: 'en', identifier: acct.handle, password: acct.password, remember: true })
  if (si.status !== 200) return void (await broke('sign-in', { identifier: acct.handle }, 200, { status: si.status, body: si.json }))
  const c = await b.api(page, '/consent', { did: si.json.account.did })
  const back = await b.navigate(c.json.url, { site: 'same-origin', referer: page })
  const code = target(back.headers.location)?.params?.code
  const t = form({ grant_type: 'authorization_code', client_id: clientId, redirect_uri: redirect, code, code_verifier: pk.verifier })
  const tok = await dpop.send(`${issuer(cand)}/oauth/token`, { method: 'POST', headers: t.headers, body: t.body })
  if (tok.status !== 200) return void (await broke('token', { grant_type: 'authorization_code' }, 200, tok))
  return { dpop, access: tok.body.access_token, refresh: tok.body.refresh_token, clientId }
}

/// OAuth's sign-in in the login limits (spec/OAUTH.md, "The API";
/// spec/LIMITS.md, "Rate limits"): 20 wrong passwords by createSession and
/// 10 by the sign-in, for one identifier from one address, each refused for
/// the password; then the right one by the sign-in is `429`, with
/// Retry-After, and by createSession `429 RateLimitExceeded`; the
/// identifier in upper case, and another address, are other keys. The
/// reference has no such limit (probed: 40 wrong sign-ins, each `400`).
export async function oauthSignInLimit() {
  const acct = await serverAccountWithPassword()
  const ip = freshIp()
  const session = (password, from = ip, identifier = acct.handle) => fetchOn(cand, '/xrpc/com.atproto.server.createSession', { method: 'POST', headers: { 'content-type': 'application/json', 'x-forwarded-for': from }, body: JSON.stringify({ identifier, password }) })
  const signIn = (password, from = ip, identifier = acct.handle) => signInCall(issuer(cand), { locale: 'en', identifier, password }, { ip: from })
  const wrong = [...(await Promise.all(Array.from({ length: 20 }, () => session('wrong')))).map((r) => [r.status, r.body?.error]), ...(await Promise.all(Array.from({ length: 10 }, () => signIn('wrong')))).map((r) => [r.status, r.json?.error])]
  const odd = wrong.filter(([st]) => st !== 400 && st !== 401)
  if (odd.length) await broke('login limits', { identifier: acct.handle, wrong: '20 by createSession, 10 by sign-in' }, 'each refused for its password', odd)
  const over = await signIn(acct.password)
  if (over.status !== 429 || over.json?.error !== 'invalid_request' || !over.headers['retry-after']) await broke('OAuth sign-in past the login limit', { identifier: acct.handle, after: '20 wrong by createSession, 10 by sign-in' }, '429 invalid_request with Retry-After', { status: over.status, error: over.json?.error, retryAfter: over.headers['retry-after'] ?? null })
  const pw = await session(acct.password)
  if (pw.status !== 429 || pw.body?.error !== 'RateLimitExceeded') await broke('createSession past the login limit', { identifier: acct.handle, after: '20 wrong by createSession, 11 by sign-in' }, '429 RateLimitExceeded', { status: pw.status, error: pw.body?.error })
  const upper = await signIn(acct.password, ip, acct.handle.toUpperCase())
  if (upper.status !== 200) await broke('OAuth sign-in, the identifier in upper case', { identifier: acct.handle.toUpperCase() }, 200, { status: upper.status, error: upper.json?.error })
  const elsewhere = await signIn(acct.password, freshIp())
  if (elsewhere.status !== 200) await broke('OAuth sign-in from another address', { identifier: acct.handle }, 200, { status: elsewhere.status, error: elsewhere.json?.error })
  count('limits: OAuth sign-in in the login limits', true)
}

/// PAR's pending requests (spec/OAUTH.md, "Pushed authorization requests",
/// step 18): 1000 kept from one address, the 1001st `429 invalid_request`,
/// and one from another address kept. The reference keeps any number
/// (probed: 600).
export async function parPending() {
  const dpop = new Dpop(await newKey())
  const ip = freshIp()
  const one = (from) => {
    const p = form({ client_id: 'http://localhost', response_type: 'code', redirect_uri: 'http://127.0.0.1/', scope: 'atproto', state: fresh(), code_challenge: pkce().challenge, code_challenge_method: 'S256' })
    return dpop.send(`${issuer(cand)}/oauth/par`, { method: 'POST', headers: { ...p.headers, 'x-forwarded-for': from }, body: p.body })
  }
  const statuses = {}
  for (let i = 0; i < 1000; i += 50) for (const r of await Promise.all(Array.from({ length: 50 }, () => one(ip)))) statuses[`${r.status} ${r.body?.error ?? ''}`.trim()] = (statuses[`${r.status} ${r.body?.error ?? ''}`.trim()] ?? 0) + 1
  if (statuses['201'] !== 1000) await broke('PAR', { kept: 'from one address', pars: 1000 }, { 201: 1000 }, statuses)
  const over = await one(ip)
  if (over.status !== 429 || over.body?.error !== 'invalid_request') await broke('PAR past 1000 pending from one address', { ip }, '429 invalid_request', { status: over.status, error: over.body?.error })
  const other = await one(freshIp())
  if (other.status !== 201) await broke('PAR from another address', {}, 201, { status: other.status, error: other.body?.error })
  count('limits: PARs pending from one address', true)
}

export const OAUTH_LIMIT_CHECKS = [oauthEndpointsUnlimited, oauthAccountBuckets, oauthRefusedFree, oauthGlobalLimit]
export const OAUTH_SERVER_CHECKS = [oauthSignInLimit, parPending]