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

A compatibility check of any PDS against the reference, area by area: the core

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:compat
compat/README.mdnew+226−0
@@ -0,0 +1,226 @@
# Compatibility with the reference PDS
`harness/compat.mjs` checks how closely a PDS behaves like the reference
(`@atproto/pds`, the version `harness/package-lock.json` pins), area by
area. It runs the core of `harness/compare.mjs`'s checks against any
implementation that has an adapter in `harness/lib/adapters.mjs`: the same
random requests to the server and to a reference beside it, their answers
compared as `compare.mjs` compares them. Unlike `compare.mjs`, it keeps going
past a difference: each area records its checks that agree and that differ,
and the first difference in full. [`RESULTS.md`](RESULTS.md) is a run against
spec-pds, zds and vlpds.
```sh
cd harness
node bench.mjs --setup # once: spec-pds's binary, and the zds and vlpds images (bench/README.md)
node compat.mjs --steps 200 --json ../compat/results.json > ../compat/tables.md
node compat.mjs --report ../compat/results.json # the tables again
```
`--impls spec-pds,zds` and `--areas oauth,records` run only some; `--seed`
draws other requests; `--jobs` is how many runs go at once (3).
spec-pds's own gates are not this: `just gates` runs `compare.mjs` as
before, every check, stopping at the first difference.
## What is checked: the map
`compare.mjs`'s checks fall in three kinds. **Core** checks compare the
server with the reference, or hold both to the same rule; they run against
every implementation. **Not yet** checks compare with the reference too,
but in areas the first cut leaves out (email, invites, rate limits, the
admin lifecycle, proxying). **spec-pds's own** checks hold spec-pds to its
own pages where the reference cannot say, or to the reference's
implementation rather than the protocol; they run only against spec-pds,
in its gates.
| check (compare.mjs step) | module | kind | area |
|---|---|---|---|
| `checkOAuthMetadata` | oauth | core (but see below) | oauth |
| `oauthLogin`, `oauthParRefused`, `oauthDpopRefused`, `oauthTokenRefused`, `oauthRevokeRefused`, `oauthRefresh`, `oauthRevoke`, `oauthGetSession`, `oauthClientLibrary` | oauth | core | oauth |
| `oauthScopedCall`, `oauthScopedRefused`, `oauthScopedEdges` | oauth-scopes | core | oauth scopes |
| `oauthClientDocument`, `oauthClientCache`, `oauthClientLogin`, `oauthAssertionRefused`, `oauthConfidentialSession` | oauth-clients | core | oauth clients |
| `oauthAuthorizeRefused` (the page, its API and its redirect endpoint, each with one thing wrong) | oauth | spec-pds's own: the reference's page API | |
| `oauthDeviceCookies` (device cookies, renewed at sign-in, 30 s of grace) | oauth | spec-pds's own: the reference's page API | |
| `oauthSilentSignIn` (a remembered device sent back at once) | oauth-clients | spec-pds's own: the reference's page API | |
| `oauthDepartures`, `oauthClientDepartures` (spec/OAUTH.md's and spec/OAUTH-CLIENTS.md's departures, held to the spec) | oauth, oauth-clients | spec-pds's own | |
| `createSession`, `getSession`, `describeServer`, `refreshSession`, `deleteSession`, `wrongTokens`, `appPasswords`, `sessionRace` | accounts, session, sessions | core | sessions |
| `createAccount`, `createAccountRefused`, `accountRace` | accounts | core | accounts |
| `createRecord`, `putRecord`, `deleteRecord`, `applyWrites`, `getRecord`, `listRecords`, `describeRepo`, `createWithTid`, `concurrent`, `oddRequests`, `crossWrites` | records, odd, accounts | core | records |
| `validatedWrite`, `duplicates`, `validatedBatch`, `validatedElsewhere` | validation | core | validation |
| `checkRepos` (getRepo verified by the reference's library, the MST root, `since`, getLatestCommit) | repository | core | repository |
| `listRepos`, `getRepoStatus`, `getBlocks`, `getGoneBlocks`, `syncGetRecord`, `noCrawlsYet`, `checkCrawls` | federation | core | sync |
| `--firehose`: `startFirehose`, `checkFirehose`, `checkReplay` | firehose | core | firehose |
| `updateHandle`, `updateHandleRefused`, `updateHandleNoToken`, `resolveHandle`, `wellKnownHandle`, `recommendedCredentials`, `handleRace`, `describeRepo` | identity, records | core | identity |
| `uploadBlob`, `blobRecord`, `getBlob`, `listBlobs` | blobs | core | blobs |
| `requestEmailConfirmation`, `confirmEmail`, `requestEmailUpdate`, `updateEmail`, `emailFactor`, `passwordReset`, `appPasswordEmail` | email | not yet: email | |
| `inviteCodes`, `--invites` | limits | not yet: invites | |
| `bigBatch`, `bodyCaps`, `appPasswordScopes`, `--limits` | limits, oauth-limits | not yet: limits; their exact numbers are spec-pds's own | |
| `loginTiming`, `oauthSignInTiming` | limits | spec-pds's own: timing floors | |
| `--lifecycle` | lifecycle | not yet: the admin lifecycle | |
| `forwarded`, `refused`, `serviceAuth`, `chatCase`, `preferences`, `readAfterWrite`, `foreignRecord`, `feedAndPush` | proxy | not yet: proxying | |
| `--commands`: `checkCommands`, `withoutAccount`, calls through MCP tools and CLI commands | commands, via | spec-pds's own (spec/COMMANDS.md) | |
| `outage`, `checkOperations` (logs, traces, metrics, health, lifecycle restarts) | operations, logging | spec-pds's own (spec/OPERATIONS.md) | |
| `--store`, `--scale` | store, scale | spec-pds's own (spec/STORE.md) | |
| `--crash-every`: `crash` (a server killed and started again on its data) | crashes | core, but not in this first cut: it needs the server killed and restarted, which the adapters can do (`server.kill`, `server.start`), and is left for later | |
Within core checks, these parts are spec-pds's own, and hold only it
(`cand.adapter.own` in the code):
| part | where | why |
|---|---|---|
| `describeServer`'s `spacesAlpha: true` | checks/session.mjs | spec/SPACES.md, not the reference |
| the genesis operation's and getRecommendedDidCredentials' `atproto_kem` key required | checks/accounts.mjs, checks/identity.mjs | spec/SPACES.md; another implementation may have one (below) |
| a blob at exactly the 5 MiB limit, and one byte past it; `describeServer`'s `blobUploadLimit` | checks/blobs.mjs | the exact number of a limit |
| PAR bodies of exactly 100 KiB and one byte past it | checks/oauth.mjs | the exact number of a limit |
| OAuth access tokens' `expires_in` of 899 to 900 | checks/oauth.mjs | spec/OAUTH.md's departure (below) |
| the authorization server metadata's `request_parameter_supported: false` | checks/oauth.mjs | spec/OAUTH.md, held to the spec |
| `GET` of the page API's `sign-in`, and `POST` of an endpoint it has not | checks/oauth.mjs | the reference's page API |
Each area runs its own steps, drawn by weight as `compare.mjs` draws its
steps, on a fresh pair of servers with two or three accounts made first.
The repository, sync and firehose areas need writes to have something to
check: `createRecord`, `putRecord`, `deleteRecord` and `applyWrites` are
drawn among their steps as supporting steps (the firehose's also
`createAccount` and `updateHandle`), and so are the first accounts in every
area. A supporting step's difference is reported apart, not counted in the
area. The repository's `checkRepos` and the firehose's checks run every
`--check-every` steps (10) and at the end; sync's crawl checks with the
first accounts, every 10 steps and at the end.
A check is one step. It goes on past what differs (in a compatibility run
`differ` in `lib/report.mjs` keeps the difference rather than ending the
run), and counts as failed if anything in it differed; one that throws (an
answer of a shape it cannot read) or takes more than 3 minutes counts as
not going on. Each area records, per check, how many ran and failed, each
thing that differed and how often, and its first difference: the request
and both answers, as `compare.mjs` prints them.
## The adapters
`harness/lib/adapters.mjs` has an adapter per implementation; `compare.mjs
--impl <name>` picks one (spec-pds by default). An adapter says how to make
the server for the run's setup, and what it is:
- `start(o)` makes the server for the setup `o` (port, data directory, PLC
directory, the reference's recovery key, crawlers, AppView, the web of
OAuth client documents, rate limits and invites on or off): the process
the harness starts, kills and starts again, the URL it calls and the one
the server's DID documents and OAuth issuer name, the rotation keys it
lists in each DID and its own as a signer, its admin's `Authorization`,
and `takeMail()`, the emails it sent.
- `unsupported` lists each setting it cannot be given, with why: the checks
that depend on one are skipped, and the report says why.
- `pageApi`, or `signIn` (below).
- `own`: whether spec-pds's own rules hold it. Only spec-pds's does.
**spec-pds**'s adapter is the harness as it always ran it: the command after
`--`, given the `PDS_*` environment `compare.mjs`'s header lists, its mail
read from `PDS_DEV_MAIL_DIR`, killed and restarted as a process.
**zds** and **vlpds** run in Docker, from the images `bench.mjs --setup`
builds and pulls (pinned in `bench/impls.json`), configured as the benchmark
configures them (`harness/lib/impls.mjs`, shared with `bench.mjs`), plus what
a compatibility run needs. The harness reaches each on a loopback port; each
reaches the harness's PLC directory, AppView and crawlers through
`host.docker.internal`. The server is the container: started, killed with a
signal, and its log followed with `docker logs`.
| setting | spec-pds | zds | vlpds |
|---|---|---|---|
| PLC directory | `PDS_PLC_URL` | `ZDS_PLC_DIRECTORY` | `VLPDS_PLC_URL`, `VLPDS_PLC_MODE=directory` |
| rotation key, the harness's | `PDS_PLC_ROTATION_KEY_HEX` | `ZDS_PLC_ROTATION_KEY` | `VLPDS_PLC_ROTATION_KEY_K256_PRIVATE_KEY_HEX` |
| the reference's recovery key | `PDS_RECOVERY_DID_KEY` | `ZDS_RECOVERY_DID_KEY` | `VLPDS_PLC_RECOVERY_DID_KEY` |
| server DID `did:web:localhost` | `PDS_HOSTNAME` | `ZDS_SERVER_DID` | `VLPDS_SERVICE_DID` |
| hostname `localhost` (requestCrawl's) | `PDS_HOSTNAME` | **no**: from `ZDS_PUBLIC_URL`, which must be the URL the harness calls (DPoP's `htu`) | **no**: the same, and it asks no relay on another host to crawl when its own is local |
| handle domains `.test`, `.example` | `PDS_HANDLE_DOMAINS` | `ZDS_HANDLE_DOMAINS` | **`.test` only**: `VLPDS_HANDLE_DOMAIN=test`; another domain needs two labels |
| admin password `admin-pass` | `PDS_ADMIN_PASSWORD` | `ZDS_ADMIN_TOKEN` | **no**: its admin token must be 32 bytes or more |
| invites off (or on) | `PDS_INVITE_REQUIRED` | `ZDS_INVITE_REQUIRED` | `VLPDS_INVITE_REQUIRED` |
| rate limits off (or on) | `PDS_RATE_LIMITS_ENABLED` | **no** general limits to turn on; full getRepo exports raised to 8 at once | `VLPDS_NO_RATE_LIMITS` |
| the harness's AppView | `PDS_BSKY_APP_VIEW_*` | `ZDS_PROXY_SERVICE_URL`, `_DID` | `VLPDS_APPVIEW` |
| the harness's crawlers | `PDS_CRAWLERS` | `ZDS_CRAWLERS` | not given (see hostname) |
| OAuth client documents from the harness's web | `PDS_OAUTH_CLIENT_FETCH` | **no**: it fetches the client_id's own https URL | **no**: the same (http only with `--dev-mode`) |
| no SSRF guard, as the reference runs | `PDS_DISABLE_SSRF_PROTECTION` | `ZDS_ALLOW_PRIVATE_FETCH` | its default for operator-set URLs |
| mail | `PDS_DEV_MAIL_DIR` | `ZDS_MAIL_PROVIDER=outbox`, read with `dev.zat.admin.listMail` | **no**: readable only with `--dev-mode` |
| consent to a narrower scope | the page API | **no**: there is no consent step | **no**: its form only takes scopes away |
The checks each "no" skips: the hostname, sync's crawl checks; the handle
domains, `describeServer`; client documents, the whole of the oauth clients
area; a narrower scope, the narrowing in `oauthLogin` (the scope asked is
granted). Mail, the admin password and rate limits are needed by no core
check.
## The OAuth sign-in hook
The harness signs in on the reference's authorization page through its page
API (`/@atproto/oauth-provider/~api/sign-in`, `consent`, `reject`, with its
CSRF cookie and device cookies), which spec-pds serves too: with spec-pds,
every step of a sign-in is compared, as before. No other server serves that
API, and the protocol leaves the sign-in step to each server. So an adapter
without `pageApi` has a hook:
```js
signIn(account, authorizeUrl, consent)
// account: {identifier, password}; authorizeUrl: the page a PAR's request_uri names;
// consent: {approve}. Answers the answer that sends the browser back to the client,
// with its code: a redirect, or a form_post page.
```
**zds**'s posts its password form (`POST /oauth/authorize`: `request_uri`,
`username`, `password`, or `deny`), which grants at once with a 303 to the
client. **vlpds**'s loads the page (its device cookie and `csrf` field),
posts `/oauth/authorize/sign-in` (`identifier`, `password`), and then
`/oauth/authorize/consent` (`did`, `action=allow` or `deny`), which
redirects to the client or answers a `form_post` page. Neither needs a
browser.
With a hook, the reference still signs in through its page API, but its
page's answers are its own, not compared; the server signs in through its
hook; and what is compared is the protocol around it: PAR, the redirect to
the client (its target, `code`, `state` and `iss`, or `error`), the token
exchange with PKCE, DPoP and its nonces, refresh, revocation, getSession and
every scoped XRPC call with the session's tokens, and the client documents'
rules. `oauthClientLibrary` signs in through the hook too, and compares only
the redirect's status of the pages.
## What other implementations are let have
[`spec/COMPAT.md`](../spec/COMPAT.md) says it, section by section, each
with why: the same things taken out of every answer as for spec-pds; the
KEM key optional (held to spec-pds's form if published); an OAuth access
token of 15 or 60 minutes; `describeServer`'s three compared fields; no
check of the exact numbers of limits; sign-in on the server's own page,
compared from the redirect on; spec-pds's own departures not held; and the
settings an adapter cannot give, whose checks are skipped and reported.
The harness lets nothing else, and spec-pds is held to all of `spec/PDS.md`
as before.
What `spec/PDS.md` and the area pages list as "what the reference does that
the specs leave open" (the order a write's checks refuse in, the 500s, and
the rest) is not let differ: another implementation that does otherwise
differs from the reference. `RESULTS.md` says where a difference is one of
those.
## The vlpds documentation the report cites as deliberate
- `listRepos`' order, `DESIGN.md:5905`: "**listRepos order** is
`(slot, DID)`, because listings are served per shard, not by creation
order."
- `getBlob` of an upload no record names, `DESIGN.md:5906-5907`: "**Fresh
uploads are readable.** Blobs are written under their final key at
upload, so getBlob serves an upload before any record references it,
until the blob GC collects it." And `docs/blobs.md:65-66`: "Unlike the
reference PDS, vlpds serves a blob through `getBlob` as soon as it's
uploaded, before any record names it."
## Adding an implementation
1. Pin it in `bench/impls.json` and give it a benchmark adapter
(`bench/README.md`); put its Docker configuration in
`harness/lib/impls.mjs`.
2. Give it an adapter in `harness/lib/adapters.mjs`: `start`, `port`,
`info`, `unsupported` with why, `signIn` unless it serves the
reference's page API, and `readyMs` if it starts slowly.
3. Add its name to `IMPLS` in `harness/compat.mjs`, and the differences its
documentation says are on purpose to `DELIBERATE` there.
4. `node compat.mjs --impls <name> --steps 60` to try it, then a full run.
compat/results.jsonnew+15579−0
A large diff, not shown.
compat/RESULTS.mdnew+1488−0
1488 lines changed: not loaded until asked for.
harness/checks/accounts.mjs+15−9
@@ -8,7 +8,7 @@ import { isDeepStrictEqual } from 'node:util'
import { COLLECTIONS, RKEYS, below, chance, goodRecord, pick, rand } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { checkDidDoc, fail, plcLog } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { allow, count, differ } from '../lib/report.mjs'
import { accounts, addAccount, didOf } from '../lib/state.mjs'
import { METHODS, commandLine, runCli, viaCommand, viaTool } from '../lib/via.mjs'
import { both, normalize, shown, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
@@ -85,15 +85,18 @@ const made = (body, a, b) =>
/// Answers the account, or null. `http` sends it over XRPC only. `body` may
/// be a function of the side, for what differs between them, such as an
/// invite code.
export async function sendCreate(kind, body, http = false) {
export async function sendCreate(kind, body, http = false, statuses = {}) {
const send = http ? xrpcHttp : xrpc
const on = typeof body === 'function' ? body : () => body
const [a, b] = await Promise.all([ref, cand].map((side) => send(side, CREATE, { body: on(side) })))
Object.assign(statuses, { reference: a.status, server: b.status })
const name = `<did:${accounts.length + 1}>`
const [na, nb] = [normalize(ref, a, CREATE, [[a.body?.did, name]]), normalize(cand, b, CREATE, [[b.body?.did, name]])]
if (!isDeepStrictEqual(na, nb)) await differ(CREATE, on(ref), na, nb)
count(kind, a.status < 400)
if (a.status !== 200) return null
// An account only one side made is not kept (a compatibility run goes on
// past the difference, lib/areas.mjs).
if (a.status !== 200 || b.status !== 200) return null
const acct = made(on(ref), a, b)
await checkNewAccount(acct, [a, b], on(ref))
return acct
@@ -107,9 +110,10 @@ export const newAccountInput = (withPassword = false) => inputOf(newDetails(with
/// the side's rotation keys, the account's handle and the side's URL, whose
/// signing key is then the one its repository is verified against; and
/// getSession with the new token is the same on both sides. The reference
/// is held to all of it too, which checks the checks. The server's
/// operation also has the account's KEM key, a P-256 did:key other than
/// the signing key (spec/SPACES.md), which the `latest` reference has not.
/// is held to all of it too, which checks the checks. spec-pds's operation
/// also has the account's KEM key, a P-256 did:key other than the signing
/// key (spec/SPACES.md), which the `latest` reference has not; another
/// implementation may have one, held to the same (spec/COMPAT.md).
async function checkNewAccount(acct, answers, body) {
const request = shown({ body })
for (const [side, res] of [[ref, answers[0]], [cand, answers[1]]]) {
@@ -124,7 +128,8 @@ async function checkNewAccount(acct, answers, body) {
const key = op.verificationMethods?.atproto
const kem = op.verificationMethods?.atproto_kem
const verificationMethods = { atproto: typeof key === 'string' && key.startsWith('did:key:') ? key : '<the signing key, a did:key>' }
if (side === cand) verificationMethods.atproto_kem = isP256DidKey(kem) && kem !== key ? kem : '<the KEM key, a P-256 did:key other than the signing key>'
if (side === cand && (cand.adapter.own || kem !== undefined)) verificationMethods.atproto_kem = isP256DidKey(kem) && kem !== key ? kem : '<the KEM key, a P-256 did:key other than the signing key>'
if (side === cand && !cand.adapter.own && kem !== undefined) allow('a KEM key (atproto_kem) in the genesis operation, as spec-pds\'s (spec/SPACES.md)')
const want = {
type: 'plc_operation',
verificationMethods,
@@ -159,8 +164,9 @@ export async function createAccount({ withPassword = false } = {}) {
const free = freeEmails()
if (free.length && chance(0.2)) d.email = pick(free)
const body = inputOf(d, true)
const acct = await sendCreate('createAccount', body)
if (!acct) await differ(CREATE, body, 'an account', 'none', 'the reference refuses an account the harness means to make')
const statuses = {}
const acct = await sendCreate('createAccount', body, false, statuses)
if (!acct && statuses.reference !== 200) await differ(CREATE, body, 'an account', 'none', 'the reference refuses an account the harness means to make')
return acct
}
harness/checks/blobs.mjs+4−3
@@ -308,7 +308,8 @@ async function sendUpload(acct, m, { bytes, type, token, chunked = false, sniffe
/// ones and rarely ones at the limit or past it; Content-Types of each kind
/// spec/BLOBS.md names, or none; the account's token, none, or a JWT never
/// given out. Answers compared whole; the reference's `ref` and `size` held
/// to the body.
/// to the body. The limit's exact number is spec-pds's own: another
/// implementation is sent no body at it (spec/COMPAT.md).
export async function uploadBlob(acct) {
const m = model(acct)
const r = rand()
@@ -325,7 +326,7 @@ export async function uploadBlob(acct) {
bytes = make(Buffer.from(`spec-pds ${++serial}`))
sniffed = type
await sniffs(bytes, type)
} else if (r < 0.97) {
} else if (r < 0.97 || !cand.adapter.own) {
bytes = Buffer.alloc(0)
} else {
bytes = bigBody(LIMIT + below(2))
@@ -342,7 +343,7 @@ export async function uploadBlob(acct) {
const u = await runCli(['repo', 'upload-blob'], { token: tokenOf(cand, acct), stdin: Buffer.from('x') })
if (u.code !== 2) await differ('pds repo upload-blob without --encoding', {}, 'a usage error: exit 2', { code: u.code, stdout: u.stdout.toString().slice(0, 200) })
}
if (chance(0.05)) {
if (cand.adapter.own && chance(0.05)) {
const [da, db] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.server.describeServer')))
if (da.body?.blobUploadLimit !== LIMIT) throw new Error(`the reference's blobUploadLimit is ${da.body?.blobUploadLimit}, not ${LIMIT}`)
if (db.body?.blobUploadLimit !== LIMIT) await differ('describeServer blobUploadLimit', {}, LIMIT, db.body?.blobUploadLimit ?? null)
harness/checks/identity.mjs+4−3
@@ -265,8 +265,9 @@ export async function wellKnownHandle(acct) {
/// getRecommendedDidCredentials with the account's token, none, or one
/// never given out; on each side, the keys and URL must be its own, and on
/// the server the KEM key its genesis operation has (spec/SPACES.md), which
/// the `latest` reference has not.
/// spec-pds the KEM key its genesis operation has (spec/SPACES.md), which
/// the `latest` reference has not; on another implementation, the one its
/// genesis operation has, if it has one (spec/COMPAT.md).
export async function recommendedCredentials(acct) {
const r = rand()
const token = r < 0.7 ? acct : r < 0.85 ? undefined : 'never-given-out'
@@ -275,7 +276,7 @@ export async function recommendedCredentials(acct) {
for (const [side, res] of [[ref, a], [cand, b]]) {
if (res.status !== 200) continue
const verificationMethods = { atproto: acct.sides[side.name].key }
if (side === cand) verificationMethods.atproto_kem = acct.sides[side.name].kem
if (side === cand && (cand.adapter.own || acct.sides[side.name].kem !== undefined)) verificationMethods.atproto_kem = acct.sides[side.name].kem
const want = {
alsoKnownAs: [`at://${acct.handle}`],
verificationMethods,
harness/checks/logging.mjs+2−1
@@ -7,7 +7,8 @@
// the run's secrets anywhere the server wrote.
import { readFileSync } from 'node:fs'
import { OTLP_KEY, server } from '../lib/processes.mjs'
import { server } from '../lib/processes.mjs'
import { OTLP_KEY } from '../lib/adapters.mjs'
import { now, secrets, sent, settled, tokenDids } from '../lib/observe.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts } from '../lib/state.mjs'
harness/checks/oauth-clients.mjs+9−11
@@ -19,7 +19,7 @@ import { accounts, didOf } from '../lib/state.mjs'
import { HOSTS, ageReferenceCaches, fetchCount, serve } from '../lib/clients.mjs'
import { Browser, Dpop, b64u, fresh, newKey, pkce, signJwt } from '../lib/oauth.mjs'
import {
RENEW_AFTER_MS, URN, codeOf, codesOf, compare, consent, dpops, exchange, followRedirect, getSessionBoth, handleOf, holdToken, issuer, loadPage, oauthOf, par, revokeOn, sides, signIn, token, tokenBody, view,
RENEW_AFTER_MS, URN, approve, codeOf, codesOf, compare, consent, dpops, exchange, getSessionBoth, handleOf, holdToken, issuer, loadPage, oauthOf, pageApi, par, redirectBoth, revokeOn, sides, signIn, token, tokenBody, view,
} from './oauth.mjs'
const H = `https://${HOSTS[0]}`
@@ -215,7 +215,9 @@ export async function exchangeAndKeep(acct, req, codes, kind) {
/// A full sign-in with client `c`, compared at each step, on the account's
/// device unless `browsers` are given. The page may send the browser back
/// at once (silent sign-in). Answers the session, or null.
/// at once (silent sign-in), on the reference's page API alone. With a
/// server's sign-in hook, the server signs in through it (checks/oauth.mjs,
/// `redirectBoth`). Answers the session, or null.
export async function clientLogin(acct, c, { browsers, remember, prompt, hint, scope, kind = `${c.kind} client` } = {}) {
const st = oauthOf(acct)
const own = !browsers
@@ -231,13 +233,13 @@ export async function clientLogin(acct, c, { browsers, remember, prompt, hint, s
if (si.reference.status !== 200) return null
if (own && remember === true) st.remembered = true
else if (own && remember === false) st.remembered = false
if (si.reference.json.ephemeralToken) bearer = { reference: si.reference.json.ephemeralToken, server: si.server.json?.ephemeralToken }
if (si.reference.json.ephemeralToken) bearer = { reference: si.reference.json.ephemeralToken, server: si.server?.json?.ephemeralToken }
}
const narrow = chance(0.15) ? req.scope.filter((t) => t === 'atproto' || chance(0.5)).join(' ') : undefined
const narrow = chance(0.15) && !cand.adapter.unsupported.narrowScope ? req.scope.filter((t) => t === 'atproto' || chance(0.5)).join(' ') : undefined
const decided = await consent(acct, req, browsers, { scope: narrow, bearer, kind: `consent (${kind})` })
if (decided.reference.status !== 200 || !codesOf(decided)) return null
back = await followRedirect(req, browsers, { reference: decided.reference.json.url, server: decided.server.json?.url }, `redirect (${kind})`)
} else if (!silent(back.reference)) return null
back = await redirectBoth(acct, req, browsers, { reference: decided.reference.json.url, server: decided.server?.json?.url }, { kind: `redirect (${kind})` })
} else if (!silent(back.reference) || !pageApi()) return null
const codes = { reference: codeOf(back.reference, req.mode).code, server: codeOf(back.server, req.mode).code }
if (!codes.reference) return null
return exchangeAndKeep(acct, req, codes, `token: code (${kind})`)
@@ -548,13 +550,9 @@ export async function oauthAssertionRefused(acct) {
}
if (where === 'code') {
if (!handleOf(acct) || !acct.password) return
const browsers = { reference: new Browser(), server: new Browser() }
const req = await clientRequest(acct, c, { kind: 'PAR (for another check)' })
if (!req) return
await loadPage(req, browsers, 'authorization page (for another check)')
const si = await signIn(acct, req, browsers, { remember: true, identifier: 'handle', kind: 'sign-in (for another check)' })
if (si.reference.status !== 200) return
const codes = codesOf(await consent(acct, req, browsers, { kind: 'consent (for another check)' }))
const codes = (await approve(acct, req))?.codes
if (!codes) return
if (reuse) await spend('PAR (an assertion to reuse)')
await exchange(acct, req, codes, { kind: `token: code, client assertion: ${name}`, auth: fault })
harness/checks/oauth.mjs+85−31
@@ -13,7 +13,7 @@ import { NodeOAuthClient, requestLocalLock } from '@atproto/oauth-client-node'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { cand, plcUrl, ref } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { allow, count, differ } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { strip } from '../lib/xrpc.mjs'
import { API, Browser, Dpop, answer, b64u, form, formPost, fresh, newKey, pkce, proof, sha256, signJwt, target, wwwError } from '../lib/oauth.mjs'
@@ -26,7 +26,8 @@ const DEFAULT_REDIRECTS = ['http://127.0.0.1/', 'http://[::1]/']
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
const B64TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/
/// `expires_in` of a token answer on each side: the spec's on the server,
/// the reference's own on the reference (spec/OAUTH.md, departures).
/// the reference's own on the reference (spec/OAUTH.md, departures). An
/// implementation other than spec-pds may answer either (spec/COMPAT.md).
const TOKEN_LIFE = { reference: [3599, 3600], server: [899, 900] }
/// The loopback clients the harness signs in with: each one's declared scope
@@ -86,6 +87,23 @@ export async function compare(kind, request, send, show) {
return { reference: a, server: b }
}
/// Whether the server signs in through the reference's page API
/// (`/@atproto/oauth-provider/~api/*`), as spec-pds does. Without it, it
/// has a sign-in hook (lib/adapters.mjs): the reference's page, its API and
/// its answers are then the reference's alone, not compared, and only the
/// redirect to the client is (`redirectBoth`).
export const pageApi = () => cand.adapter.pageApi
/// A step of the reference's page API: compared on both sides as `compare`
/// compares, when the server has the page API; on the reference alone when
/// it has a sign-in hook instead, its `server` answer then undefined.
export async function onPage(kind, request, send, show) {
if (pageApi()) return compare(kind, request, send, show)
const a = await send(ref)
count(`oauth ${kind}`, (a.status ?? 0) < 400)
return { reference: a, server: undefined }
}
/// Redirect parameters as compared: the request's `state` and the codes
/// named, `error_description` taken out.
function params(side, p, ctx) {
@@ -221,7 +239,7 @@ export async function checkOAuthMetadata() {
}
const sm = as.server.body ?? {}
const extra = Object.keys(sm).filter((k) => k.startsWith('request_object_'))
if (sm.request_parameter_supported !== false || extra.length) await fail(cand, 'authorization server metadata (spec/OAUTH.md)', { get: '/.well-known/oauth-authorization-server' }, { request_parameter_supported: false }, { request_parameter_supported: sm.request_parameter_supported, ...(extra.length ? { extra } : {}) })
if (cand.adapter.own && (sm.request_parameter_supported !== false || extra.length)) await fail(cand, 'authorization server metadata (spec/OAUTH.md)', { get: '/.well-known/oauth-authorization-server' }, { request_parameter_supported: false }, { request_parameter_supported: sm.request_parameter_supported, ...(extra.length ? { extra } : {}) })
await compare('JWKS', { get: '/oauth/jwks' }, async (side) => answer(await fetch(`${issuer(side)}/oauth/jwks`)),
(side, r) => ({ status: r.status, cors: corsOf(r.headers), keys: Array.isArray(r.body?.keys) }))
for (const path of ['/.well-known/oauth-authorization-server', '/oauth/jwks', '/oauth/par', '/oauth/token', '/oauth/revoke']) {
@@ -229,7 +247,7 @@ export async function checkOAuthMetadata() {
async (side) => answer(await fetch(`${issuer(side)}${path}`, { method: 'OPTIONS', headers: { origin: 'http://app.example', 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type,dpop' } })),
(side, r) => ({ status: r.status, cors: corsOf(r.headers), nonce: 'dpop-nonce' in r.headers, cacheControl: r.headers['cache-control'] ?? null, pragma: r.headers.pragma ?? null }))
}
for (const [path, method] of [['/oauth/par', 'GET'], ['/oauth/par', 'PUT'], ['/oauth/token', 'GET'], ['/oauth/token', 'DELETE'], ['/oauth/revoke', 'GET'], ['/oauth/revoke', 'PUT'], ['/oauth/revoke', 'DELETE'], ['/oauth/authorize', 'POST'], [`${API}/sign-in`, 'GET'], [`${API}/nope`, 'POST']]) {
for (const [path, method] of [['/oauth/par', 'GET'], ['/oauth/par', 'PUT'], ['/oauth/token', 'GET'], ['/oauth/token', 'DELETE'], ['/oauth/revoke', 'GET'], ['/oauth/revoke', 'PUT'], ['/oauth/revoke', 'DELETE'], ['/oauth/authorize', 'POST'], ...(pageApi() ? [[`${API}/sign-in`, 'GET'], [`${API}/nope`, 'POST']] : [])]) {
await compare(`${method} ${path}`, { [method]: path }, async (side) => answer(await fetch(`${issuer(side)}${path}`, { method })), (side, r) => ({ status: r.status }))
}
}
@@ -313,7 +331,7 @@ async function newRequest(acct, { client, extra = {}, kind = 'PAR', whole = fals
/// Load the request's page on both sides, in each side's `browser`.
async function loadPage(req, browsers, kind = 'authorization page') {
return compare(kind, { authorize: req.clientId }, (side) => browsers[side.name].navigate(pageUrl(side, req.clientId, req.requestUri[side.name])), (side, p) => pageView(side, p, req))
return onPage(kind, { authorize: req.clientId }, (side) => browsers[side.name].navigate(pageUrl(side, req.clientId, req.requestUri[side.name])), (side, p) => pageView(side, p, req))
}
/// Sign the account in on both sides' pages. Answers each side's answer.
@@ -323,13 +341,13 @@ async function signIn(acct, req, browsers, { identifier, password, remember, kin
const id = (side) => (how === 'handle' ? handleOf(acct) : how === 'HANDLE' ? handleOf(acct).toUpperCase() : how === 'email' ? acct.email : how === 'did' ? didOf(side, acct) : how)
const pw = password ?? (acct.password || 'x')
const input = (side) => ({ locale: pick(['en']), identifier: id(side), password: pw, ...(remember === undefined ? {} : { remember }), ...extra(side) })
return compare(kind, { signIn: { by: how, remember } }, (side) => browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/sign-in', input(side)), (side, r) => apiView(side, r, req))
return onPage(kind, { signIn: { by: how, remember } }, (side) => browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/sign-in', input(side)), (side, r) => apiView(side, r, req))
}
/// Consent on both sides. `bearer` is each side's ephemeral token, if any.
async function consent(acct, req, browsers, { scope, bearer, did, kind = 'consent' } = {}) {
const input = (side) => ({ did: did ? did(side) : didOf(side, acct), ...(scope ? { scope } : {}) })
return compare(kind, { consent: { scope, bearer: Boolean(bearer) } }, (side) => browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/consent', input(side), { bearer: bearer?.[side.name] }), (side, r) => apiView(side, r, req))
return onPage(kind, { consent: { scope, bearer: Boolean(bearer) } }, (side) => browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/consent', input(side), { bearer: bearer?.[side.name] }), (side, r) => apiView(side, r, req))
}
/// Follow the API's `url` to the client on both sides.
@@ -337,6 +355,19 @@ async function followRedirect(req, browsers, urls, kind = 'redirect') {
return compare(kind, { follow: 'the url the API answered' }, (side) => browsers[side.name].navigate(urls[side.name], { site: 'same-origin', referer: pageUrl(side, req.clientId, req.requestUri[side.name]) }), (side, p) => pageView(side, p, req))
}
/// The answer that sends the browser back to the client, on both sides,
/// compared: on the reference, the API's `url` followed; on the server, the
/// same, or with a sign-in hook, what the hook answers for the account
/// approving the request on the server's own page (or with `approve`
/// false, refusing it).
async function redirectBoth(acct, req, browsers, urls, { approve = true, kind = 'redirect' } = {}) {
if (pageApi()) return followRedirect(req, browsers, urls, kind)
const viaHook = (side) => (side === ref
? browsers.reference.navigate(urls.reference, { site: 'same-origin', referer: pageUrl(ref, req.clientId, req.requestUri.reference) })
: cand.signIn({ identifier: handleOf(acct), password: acct.password }, pageUrl(cand, req.clientId, req.requestUri.server), { approve }))
return compare(kind, { follow: 'the url the API answered', server: `signed in on its own page, ${approve ? 'approving' : 'refusing'}` }, viaHook, (side, p) => pageView(side, p, req))
}
/// The code a redirect page gave the client on `side`, and its parameters.
function codeOf(page, mode) {
if (page.status === 200) return formPost(page.text)?.params ?? {}
@@ -362,7 +393,9 @@ async function holdToken(side, acct, res, request) {
const b = res.body
const [lo, hi] = TOKEN_LIFE[side.name]
const bad = []
if (!(b.expires_in >= lo && b.expires_in <= hi)) bad.push(`expires_in ${b.expires_in}, not ${lo} to ${hi}`)
const within = ([l, h]) => b.expires_in >= l && b.expires_in <= h
if (side === cand && !cand.adapter.own && !within(TOKEN_LIFE.server) && within(TOKEN_LIFE.reference)) allow('OAuth access tokens of the reference\'s 60 minutes, not spec/OAUTH.md\'s 15')
else if (!within([lo, hi])) bad.push(`expires_in ${b.expires_in}, not ${lo} to ${hi}`)
// A client without the refresh_token grant is given none
// (spec/OAUTH-CLIENTS.md); whether there is one is compared.
for (const t of ['access_token', ...('refresh_token' in b ? ['refresh_token'] : [])]) if (typeof b[t] !== 'string' || !B64TOKEN.test(b[t])) bad.push(`${t} not a b64token`)
@@ -397,11 +430,11 @@ export async function login(acct, { client, reject = chance(0.08), narrow = chan
if (si.reference.status !== 200) return null
if (remember === true) st.remembered = true
else if (remember === false) st.remembered = false
if (si.reference.json.ephemeralToken && chance(0.95)) bearer = { reference: si.reference.json.ephemeralToken, server: si.server.json?.ephemeralToken }
if (si.reference.json.ephemeralToken && chance(0.95)) bearer = { reference: si.reference.json.ephemeralToken, server: si.server?.json?.ephemeralToken }
if (chance(0.2)) await loadPage(req, st.browsers, 'authorization page after sign-in')
}
let scope
if (narrow) {
if (narrow && !cand.adapter.unsupported.narrowScope) {
const kept = req.scope.filter((t) => ['atproto', 'transition:email', 'transition:generic', 'transition:chat.bsky', 'repo:*', 'blob:image/*', 'account:email?action=manage', 'identity:handle', 'rpc:app.bsky.feed.getTimeline?aud=*'].includes(t))
let picked = kept.filter((t) => (t === 'atproto' ? chance(0.9) : chance(0.5)))
// The narrowed scope's order depends on how many tokens `scope` names,
@@ -411,11 +444,11 @@ export async function login(acct, { client, reject = chance(0.08), narrow = chan
scope = picked.join(' ') || 'atproto'
}
const decided = reject
? await compare('reject', { reject: true }, (side) => st.browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/reject', {}), (side, r) => apiView(side, r, req))
? await onPage('reject', { reject: true }, (side) => st.browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/reject', {}), (side, r) => apiView(side, r, req))
: await consent(acct, req, st.browsers, { scope, bearer })
if (decided.reference.status !== 200) return null
const urls = { reference: decided.reference.json.url, server: decided.server.json?.url }
const back = await followRedirect(req, st.browsers, urls)
const urls = { reference: decided.reference.json.url, server: decided.server?.json?.url }
const back = await redirectBoth(acct, req, st.browsers, urls, { approve: !reject })
const got = { reference: codeOf(back.reference, req.mode), server: codeOf(back.server, req.mode) }
if (!got.reference.code) return null
const codes = { reference: got.reference.code, server: got.server.code }
@@ -442,22 +475,34 @@ export async function login(acct, { client, reject = chance(0.08), narrow = chan
/// Each side's code in a consent's `url`, or null if the reference gave none.
function codesOf(c) {
const codes = { reference: target(c.reference.json?.url)?.params?.code, server: target(c.server.json?.url)?.params?.code }
const codes = { reference: target(c.reference.json?.url)?.params?.code, server: target(c.server?.json?.url)?.params?.code }
return codes.reference ? codes : null
}
/// An approved request on both sides: PAR, page, sign-in and consent, with
/// each side's code. Answers `{req, codes, browsers}` or null.
export async function approved(acct) {
const browsers = { reference: new Browser(), server: new Browser() }
const req = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (for another check)' })
if (!req) return null
return approve(acct, req)
}
/// `req` approved on both sides, each in a new browser: page, sign-in and
/// consent, with each side's code. Answers `{req, codes, browsers}` or
/// null. With a server's sign-in hook, the server's code is the one its
/// hook brings back, and the redirect each side answers is compared.
export async function approve(acct, req) {
const browsers = { reference: new Browser(), server: new Browser() }
await loadPage(req, browsers, 'authorization page (for another check)')
const si = await signIn(acct, req, browsers, { remember: true, identifier: 'handle', kind: 'sign-in (for another check)' })
if (si.reference.status !== 200) return null
const c = await consent(acct, req, browsers, { kind: 'consent (for another check)' })
const codes = { reference: target(c.reference.json?.url)?.params?.code, server: target(c.server.json?.url)?.params?.code }
if (!codes.reference) return null
let codes = codesOf(c)
if (!codes) return null
if (!pageApi()) {
const back = await redirectBoth(acct, req, browsers, { reference: c.reference.json.url }, { kind: 'redirect (for another check)' })
codes = { reference: codes.reference, server: codeOf(back.server, req.mode).code }
}
return { req, codes, browsers }
}
@@ -656,7 +701,7 @@ const PAR_FAULTS = [
/// One PAR with one thing wrong, on both sides with a fresh nonce.
export async function oauthParRefused() {
const [name, change] = pick(PAR_FAULTS)
const [name, change] = pick(cand.adapter.own ? PAR_FAULTS : PAR_FAULTS.filter(([n]) => !n.includes('100 KiB')))
const p = basePar()
change(p)
const d = dpops(await newKey())
@@ -1004,7 +1049,9 @@ export async function oauthRevokeRefused() {
/// A client app's own library, @atproto/oauth-client-node, as a loopback
/// client on each side: authorize, the page, callback, getSession, a
/// refresh, signOut, and restore after it.
/// refresh, signOut, and restore after it. With a server's sign-in hook,
/// the server signs in through it, and of the pages only the redirect's
/// status is compared.
export async function oauthClientLibrary(acct) {
const handle = handleOf(acct)
if (!handle || !acct.password) return
@@ -1033,17 +1080,24 @@ export async function oauthClientLibrary(acct) {
return { authorize: errName(e) }
}
out.authorize = { to: strip(side, url.origin + url.pathname), params: [...url.searchParams.keys()].sort() }
const b = new Browser()
const pageRes = await b.navigate(url.href)
out.page = pageRes.status
if (pageRes.status !== 200) return out
const si = await b.api(url.href, '/sign-in', { locale: 'en', identifier: handle, password: acct.password, remember: true })
out.signIn = si.status
if (si.status !== 200) return out
const c = await b.api(url.href, '/consent', { did: si.json.account.did })
out.consent = c.status
if (!c.json?.url) return out
const back = await b.navigate(c.json.url, { site: 'same-origin', referer: url.href })
// The reference's page and its API, as a browser drives them.
const throughPage = async () => {
const steps = {}
const b = new Browser()
const pageRes = await b.navigate(url.href)
steps.page = pageRes.status
if (pageRes.status !== 200) return { steps }
const si = await b.api(url.href, '/sign-in', { locale: 'en', identifier: handle, password: acct.password, remember: true })
steps.signIn = si.status
if (si.status !== 200) return { steps }
const c = await b.api(url.href, '/consent', { did: si.json.account.did })
steps.consent = c.status
if (!c.json?.url) return { steps }
return { steps, back: await b.navigate(c.json.url, { site: 'same-origin', referer: url.href }) }
}
const { steps, back } = side === cand && !pageApi() ? { steps: {}, back: await cand.signIn({ identifier: handle, password: acct.password }, url.href, { approve: true }) } : await throughPage()
if (pageApi()) Object.assign(out, steps)
if (!back) return out
out.redirect = back.status
const loc = back.headers.location
if (!loc) return out
@@ -1178,4 +1232,4 @@ export async function oauthAfterCrash() {
// ------------------------------------------------------------- shared
// What checks/oauth-clients.mjs shares with these checks.
export { pageView, apiView, where, par, token, revokeOn, getSessionOn, GET_SESSION, URN, pageUrl, loadPage, signIn, consent, followRedirect, codeOf, codesOf, exchange, tokenBody, holdToken, getSessionBoth, newRequest, CLIENTS }
export { pageView, apiView, where, par, token, revokeOn, getSessionOn, GET_SESSION, URN, pageUrl, loadPage, signIn, consent, redirectBoth, codeOf, codesOf, exchange, tokenBody, holdToken, getSessionBoth, newRequest, CLIENTS }
harness/checks/operations.mjs+2−1
@@ -14,7 +14,8 @@ import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { cborDecodeMulti } from '@atproto/common'
import { LIMITS, ONLY, SEED, STEPS } from '../lib/args.mjs'
import { OTEL_ENV, OTLP_KEY, cand, dataDir, metricsUrl, otlp, ref, server, wait, waitReady } from '../lib/processes.mjs'
import { cand, dataDir, metricsUrl, otlp, ref, server, wait, waitReady } from '../lib/processes.mjs'
import { OTEL_ENV, OTLP_KEY } from '../lib/adapters.mjs'
import { ROUTES, SERVED, httpRoute, noteSecret, now, sent, settled } from '../lib/observe.mjs'
import { parseMetrics } from '../lib/prometheus.mjs'
import { count } from '../lib/report.mjs'
harness/checks/session.mjs+4−3
@@ -15,10 +15,11 @@ export async function getSession(acct) {
}
/// describeServer, of which `did`, `availableUserDomains` and
/// `inviteCodeRequired` are compared. The server must also answer
/// `inviteCodeRequired` are compared. spec-pds must also answer
/// `spacesAlpha: true` (spec/SPACES.md), which the `latest` reference does
/// not, so it is held to that and not compared.
/// not, so it is held to that and not compared; another implementation is
/// not held to it (spec/COMPAT.md).
export async function describeServer() {
const [, b] = await both('describeServer', 'com.atproto.server.describeServer', {})
if (b.status === 200 && b.body?.spacesAlpha !== true) await differ('describeServer spacesAlpha', {}, true, b.body?.spacesAlpha ?? normalize(cand, b, 'com.atproto.server.describeServer'), 'held to spec/SPACES.md, not to the reference')
if (cand.adapter.own && b.status === 200 && b.body?.spacesAlpha !== true) await differ('describeServer spacesAlpha', {}, true, b.body?.spacesAlpha ?? normalize(cand, b, 'com.atproto.server.describeServer'), 'held to spec/SPACES.md, not to the reference')
}
harness/lib/adapters.mjsnew+418−0
418 lines changed: not loaded until asked for.
harness/lib/areas.mjsnew+235−0
@@ -0,0 +1,235 @@
// A compatibility run (compare.mjs --area, which compat.mjs runs): the core
// checks of one area, compared with the reference as compare.mjs compares
// them, but going on past a difference. Each area is a run of its own, on a
// fresh pair of servers, so that what differs in one does not spill into
// another: its own steps, drawn by weight as compare.mjs draws its steps,
// and the steps it needs others for (writes, for the repository, sync and
// the firehose), whose differences are kept apart. A check is one step;
// it goes on past what differs (lib/report.mjs keeps it), is counted
// failed if anything did, and the run goes on. What it found is written to
// `--result` as JSON.
//
// Only the core is here (compat/README.md, the map): the email flows,
// invites, rate limits, the admin lifecycle and proxying are not, nor
// spec-pds's own rules (its commands, logs, traces and metrics, store and
// scale, the exact numbers of its limits, its timing floors, and the
// reference's page API).
import { readFileSync, writeFileSync } from 'node:fs'
import { AREA, CHECK_EVERY, FIREHOSE, IMPL, RESULT, SEED, STEPS } from './args.mjs'
import { below, chance, pick } from './random.mjs'
import { adapter, shutdown } from './processes.mjs'
import { allowed, counts, found, run } from './report.mjs'
import { accounts } from './state.mjs'
import { accountRace, createAccount, createAccountRefused, createSession, crossWrites } from '../checks/accounts.mjs'
import { blobRecord, getBlob, listBlobs, uploadBlob } from '../checks/blobs.mjs'
import { checkCrawls, getBlocks, getGoneBlocks, getRepoStatus, listRepos, noCrawlsYet, syncGetRecord } from '../checks/federation.mjs'
import { checkFirehose, checkReplay, startFirehose } from '../checks/firehose.mjs'
import { handleRace, recommendedCredentials, resolveHandle, updateHandle, updateHandleNoToken, updateHandleRefused, wellKnownHandle } from '../checks/identity.mjs'
import { oddRequests } from '../checks/odd.mjs'
import { checkOAuthMetadata, oauthClientLibrary, oauthDpopRefused, oauthGetSession, oauthLogin, oauthParRefused, oauthRefresh, oauthRevoke, oauthRevokeRefused, oauthTokenRefused } from '../checks/oauth.mjs'
import { oauthScopedCall, oauthScopedEdges, oauthScopedRefused } from '../checks/oauth-scopes.mjs'
import { oauthAssertionRefused, oauthClientCache, oauthClientDocument, oauthClientLogin, oauthConfidentialSession } from '../checks/oauth-clients.mjs'
import { applyWrites, concurrent, createRecord, createWithTid, deleteRecord, describeRepo, getRecord, listRecords, putRecord } from '../checks/records.mjs'
import { checkRepos } from '../checks/repository.mjs'
import { describeServer, getSession } from '../checks/session.mjs'
import { appPasswords, deleteSession, refreshSession, sessionRace, wrongTokens } from '../checks/sessions.mjs'
import { duplicates, validatedBatch, validatedElsewhere, validatedWrite } from '../checks/validation.mjs'
/// The record writes the repository, sync and firehose areas need.
const WRITES = [[createRecord, 14], [putRecord, 14], [deleteRecord, 8], [applyWrites, 8]]
const newAccount = Object.defineProperty(() => createAccount(), 'name', { value: 'createAccount' })
const firehoseChecks = Object.defineProperty(async () => {
await checkFirehose()
if (chance(0.3)) await checkReplay()
}, 'name', { value: 'checkFirehose' })
const crawlsSoFar = Object.defineProperty(() => checkCrawls(0), 'name', { value: 'checkCrawls' })
/// The areas, in the order the report lists them. Each has `about`, what it
/// checks; `steps`, `[check, weight, needs]`, drawn as compare.mjs draws
/// its steps, `needs` the settings (lib/adapters.mjs, `unsupported`) a
/// check depends on; `support`, `[step, weight]` drawn among them, whose
/// differences are kept apart; `pre`, checks of the area before the steps
/// (and after the first accounts unless `beforeAccounts`); and `every`,
/// checks of the area every `--check-every` steps and at the end.
export const AREAS = {
oauth: {
about: 'OAuth, the protocol: the server\'s metadata, PAR, the code exchange with PKCE, DPoP and its nonces, refresh and its rotation, revocation, DPoP-bound calls to XRPC, and a client app\'s own library',
pre: [[checkOAuthMetadata]],
steps: [[oauthLogin, 4], [oauthParRefused, 3], [oauthDpopRefused, 3], [oauthTokenRefused, 2], [oauthRevokeRefused, 1], [oauthRefresh, 3], [oauthRevoke, 2], [oauthGetSession, 2], [oauthClientLibrary, 1]],
},
'oauth scopes': {
about: 'OAuth scopes, enforced on every method: calls with an OAuth session\'s token, and with one thing wrong in its proof, token or scheme',
steps: [[oauthScopedCall, 8], [oauthScopedRefused, 4], [oauthScopedEdges, 1]],
},
'oauth clients': {
about: 'OAuth clients\' metadata documents: fetched from the harness\'s web, kept and refused as the reference does; confidential clients and their assertions',
steps: [[oauthClientDocument, 4, ['clientFetch']], [oauthClientCache, 1, ['clientFetch']], [oauthClientLogin, 3, ['clientFetch']], [oauthAssertionRefused, 3, ['clientFetch']], [oauthConfidentialSession, 2, ['clientFetch']]],
},
sessions: {
about: 'Sessions: createSession, getSession, refreshSession, app passwords and their scopes, deleteSession, tokens of the wrong kind, and describeServer',
steps: [[createSession, 3], [getSession, 1], [describeServer, 1, ['handleDomains']], [refreshSession, 3], [deleteSession, 2], [wrongTokens, 2], [appPasswords, 4], [sessionRace, 1]],
},
accounts: {
about: 'Accounts: createAccount, the DID it registers with the PLC directory and its genesis operation, and what it refuses',
steps: [[newAccount, 4], [createAccountRefused, 4], [accountRace, 1]],
},
records: {
about: 'Records: createRecord, putRecord, deleteRecord, applyWrites, swapCommit and swapRecord, getRecord, listRecords, describeRepo, writes to another account\'s repository, and requests the lexicons refuse',
steps: [[createRecord, 14], [putRecord, 14], [deleteRecord, 8], [applyWrites, 8], [getRecord, 10], [listRecords, 6], [describeRepo, 2], [createWithTid, 2], [concurrent, 6], [oddRequests, 3], [crossWrites, 3]],
},
validation: {
about: 'Records checked against their lexicons: known types valid and not, `validate`, duplicates replaced, in applyWrites too',
steps: [[validatedWrite, 10], [duplicates, 5], [validatedBatch, 4], [validatedElsewhere, 1]],
},
repository: {
about: 'The repository: each account\'s whole repository from getRepo, verified (signature, MST, every record) by the reference\'s library against the DID\'s key, its MST root the reference\'s, getRepo since, getLatestCommit',
support: WRITES,
pre: [[checkRepos]],
every: [[checkRepos]],
},
sync: {
about: 'Sync: listRepos, getRepoStatus, getBlocks, sync.getRecord with its proof, and requestCrawl',
pre: [[noCrawlsYet, ['hostname'], true], [crawlsSoFar, ['hostname']]],
steps: [[listRepos, 2], [getRepoStatus, 2], [getBlocks, 3], [getGoneBlocks, 2], [syncGetRecord, 3]],
support: WRITES,
every: [[crawlsSoFar, ['hostname']]],
},
firehose: {
about: 'The firehose: each side\'s subscribeRepos from the start, every event checked as a consumer would, in order, with its blocks, and replays from a cursor',
support: [...WRITES, [newAccount, 1], [updateHandle, 2]],
every: [[firehoseChecks]],
},
identity: {
about: 'Identity: handles, their changes and the PLC operations they make, resolveHandle, /.well-known/atproto-did, getRecommendedDidCredentials, and DID documents',
steps: [[updateHandle, 3], [updateHandleRefused, 3], [updateHandleNoToken, 1], [resolveHandle, 3], [wellKnownHandle, 2], [recommendedCredentials, 1], [describeRepo, 2], [handleRace, 1]],
},
blobs: {
about: 'Blobs: uploadBlob, records that reference them, getBlob, listBlobs',
steps: [[uploadBlob, 4], [blobRecord, 5], [getBlob, 3], [listBlobs, 2]],
},
}
/// Why `needs` cannot be met by the server, or null.
const missing = (needs = []) => needs.map((n) => adapter.unsupported[n] && `${n}: ${adapter.unsupported[n]}`).filter(Boolean)
/// What the run found, of its own checks and of its supporting steps: how
/// many ran, differed, and could not go on; the first difference; and by
/// check, the same, with each one's first difference.
const own = { checks: 0, failed: 0, errors: 0, first: null, byCheck: {} }
const support = { checks: 0, failed: 0, errors: 0, first: null, byCheck: {} }
const skipped = {}
/// An exception a check did not expect, as an answer of a shape it cannot
/// read, kept as a difference is.
const exception = (e, name) => ({ name, step: run.step, what: `the check could not go on: ${String(e?.message ?? e).split('\n')[0]}`, note: 'an exception, not a comparison: what the server answered was of a shape the check cannot read, or the harness is wrong', request: null, reference: null, server: String(e?.stack ?? e).split('\n').slice(0, 6).join('\n') })
/// Run `fn` as one check of the area (or a supporting step, `mine` false).
/// It goes on past what differs (lib/report.mjs keeps it): one with a
/// difference is counted failed, and its first difference kept; one that
/// throws, or does not end within 3 minutes, with none, is counted as not
/// going on. Then the run goes on.
async function check(fn, args, mine) {
const name = fn.name || 'anonymous'
const tally = mine ? own : support
const by = (tally.byCheck[name] ??= { checks: 0, failed: 0, errors: 0, first: null, whats: {} })
tally.checks++
by.checks++
found.length = 0
let timer, error = null
try {
await Promise.race([fn(...args), new Promise((_, no) => (timer = setTimeout(() => no(new Error('no answer within 3 minutes')), 180_000)))])
} catch (e) {
error = e
} finally {
clearTimeout(timer)
}
const diffs = found.splice(0)
if (!diffs.length && !error) return
// Each thing that differed, how often, the exception it ended in after
// them too.
const whats = [...diffs.map((d) => d.what), ...(error && diffs.length ? [`then could not go on: ${String(error?.message ?? error).split('\n')[0]}`] : [])]
for (const w of whats) by.whats[w] = (by.whats[w] ?? 0) + 1
const f = diffs.length ? { name, ...diffs[0], ...(diffs.length > 1 ? { more: diffs.length - 1 } : {}) } : exception(error, name)
const kind = diffs.length ? 'failed' : 'errors'
tally[kind]++
by[kind]++
tally.first ??= f
by.first ??= f
console.error(`step ${run.step}: ${name}: ${f.what}${f.note ? ` (${f.note})` : ''}`)
}
/// Each of `list`, `[check, needs, beforeAccounts]`, run unless the server
/// cannot meet its needs, which is noted.
async function runAll(list, mine, when) {
for (const [fn, needs, before] of list ?? []) {
if (Boolean(before) !== when) continue
const why = missing(needs)
if (why.length) skipped[fn.name] = why
else await check(fn, [], mine)
}
}
/// The area's run, and its result written; then the run ends.
export async function areaRun() {
const area = AREAS[AREA]
if (!area) {
console.error(`no area ${AREA}; there are ${Object.keys(AREAS).join(', ')}`)
await shutdown(2)
}
const steps = []
for (const [fn, w, needs] of area.steps ?? []) {
const why = missing(needs)
if (why.length) skipped[fn.name] = why
else steps.push([fn, w, true])
}
if (FIREHOSE) await check(startFirehose, [], true)
await runAll(area.pre, true, true)
// The first accounts, as compare.mjs makes them, each a supporting step;
// as many more as it takes (up to ten tries), when the server refuses
// one the reference makes, which is then not kept.
const first = Object.defineProperty(() => createAccount({ withPassword: true }), 'name', { value: 'createAccount (a first account)' })
const want = 2 + below(2)
for (let tries = 0; accounts.length < want && tries < 10; tries++) await check(first, [], false)
for (const acct of accounts) await check(describeRepo, [acct], false)
await runAll(area.pre, true, false)
const drawn = [...steps, ...(area.support ?? []).map(([fn, w]) => [fn, w, false])]
const total = drawn.reduce((n, [, w]) => n + w, 0)
for (run.step = 1; run.step <= STEPS; run.step++) {
if (drawn.length && accounts.length) {
let r = below(total)
for (const [fn, w, mine] of drawn) {
if ((r -= w) < 0) {
await check(fn, [pick(accounts)], mine)
break
}
}
}
if (run.step % CHECK_EVERY === 0) await runAll(area.every, true, false)
if (run.step % 100 === 0) console.error(`${run.step} steps`)
}
run.step = STEPS
await runAll(area.every, true, false)
const pkg = (name) => JSON.parse(readFileSync(new URL(`../node_modules/${name}/package.json`, import.meta.url), 'utf8')).version
const result = {
impl: IMPL,
area: AREA,
about: area.about,
seed: SEED,
steps: STEPS,
reference: `@atproto/pds ${pkg('@atproto/pds')} (through @atproto/dev-env ${pkg('@atproto/dev-env')})`,
server: await adapter.info(),
own,
support,
skipped,
unsupported: adapter.unsupported,
allowed,
accounts: accounts.length,
requests: Object.values(counts).reduce((n, { ok, error }) => n + ok + error, 0),
}
// A difference may hold what a firehose frame decodes to: BigInts and bytes.
const plain = (k, v) => (typeof v === 'bigint' ? `${v}` : v instanceof Uint8Array ? `<${v.length} bytes>` : v)
writeFileSync(RESULT, `${JSON.stringify(result, plain, 2)}\n`)
console.error(`\n${AREA}: ${own.checks - own.failed - own.errors} of ${own.checks} checks agree, ${own.failed} differ, ${own.errors} could not go on; supporting steps: ${support.failed + support.errors} of ${support.checks} failed`)
await shutdown(0)
}
harness/lib/args.mjs+15−3
harness/lib/impls.mjsnew+186−0
harness/lib/mail.mjs+7−31
harness/lib/processes.mjs+28−84
harness/lib/report.mjs+16−3
harness/bench.mjs+15−125
harness/compare.mjs+10−2
harness/compat.mjsnew+236−0
spec/COMPAT.mdnew+92−0
spec/PDS.md+4−0
README.md+12−0