From c65298ffb6575d94bb4ce136d00a98e8cce01f99 Mon Sep 17 00:00:00 2001 From: Evelyn Osman Date: Thu, 12 Nov 2026 11:55:54 +0100 Subject: [PATCH] feat: issue tracked migration credentials and guard activation Add dormant tracked credential and activation operations to the incoming arrival composition. Credentials: a bound, pending arrival can be issued one tracked access/refresh family, either to the saved browser user or as the cookie-less continuation of an accepted createAccount admission presented with the current arrival code. Family creation, arrival association and revocation of prior families commit in one authority transaction; tokens are returned only after commit. Saved-user recovery with a fresh email code replaces earlier refresh families. Ordinary login, refresh and account checks are unchanged and still refuse a pending account. Activation: one fenced operation checks canonical PLC head, endpoint, repository key, rotation custody, handle, placement, saved-user binding and backend state before anything is journaled, activates through the admin status hook, observes the backend active, then settles the attempt and completes the arrival in one transaction. A lost acknowledgement stays uncertain until isolation or drain recovery. Storage: completeArrivalActivation now requires the exact placed provisioning account and activates it in the same transaction, and settleArrivalAttempt accepts receipts already resolved by an approved recovery. No schema change. No routes are mounted. This work was assisted by a machine --- docs/incoming-migration.md | 129 +++ src/accounts/operation-ownership.ts | 2 +- src/compose-incoming-arrival.mjs | 111 ++- src/database/accounts.port.ts | 4 + src/database/drizzle/account-storage.ts | 12 + src/database/drizzle/migration-arrival.ts | 73 +- src/database/migration-journal.port.ts | 7 + .../external-migration/activate-arrival.ts | 422 ++++++++++ .../external-migration/activation-checks.ts | 108 +++ .../external-migration/arrival-credentials.ts | 441 ++++++++++ .../arrival-lifecycle.test.mjs | 1 + .../external-migration/arrival-owner.ts | 101 +++ .../external-migration/arrival-types.ts | 11 +- src/oauth/legacy-credentials.mjs | 91 ++- src/pds/arrival-client.ts | 14 +- tests/contracts/incoming-activation.test.mjs | 770 ++++++++++++++++++ .../incoming-arrival-admission.test.mjs | 3 + .../incoming-arrival-composition.test.mjs | 474 +---------- .../incoming-arrival-storage.test.mjs | 156 +++- tests/contracts/incoming-credentials.test.mjs | 756 +++++++++++++++++ tests/support/discover-contracts.mjs | 2 + .../helpers/incoming-arrival-fixture.mjs | 504 ++++++++++++ .../support/helpers/incoming-arrival-live.mjs | 3 + .../helpers/incoming-arrival-restart.mjs | 18 +- 24 files changed, 3710 insertions(+), 503 deletions(-) create mode 100644 src/features/external-migration/activate-arrival.ts create mode 100644 src/features/external-migration/activation-checks.ts create mode 100644 src/features/external-migration/arrival-credentials.ts create mode 100644 src/features/external-migration/arrival-owner.ts create mode 100644 tests/contracts/incoming-activation.test.mjs create mode 100644 tests/contracts/incoming-credentials.test.mjs create mode 100644 tests/support/helpers/incoming-arrival-fixture.mjs diff --git a/docs/incoming-migration.md b/docs/incoming-migration.md index 984c5b2a..878f524c 100644 --- a/docs/incoming-migration.md +++ b/docs/incoming-migration.md @@ -524,6 +524,135 @@ remote effects. No public route, transfer credential or activation is added. Exh crash/rehydration qualification, activation implementation and public migration qualification remain deferred. +### Development: tracked credentials and guarded activation + +`composeIncomingArrival` also exposes dormant credential and activation callables. +It now takes the application's `legacy` credential instance. No route, page, XRPC +handler, stock-callback consumer or pending guard is mounted; plan 012 injects these. +Failures use stable codes from `DomainError` (`code`) or `HttpError` (`error`). + +```text +issueArrivalSession(request, operationId, expectedVersion) -> session +issueCreationSession({did, operationId, arrivalCode}) -> session +refreshArrivalSession(refreshCredential) -> session +recoverArrivalSession(request, otp, {operationId, expectedVersion}) -> session +authorizeArrivalAccess(bearer) -> {operationId, did, userId, familyId} +activateArrivalAsUser(request, otp, {operationId, expectedVersion}) + -> {state: "active", operationId, version} +activateArrivalWithCredential(bearer) -> {state: "active", operationId, version} +``` + +The C3 `owner` is acquired inside each callable (`resumePending` on `arrival:`) +because ownership is scoped to the running operation. `issueArrivalSession` takes the +saved user from the normalized browser principal. `issueCreationSession` is the +cookie-less continuation for the standard `createAccount` response, which carries no +browser cookie (C1). Its saved user is never supplied: it is the user saved on the +arrival, reached only through the current, unexpired arrival code for the same DID +and operation (renewal supersedes it; only its hash is stored), so an operation id +alone mints nothing. The arrival must also be bound and carry an accepted +`createAccount` admission for that saved user and DID with a recorded code +generation. The version is read under the fence because the tool cannot know it. The +source JWT is verified by the admission step, not repeated here. A repeat issuance is +`OperationConflict`. + +Consequences, stated plainly. Once the creation admission and binding exist, the code +together with the DID and operation id from the same preparation response is enough to +obtain the first family: no source JWT (it cannot verify after cutover) and no browser +session. The window closes at first issuance or code expiry. A repeat call is +`OperationConflict`; a lost or pre-empted first issuance is recovered through +`recoverArrivalSession` with a fresh email code, which revokes the earlier family apart +from the stock access-token expiry gap. For plan 012: the exported `admitIncoming` still +takes the saved user from a browser principal, so the cookie-less creation admission +that precedes this call must be resolved there. + +A session holds the standard fields `did`, `handle`, `email`, `emailConfirmed`, +`didDoc`, `accessJwt` and `refreshJwt`, plus `active: false` and +`status: "deactivated"` because the backend is still paused. The access token is +`at+jwt` with the issuer, subject the DID, audience the placement's PDS DID and scope +`com.atproto.access`; the refresh token is `refresh+jwt` for the Entryway service DID +with scope `com.atproto.refresh`. These are the existing legacy families. + +Issuance and recovery require observed provisioning, observed deactivation, the +saved-user binding, a pending (`provisioning`) account on the configured host that +matches the saved arrival, and no unresolved attempt. Refresh requires the same saved +facts and bound unfinished state under the fence, but is not refused by an unresolved +attempt (accepted decision). The family, its arrival association and, for recovery, the +revocation of every prior family commit in one authority transaction; tokens are signed +before it but returned only after it. Recovery needs the exact saved version (a +bound-pending continuation returns it without remote effects), no source JWT (the +source key is no longer current after cutover), and does not depend on the arrival +code's expiry. Revoking local families does not revoke access tokens already issued, +which stock PDS accepts until they expire (five minutes); this gap applies to every +recovery. + +Ordinary paths are unchanged. A pending account has status `provisioning`, so ordinary +login, access verification and refresh refuse its families with `AccountUnavailable` +without revoking them, even with a real main password. Ordinary status changes stay +refused by the existing `MigrationPending` and pending-arrival guards. After activation +the same families are ordinary account sessions. `refreshArrivalSession` serves only +tracked families of a bound, unfinished arrival (`InvalidToken` for others, +`ArrivalExpired` for finished ones). Replay revokes the family as for ordinary sessions. + +Errors: `AccountNotFound` (unknown operation or other user, identical), +`ArrivalProofRequired`, `InvalidRequest`, `OperationConflict` (version, state, host, +account, repeat issuance), `ArrivalExpired` (cancelled or complete, or an unknown, +superseded or expired code for creation issuance), `OperationRecoveryRequired`, +`InvalidToken`, `ExpiredToken`, `AccountMismatch` (binding or missing creation +admission) and `AccountUnavailable`. + +Activation is one operation for every consumer. Intent comes from the saved verified +user or from a live tracked access credential for the arrival (exact subject, +audience, type, main-access scope, unrevoked family, bound unfinished arrival, +re-proved under the fence). No client ready flag, count or digest is read. Under live +ownership it checks, before journaling anything: the canonical PLC head is the exact +saved destination move and its endpoint, repository key, ordered rotation custody and +handle equal the saved facts (`IdentityConflict`; an unreadable directory is +`AccountUnavailable`); the configured host (a changed placement is `OperationConflict`), +local account and saved-user binding match (`OperationConflict`, `AccountMismatch`); no +other unresolved attempt exists; and the backend is observed, is the same DID and +handle, and is paused (`AccountUnavailable` when unobservable; an active backend +without this arrival's journaled activation is `OperationRecoveryRequired`). Raw +transport errors never surface. It then journals the `incoming-activation` attempt and +sets `deactivated: {applied: false}` through the administrator `updateSubjectStatus` +hook. A fresh send requires the backend still paused, otherwise +`OperationRecoveryRequired` with the receipt left unresolved. It observes the backend +active, rechecks identity and, in one transaction, settles the attempt (and any attempt +replaced by an approved safe retry), completes the arrival checkpoint through the +storage primitive (which also marks the local account active), and completes the ownership claim. A +lost acknowledgement keeps the attempt unresolved: backend status alone never +completes, and only isolation/drain recovery allows the exact operation to finish. +Retrying a completed arrival as the saved user returns the committed result. Activation +does not fence in-flight imports and makes no inventory or finality claim (C4). + +Accepted decisions for this slice: + +- `issueCreationSession` is gated by the current, unexpired arrival code plus an + accepted `createAccount` admission for the saved user and DID on a bound arrival. + That gating is the tool's capability for the first family (consequences above). +- Recovery and browser activation each require a fresh destination email code, with + the separate `incoming-recover` and `incoming-activate` budgets on the existing + challenge producer at its existing limits. +- Refresh stays allowed while an external attempt is unresolved; issuance and + recovery are refused. +- A retry of `activateArrivalWithCredential` after activation completed returns the + committed `{state: "active", operationId, version}` with no backend write and no + journal change. It applies only to a bearer that verifies exactly as before (live, + unrevoked family tracked against that arrival, same DID, host and scope pins), so a + revoked or replaced family, another bearer or an ordinary unrelated session still + gets the earlier refusal and learns nothing about completion. A cancelled arrival + never qualifies. `authorizeArrivalAccess` itself still refuses a finished arrival + with `AccountUnavailable`. An expired access token needs an ordinary refresh first. +- Marking the local account `active` is part of the storage primitive: + `completeArrivalActivation` moves the exact placed account (`provisioning`, same + email, handle and placement) to `active` through the account authority in the same + transaction, fence and version checks as the checkpoint, and refuses an account that + does not match. An arrival cannot complete without the account becoming active. + +Storage ownership note: this change adds to plan 009's storage code, with no schema +change. `ArrivalAuthority` gains `activatePlacedAccount`, `completeArrivalActivation` +performs the flip, `settleArrivalAttempt` also retires an attempt replaced by an +approved safe retry, and `readArrivalFamilies` and `readArrivalFamily` are read-only. + ## Contract qualification gates for implementers These are delivery contracts for implementers, not public APIs. The development diff --git a/src/accounts/operation-ownership.ts b/src/accounts/operation-ownership.ts index d9926172..f20a19ae 100644 --- a/src/accounts/operation-ownership.ts +++ b/src/accounts/operation-ownership.ts @@ -57,7 +57,7 @@ function canonical(value: unknown): unknown { ); return value; } -const requestDigest = (value: unknown) => +export const requestDigest = (value: unknown) => createHash("sha256") .update(JSON.stringify(canonical(value)) ?? "null") .digest("hex"); diff --git a/src/compose-incoming-arrival.mjs b/src/compose-incoming-arrival.mjs index faca00a9..b078910c 100644 --- a/src/compose-incoming-arrival.mjs +++ b/src/compose-incoming-arrival.mjs @@ -11,12 +11,15 @@ import { createIncomingAuthorization } from "./features/external-migration/incom import { createArrivalLifecycle } from "./features/external-migration/manage-arrival.js"; import { createAuthenticatedArrival } from "./features/external-migration/submit-handoff.js"; import { readIncomingObservation } from "./plc/incoming-observation.js"; +import { createArrivalCredentials } from "./features/external-migration/arrival-credentials.js"; +import { createArrivalActivation } from "./features/external-migration/activate-arrival.js"; export async function composeIncomingArrival({ db, arrivals, config, accounts, + legacy, authentication, browserFlow, }) { @@ -27,6 +30,36 @@ export async function composeIncomingArrival({ accounts, }); const { choosePds } = await createPdsAccountClient({ config, accounts }); + const placement = (pdsId) => config.pds.find((pds) => pds.id === pdsId); + const arrivalBackend = (saved) => { + const pds = choosePds(saved.pdsId); + if (pds.url !== saved.endpoint) + throw new DomainError( + "OperationConflict", + 409, + "Arrival placement changed", + ); + const transport = new ArrivalPdsClient({ + endpoint: saved.endpoint, + did: saved.did, + pdsDid: pds.did, + issuer: config.serviceDid, + jwtJwk: config.jwtJwk, + }); + const authorization = () => + `Basic ${Buffer.from(`admin:${pds.adminPassword}`).toString("base64")}`; + return { + inspect: () => transport.getAccountInfo(authorization), + create: (operation) => + transport.createAccount({ + did: saved.did, + handle: saved.handle, + operation, + }), + pause: () => transport.pauseAccount(authorization), + activate: () => transport.activateAccount(authorization), + }; + }; const prepareArrival = createIncomingPreparation({ arrivals, ownership: accounts.ownership, @@ -41,7 +74,12 @@ export async function composeIncomingArrival({ entrywayDid: config.serviceDid, reserveSigningKey: ({ did, pdsId, endpoint }) => { const pds = choosePds(pdsId); - if (pds.url !== endpoint) throw new Error("Arrival placement changed"); + if (pds.url !== endpoint) + throw new DomainError( + "OperationConflict", + 409, + "Arrival placement changed", + ); return new ArrivalPdsClient({ endpoint, did, @@ -73,30 +111,7 @@ export async function composeIncomingArrival({ client: accounts.plcClient, signer: accounts.plcSigner, bindPending: admission.bindPending, - backend: (saved) => { - const pds = choosePds(saved.pdsId); - if (pds.url !== saved.endpoint) - throw new Error("Arrival placement changed"); - const transport = new ArrivalPdsClient({ - endpoint: saved.endpoint, - did: saved.did, - pdsDid: pds.did, - issuer: config.serviceDid, - jwtJwk: config.jwtJwk, - }); - const authorization = () => - `Basic ${Buffer.from(`admin:${pds.adminPassword}`).toString("base64")}`; - return { - inspect: () => transport.getAccountInfo(authorization), - create: (operation) => - transport.createAccount({ - did: saved.did, - handle: saved.handle, - operation, - }), - pause: () => transport.pauseAccount(authorization), - }; - }, + backend: arrivalBackend, }), verify: createIncomingAuthorization({ serviceDid: config.serviceDid, @@ -118,9 +133,55 @@ export async function composeIncomingArrival({ ); return principal.userId; }; + const credentials = createArrivalCredentials({ + arrivals, + ownership: accounts.ownership, + transact: (work) => db.transact(work), + signer: legacy.arrivalSessions, + readAccount: (did) => accounts.storage.getByDid(did), + readBinding: (did) => accounts.storage.getVerifiedBinding(did), + readDocument: (did) => accounts.plcClient.getDocument(did), + placement, + authentication, + checkCsrf: browserFlow.checkCsrf, + loadBrowser: browserFlow.loadBrowser, + rateLimit, + }); + const activation = createArrivalActivation({ + arrivals, + ownership: accounts.ownership, + receipts: createOperationOwnershipStore(db), + transact: (work) => db.transact(work), + plcClient: accounts.plcClient, + accounts: { + getByDid: (did) => accounts.storage.getByDid(did), + getVerifiedBinding: (did) => accounts.storage.getVerifiedBinding(did), + }, + placement, + backend: arrivalBackend, + authorizeAccess: credentials.identifyArrivalAccess, + authentication, + checkCsrf: browserFlow.checkCsrf, + loadBrowser: browserFlow.loadBrowser, + rateLimit, + }); return { ...admission, prepareArrival, + // Tracked migration credentials and the one guarded activation. Dormant: + // plan 012 injects these into routes, XRPC and the stock callback. + issueArrivalSession: async (request, operationId, expectedVersion) => + credentials.issueArrivalSession( + await savedUser(request), + operationId, + expectedVersion, + ), + issueCreationSession: credentials.issueCreationSession, + refreshArrivalSession: credentials.refreshArrivalSession, + recoverArrivalSession: credentials.recoverArrivalSession, + authorizeArrivalAccess: credentials.authorizeArrivalAccess, + activateArrivalAsUser: activation.activateArrivalAsUser, + activateArrivalWithCredential: activation.activateArrivalWithCredential, renewArrival: lifecycle.renew, cancelArrival: lifecycle.cancel, admitIncoming: async (request, input) => diff --git a/src/database/accounts.port.ts b/src/database/accounts.port.ts index 069283db..01bb9d83 100644 --- a/src/database/accounts.port.ts +++ b/src/database/accounts.port.ts @@ -56,6 +56,10 @@ export interface AccountTransactor extends AccountReader { reserveExternalMigration(input: ExternalMigrationReservation): Promise; bindProvisionedArrival(input: BindProvisionedArrival): Promise; activateBoundArrival(input: ActivateBoundArrival): Promise; + /** Incoming-arrival completion: moves the saved placed account from + * `provisioning` to `active` through `saveAccount`'s reviewed invariants. The + * arrival storage calls this inside its completion transaction. */ + activatePlacedAccount(did: string): Promise; reserveEmail( email: string, did: string, diff --git a/src/database/drizzle/account-storage.ts b/src/database/drizzle/account-storage.ts index 7b1b4dd0..94e776eb 100644 --- a/src/database/drizzle/account-storage.ts +++ b/src/database/drizzle/account-storage.ts @@ -793,6 +793,18 @@ export function createAccountStorage( return row; }); }, + async activatePlacedAccount(did) { + await db.transact(async () => { + const row = await getByDid(did); + if (!row || row.status !== "provisioning") + throw new DomainError( + "IdentityConflict", + 409, + "Placed account is not pending activation", + ); + await saveAccount({ ...row, status: "active" }); + }); + }, async activateBoundArrival(input) { return db.transact(async () => { const reservation = await one( diff --git a/src/database/drizzle/migration-arrival.ts b/src/database/drizzle/migration-arrival.ts index d5774a26..e9342861 100644 --- a/src/database/drizzle/migration-arrival.ts +++ b/src/database/drizzle/migration-arrival.ts @@ -1,6 +1,6 @@ import * as plc from "@did-plc/lib"; import { cidForCbor } from "@atproto/common"; -import { and, desc, eq, isNull, ne, or, sql } from "drizzle-orm"; +import { and, asc, desc, eq, isNull, ne, or, sql } from "drizzle-orm"; import { DomainError } from "../../accounts/errors.js"; import { normalizeEmail } from "../../accounts/rules.js"; import type { ArrivalTransactor } from "../migration-journal.port.js"; @@ -9,6 +9,7 @@ import type { DatabaseExecutor, StoredRow } from "../executor.js"; import { isObservedArrivalActivation } from "../../features/external-migration/arrival-types.js"; import type { ArrivalAccess, + ArrivalCredentialFamily, ArrivalRecord, ArrivalSignedOperationRecord, } from "../../features/external-migration/arrival-types.js"; @@ -68,6 +69,10 @@ export interface ArrivalAuthority { userId: string; }): Promise; recordSavedUserBinding(did: string, userId: string): Promise; + /** Moves the saved placed account from `provisioning` to `active` through the + * reviewed account authority, as `activateBoundArrival` does for managed + * migration. Called only inside the completion transaction. */ + activatePlacedAccount(did: string): Promise; } const canonicalFact = (value: unknown): string => { @@ -116,6 +121,15 @@ function arrivalRecord( }; } +const familyRecord = ( + saved: StoredRow<"arrival_families">, +): ArrivalCredentialFamily => ({ + familyId: saved.family_id, + operationId: saved.operation_id, + pdsId: saved.pds_id, + revokedAt: saved.revoked_at, +}); + export function createArrivalStorage( db: DatabaseExecutor, configuredPds: readonly { readonly id: string; readonly url: string }[], @@ -268,7 +282,8 @@ export function createArrivalStorage( const method = input.step === "incoming-creation" ? "com.atproto.server.createAccount" - : input.step === "incoming-pause" + : input.step === "incoming-pause" || + input.step === "incoming-activation" ? "com.atproto.admin.updateSubjectStatus" : null; if ( @@ -994,7 +1009,17 @@ export function createArrivalStorage( db.withOperationFence(owner, async () => { const saved = await current(input.operationId, expectedVersion); const receipt = await externalReceipt(owner, saved, input); - if (receipt.state !== "acknowledged" || receipt.result !== "null") + // An acknowledged receipt with `null` finished normally. One replaced + // by an approved safe retry carries its recovery disposition instead. + if ( + receipt.state !== "acknowledged" || + !( + receipt.result === "null" || + /^\{"recovery":"(unapplied|replay-safe)"\}$/.test( + receipt.result ?? "", + ) + ) + ) throw recoveryRequired(); const attemptBinding = `${input.operationId}:external:${receipt.id}`; const association = ( @@ -1334,12 +1359,30 @@ export function createArrivalStorage( "Activation requires observed backend evidence for this arrival", ); return db.withOperationFence(input.owner, async () => { - if (!(await authority.readAccount(input.did))) + const account = (await authority.readAccount(input.did)) as { + email?: unknown; + handle?: unknown; + pdsId?: unknown; + status?: unknown; + } | null; + if (!account) throw new DomainError( "OperationConflict", 409, "The bound account is not saved", ); + // Only the exact placed, still-pending account may become active. + if ( + account.status !== "provisioning" || + account.email !== saved.email || + account.handle !== saved.handle || + account.pdsId !== saved.pds_id + ) + throw new DomainError( + "OperationConflict", + 409, + "The saved account no longer matches this arrival", + ); await advance(saved, { activation_method: input.activation!.method, activation_at: input.activation!.observedAt, @@ -1347,6 +1390,9 @@ export function createArrivalStorage( did_root: null, active: 0, }); + // After the arrival is no longer active, so the authority's pending + // arrival guard passes; any failure rolls back the whole completion. + await authority.activatePlacedAccount(input.did); return { kind: "applied" as const, version: saved.version + 1 }; }); }); @@ -1487,6 +1533,25 @@ export function createArrivalStorage( }); }, + async readArrivalFamilies(operationId) { + return ( + await db.read("arrival_families", { + where: eq(familyTable.operation_id, operationId), + orderBy: [asc(familyTable.created_at), asc(familyTable.family_id)], + }) + ).map(familyRecord); + }, + + async readArrivalFamily(familyId) { + const saved = ( + await db.read("arrival_families", { + where: eq(familyTable.family_id, familyId), + limit: 1, + }) + )[0]; + return saved ? familyRecord(saved) : null; + }, + async revokeArrivalCredentialFamilies(input) { assertClaim(input.owner); return db.transact(async () => { diff --git a/src/database/migration-journal.port.ts b/src/database/migration-journal.port.ts index ccc03bd7..43d6d14d 100644 --- a/src/database/migration-journal.port.ts +++ b/src/database/migration-journal.port.ts @@ -10,6 +10,7 @@ import type { ArrivalPreparationAuthority, ArrivalActivationEvidence, ArrivalAllocationIntent, + ArrivalCredentialFamily, ArrivalOutcome, ArrivalPlacementEvidence, ArrivalRecord, @@ -189,4 +190,10 @@ export interface ArrivalTransactor { operationId: string; expectedVersion: number; }): Promise; + /** Read-only: tracked families for one arrival, including revoked ones. */ + readArrivalFamilies( + operationId: string, + ): Promise; + /** Read-only: the arrival a family is tracked against, or null if untracked. */ + readArrivalFamily(familyId: string): Promise; } diff --git a/src/features/external-migration/activate-arrival.ts b/src/features/external-migration/activate-arrival.ts new file mode 100644 index 00000000..f1c6e441 --- /dev/null +++ b/src/features/external-migration/activate-arrival.ts @@ -0,0 +1,422 @@ +import type * as plc from "@did-plc/lib"; +import { DomainError } from "../../accounts/errors.js"; +import { + requestDigest, + type OperationOwnership, +} from "../../accounts/operation-ownership.js"; +import type { + BrowserAuthentication, + BrowserRequest, +} from "../../authentication/port.js"; +import type { AccountTransactor } from "../../database/accounts.port.js"; +import type { ArrivalTransactor } from "../../database/migration-journal.port.js"; +import type { + OperationClaim, + OperationOwnershipStore, +} from "../../database/operation-ownership.port.js"; +import { HttpError } from "../../http/http-error.mjs"; +import { PlcError } from "../../plc/errors.js"; +import { readIncomingObservation } from "../../plc/incoming-observation.js"; +import { assertActivationReady } from "./activation-checks.js"; +import { + createArrivalOwner, + parseArrivalInput, + recoveryRequired, + versionConflict, +} from "./arrival-owner.js"; +import { + assertBoundPending, + type AuthorizedArrivalAccess, +} from "./arrival-credentials.js"; +import type { ArrivalAggregate } from "./arrival-types.js"; +import { createFreshArrivalProof } from "./fresh-proof.js"; + +export interface ActivatedArrival { + readonly state: "active"; + readonly operationId: string; + readonly version: number; +} + +const activationStep = "incoming-activation"; +const activationMethod = "com.atproto.admin.updateSubjectStatus"; + +/** Who asked. Intent alone never authorizes: both kinds are re-derived from + * saved state under the arrival's live ownership before anything is dispatched. */ +type Intent = + | { + readonly kind: "saved-user"; + readonly userId: string; + readonly operationId: string; + readonly expectedVersion: number; + } + | { + readonly kind: "credential"; + readonly access: AuthorizedArrivalAccess; + readonly expectedVersion: number | undefined; + }; + +/** The one guarded activation for every pending-arrival consumer. */ +export function createArrivalActivation({ + arrivals, + ownership, + receipts, + transact, + plcClient, + accounts, + placement, + backend, + authorizeAccess, + authentication, + checkCsrf, + loadBrowser, + rateLimit, +}: { + arrivals: ArrivalTransactor; + ownership: OperationOwnership; + receipts: Pick; + transact: (work: () => Promise) => Promise; + plcClient: plc.Client; + accounts: Pick; + placement: (pdsId: string) => { url: string } | undefined; + backend: (saved: ArrivalAggregate["arrival"]) => { + inspect(): Promise<{ + did: string; + handle: string; + deactivated: boolean; + } | null>; + activate(): Promise; + }; + authorizeAccess: (bearer: unknown) => Promise; + authentication: BrowserAuthentication; + checkCsrf: (request: BrowserRequest, browser: unknown) => void; + loadBrowser: (request: BrowserRequest) => Promise; + rateLimit: (subject: string) => Promise; +}) { + const owner = createArrivalOwner({ arrivals, ownership }); + const requireFreshProof = createFreshArrivalProof({ + authentication, + checkCsrf, + loadBrowser, + rateLimit, + }); + const finished = (aggregate: ArrivalAggregate): ActivatedArrival => ({ + state: "active", + operationId: aggregate.arrival.operationId, + version: aggregate.arrival.version, + }); + const inactive = () => + new HttpError( + 409, + "ArrivalExpired", + "This arrival is no longer actionable", + ); + + const run = async ( + claim: OperationClaim, + initial: ArrivalAggregate, + intent: Intent, + ): Promise => { + const saved = initial.arrival; + const read = async () => owner.read(saved.operationId, saved.userId); + if (initial.progress.completedAt !== null) { + // A lost response retries into the committed result; nothing is dispatched. + await ownership.checkpoint("complete", null); + return finished(initial); + } + assertBoundPending(initial); + if ( + intent.expectedVersion !== undefined && + saved.version !== intent.expectedVersion + ) + throw versionConflict(); + if (intent.kind === "credential") { + // Authorization is re-proved under the fence: recovery may have replaced + // the family between verification and acquiring ownership. + const tracked = await arrivals.readArrivalFamily(intent.access.familyId); + if ( + !tracked || + tracked.operationId !== saved.operationId || + tracked.revokedAt !== null + ) + throw new HttpError( + 400, + "ExpiredToken", + "Session expired or was revoked", + ); + } + // Only this operation's own journaled activation may remain unresolved. + if ( + initial.reservation?.uncertainReason || + initial.attempts.some( + (attempt) => + attempt.reason.startsWith("external:") && + attempt.reason !== `external:${activationStep}`, + ) + ) + throw recoveryRequired( + "An unresolved external attempt must be recovered before activation", + ); + const move = initial.signedOperations.find( + (item) => item.kind === "destination-move", + ); + if (!move) + throw recoveryRequired("The saved destination move is not durable"); + const target = backend(saved); + const intentFacts = { cid: move.cid, did: saved.did, step: activationStep }; + const descriptor = { + step: activationStep, + target: saved.endpoint, + method: activationMethod, + intentDigest: requestDigest(intentFacts), + }; + // Observation failures are stable refusals, never raw transport errors. + const observe = async ( + read: () => Promise, + failure: () => DomainError, + ): Promise => { + try { + return await read(); + } catch (error) { + if (error instanceof DomainError) throw error; + throw failure(); + } + }; + const unobserved = () => + new DomainError( + "AccountUnavailable", + 502, + "The destination account cannot be observed", + ); + const inspect = () => observe(() => target.inspect(), unobserved); + const readDirectory = async () => { + try { + return await readIncomingObservation(plcClient, saved.did); + } catch (error) { + if (error instanceof PlcError) + throw new DomainError( + "IdentityConflict", + 409, + "The canonical identity history is not valid", + ); + throw new DomainError( + "AccountUnavailable", + 502, + "The canonical identity cannot be observed", + ); + } + }; + const check = async () => { + const [directory, account, binding, observed, journaled] = + await Promise.all([ + readDirectory(), + accounts.getByDid(saved.did), + accounts.getVerifiedBinding(saved.did), + inspect(), + receipts.readExternal(claim, descriptor), + ]); + assertActivationReady({ + arrival: saved, + move, + directory, + account, + binding, + configuredEndpoint: placement(saved.pdsId)?.url, + backend: observed, + activationJournaled: journaled !== null, + }); + return observed; + }; + // Every precondition is checked before the activation attempt is journaled, + // so a refusal leaves no marker and sends nothing to the backend. + await check(); + const associate = async () => { + const receipt = await receipts.readExternal(claim, descriptor); + if (!receipt) + throw recoveryRequired("The generic external receipt is unavailable"); + await arrivals.associateArrivalAttempt( + claim, + (await read()).arrival.version, + { + operationId: saved.operationId, + did: saved.did, + externalAttemptId: receipt.id, + step: activationStep, + }, + ); + return receipt; + }; + const observedActive = async () => { + const observed = await inspect(); + return ( + observed !== null && + observed.did === saved.did && + observed.handle === saved.handle && + !observed.deactivated + ); + }; + await ownership.dispatch( + { + step: activationStep, + target: saved.endpoint, + method: activationMethod, + intent: intentFacts, + }, + { + send: async () => { + await associate(); + // A fresh attempt starts from a paused backend. One that became active + // through another actor is not completed by status match: the receipt + // stays unresolved for operator recovery. + if (!(await inspect())?.deactivated) + throw recoveryRequired( + "The destination changed state before activation was sent", + ); + await observe(() => target.activate(), unobserved); + if (!(await observedActive())) + throw recoveryRequired( + "The destination activation is not observed", + ); + return null; + }, + project: () => null, + resume: (value) => { + if (value !== null) + throw new DomainError( + "OperationConflict", + 409, + "Invalid saved activation receipt", + ); + return null; + }, + observe: async () => + (await observedActive()) + ? { state: "applied" as const, result: null } + : { state: "unapplied" as const }, + }, + ); + // Status match alone never completes: the journaled attempt, canonical + // identity and active backend must all hold when authority is completed. + await check(); + if (!(await observedActive())) + throw recoveryRequired("The destination activation is not observed"); + const receipt = await associate(); + await transact(async () => { + const settled = await arrivals.settleArrivalAttempt( + claim, + (await read()).arrival.version, + { + operationId: saved.operationId, + did: saved.did, + externalAttemptId: receipt.id, + step: activationStep, + }, + ); + if (settled.kind === "reconciliation-required") + throw recoveryRequired("Activation settlement requires recovery"); + // An approved safe retry replaced earlier receipts; each was observed + // unapplied or replay-safe, so its association retires with the new one. + let settledVersion = settled.version; + for (const earlier of (await read()).attempts) { + if ( + earlier.reason !== `external:${activationStep}` || + earlier.attemptId === receipt.id + ) + continue; + const outcome = await arrivals.settleArrivalAttempt( + claim, + settledVersion, + { + operationId: saved.operationId, + did: saved.did, + externalAttemptId: earlier.attemptId, + step: activationStep, + }, + ); + if (outcome.kind === "reconciliation-required") + throw recoveryRequired("Activation settlement requires recovery"); + settledVersion = outcome.version; + } + const completed = await arrivals.completeArrivalActivation({ + owner: claim, + operationId: saved.operationId, + expectedVersion: settledVersion, + did: saved.did, + userId: saved.userId, + activation: { + backendActiveObserved: true, + method: activationMethod, + observedAt: Date.now(), + }, + }); + if (completed.kind === "reconciliation-required") + throw recoveryRequired("Activation completion requires recovery"); + await ownership.checkpoint("complete", null); + }); + return finished(await read()); + }; + + const activate = async (intent: Intent): Promise => { + const userId = + intent.kind === "saved-user" ? intent.userId : intent.access.userId; + const operationId = + intent.kind === "saved-user" + ? intent.operationId + : intent.access.operationId; + const initial = await owner.read(operationId, userId); + // Both kinds of intent were just proved against this very arrival (the + // credential's own unrevoked tracked family), so a finished arrival returns + // its committed result with no backend write and no journal change. + if (initial.progress.completedAt !== null) return finished(initial); + if (initial.arrival.cancelledAt !== null) throw inactive(); + try { + return await owner.resume(initial.arrival, (claim, current) => + run(claim, current, intent), + ); + } catch (error) { + if ( + error instanceof DomainError && + error.code === "OperationNoLongerPending" + ) { + // Another request completed activation and released the claim first. + const current = await owner.read(operationId, userId); + if (current.progress.completedAt !== null) return finished(current); + } + throw error; + } + }; + + return { + /** Saved verified user, with origin/CSRF and a fresh destination email code. */ + async activateArrivalAsUser( + request: BrowserRequest, + otp: string, + input: unknown, + ): Promise { + let parsed: { operationId: string; expectedVersion: number } | undefined; + const principal = await requireFreshProof( + request, + otp, + "incoming-activate", + () => { + parsed = parseArrivalInput(input); + }, + ); + return activate({ + kind: "saved-user", + userId: principal.userId, + operationId: parsed!.operationId, + expectedVersion: parsed!.expectedVersion, + }); + }, + /** An authorized client: a live tracked access credential for this arrival. */ + async activateArrivalWithCredential( + bearer: unknown, + ): Promise { + return activate({ + kind: "credential", + access: await authorizeAccess(bearer), + expectedVersion: undefined, + }); + }, + }; +} diff --git a/src/features/external-migration/activation-checks.ts b/src/features/external-migration/activation-checks.ts new file mode 100644 index 00000000..20a3586a --- /dev/null +++ b/src/features/external-migration/activation-checks.ts @@ -0,0 +1,108 @@ +import { DomainError } from "../../accounts/errors.js"; +import type { AccountRow } from "../../accounts/types.js"; +import type { ArrivalRecord } from "./arrival-types.js"; + +/** Facts read independently of the caller. A client "ready" flag, record or blob + * counts and transfer diagnostics are deliberately absent: they are intent, never + * authorization or proof of identity. */ +export interface ActivationFacts { + readonly arrival: ArrivalRecord; + /** Saved Entryway-signed destination move, journaled before publication. */ + readonly move: { readonly cid: string }; + /** Validated canonical PLC head and its public facts. */ + readonly directory: { + readonly sourcePlcHead: string; + readonly rotationKeys: readonly string[]; + readonly source: { + readonly services: Readonly< + Record + >; + readonly verificationMethods: Readonly>; + readonly alsoKnownAs: readonly string[]; + }; + }; + readonly account: AccountRow | null; + readonly binding: { readonly userId: string } | null; + /** Configured endpoint for the saved placement, if that host still exists. */ + readonly configuredEndpoint: string | undefined; + /** Administrator observation of the destination backend. */ + readonly backend: { + readonly did: string; + readonly handle: string; + readonly deactivated: boolean; + } | null; + /** True when this arrival already journaled an activation attempt. */ + readonly activationJournaled: boolean; +} + +const identity = (message: string) => + new DomainError("IdentityConflict", 409, message); +const placement = (message: string) => + new DomainError("OperationConflict", 409, message); +const backendUnavailable = (message: string) => + new DomainError("AccountUnavailable", 502, message); + +/** Refuses, with a stable code and no remote effect, unless every independent + * identity, placement, binding and backend fact agrees. */ +export function assertActivationReady(facts: ActivationFacts): void { + const { arrival, directory, move } = facts; + // Canonical identity: exactly the saved move, with the saved public facts. + if (directory.sourcePlcHead !== move.cid) + throw identity( + "The canonical identity head is not the saved destination move", + ); + const service = directory.source.services.atproto_pds; + if ( + service?.type !== "AtprotoPersonalDataServer" || + service.endpoint !== arrival.endpoint + ) + throw identity("The canonical hosting endpoint is not the saved placement"); + if ( + arrival.signingKey === null || + directory.source.verificationMethods.atproto !== arrival.signingKey + ) + throw identity("The canonical repository key is not the saved reservation"); + if ( + directory.rotationKeys.length !== arrival.approvedRotationKeys.length || + directory.rotationKeys.some( + (key, index) => key !== arrival.approvedRotationKeys[index], + ) + ) + throw identity("The canonical rotation custody is not the approved list"); + if (!directory.source.alsoKnownAs.includes(`at://${arrival.handle}`)) + throw identity("The canonical handle is not the saved handle"); + // Placement and local account authority. + if (facts.configuredEndpoint !== arrival.endpoint) + throw placement("The saved arrival placement is not the configured host"); + const { account } = facts; + if ( + !account || + account.status !== "provisioning" || + account.email !== arrival.email || + account.handle !== arrival.handle || + account.pdsId !== arrival.pdsId || + account.pdsUrl !== arrival.endpoint + ) + throw placement("The saved account no longer matches this arrival"); + if (facts.binding?.userId !== arrival.userId) + throw new DomainError( + "AccountMismatch", + 403, + "The saved user binding does not match this arrival", + ); + // Backend: present, the same identity, and still paused unless this arrival's + // own journaled activation may already have taken effect. + const { backend } = facts; + if (!backend) + throw backendUnavailable("The destination account is not observed"); + if (backend.did !== arrival.did || backend.handle !== arrival.handle) + throw backendUnavailable( + "The destination account identity differs from the saved arrival", + ); + if (!backend.deactivated && !facts.activationJournaled) + throw new DomainError( + "OperationRecoveryRequired", + 409, + "The destination is active without a journaled activation; keep the arrival pending for recovery", + ); +} diff --git a/src/features/external-migration/arrival-credentials.ts b/src/features/external-migration/arrival-credentials.ts new file mode 100644 index 00000000..3a17ba31 --- /dev/null +++ b/src/features/external-migration/arrival-credentials.ts @@ -0,0 +1,441 @@ +import { DomainError } from "../../accounts/errors.js"; +import type { OperationOwnership } from "../../accounts/operation-ownership.js"; +import type { + BrowserAuthentication, + BrowserRequest, +} from "../../authentication/port.js"; +import type { ArrivalTransactor } from "../../database/migration-journal.port.js"; +import type { + ArrivalAggregate, + ArrivalOutcome, + ArrivalRecord, +} from "./arrival-types.js"; +import type { OperationClaim } from "../../database/operation-ownership.port.js"; +import { HttpError } from "../../http/http-error.mjs"; +import { + createArrivalOwner, + hasUnresolvedAttempt, + parseArrivalInput, + recoveryRequired, + versionConflict, +} from "./arrival-owner.js"; +import { createFreshArrivalProof } from "./fresh-proof.js"; +import { arrivalCodeHash } from "./prepare-arrival.js"; +import { isRecordedAdmissionGeneration } from "./arrival-types.js"; +import { incomingCreationMethod } from "./incoming-authorization.js"; + +/** Standard session fields for a bound, still-deactivated destination. */ +export interface TrackedArrivalSession { + readonly did: string; + readonly handle: string; + readonly email: string; + readonly emailConfirmed: true; + readonly didDoc: unknown; + readonly active: false; + readonly status: "deactivated"; + readonly accessJwt: string; + readonly refreshJwt: string; +} + +/** What the legacy credential signer provides. The arrival feature decides when + * a family may exist; the signer never reads arrival state. */ +export interface ArrivalFamilyCredentials { + prepare(input: { did: string; pdsId: string }): Promise<{ + familyId: string; + tokens: { accessJwt: string; refreshJwt: string }; + }>; + persist(minted: { familyId: string }): Promise; + revoke(familyIds: readonly string[], reason: string): Promise; + readAccess( + input: unknown, + ): Promise<{ familyId: string; did: string; pdsDid: string }>; + readRefresh(input: unknown): Promise<{ familyId: string; did: string }>; + refresh( + input: unknown, + resolve: { + account: (family: { + id: string; + did: string; + }) => Promise<{ did: string }>; + details: (account: { did: string }) => Promise>; + }, + ): Promise>; +} + +/** The authorized holder of a live tracked arrival credential. */ +export interface AuthorizedArrivalAccess { + readonly operationId: string; + readonly did: string; + readonly userId: string; + readonly familyId: string; +} + +const invalidToken = () => + new HttpError(400, "InvalidToken", "Invalid legacy session credential"); +const expiredToken = () => + new HttpError(400, "ExpiredToken", "Session expired or was revoked"); +const inactive = () => + new HttpError(409, "ArrivalExpired", "This arrival is no longer actionable"); + +/** Observed provisioning, deactivation and saved-user binding, and not finished. */ +export function assertBoundPending(aggregate: ArrivalAggregate): void { + const { arrival, progress } = aggregate; + if (arrival.cancelledAt !== null || progress.completedAt !== null) + throw inactive(); + if ( + progress.provisionedAt === null || + progress.deactivatedAt === null || + progress.boundAt === null + ) + throw new DomainError( + "OperationConflict", + 409, + "Credentials follow observed provisioning, deactivation and binding", + ); +} + +/** Tracked migration credentials. Family creation, association and (for + * recovery) prior-family revocation commit in one authority transaction; tokens + * are returned only after that commit. Ordinary login, account management and + * refresh keep their own rules and never see a pending arrival. */ +export function createArrivalCredentials({ + arrivals, + ownership, + transact, + signer, + readAccount, + readBinding, + readDocument, + placement, + authentication, + checkCsrf, + loadBrowser, + rateLimit, +}: { + arrivals: ArrivalTransactor; + ownership: OperationOwnership; + transact: (work: () => Promise) => Promise; + signer: ArrivalFamilyCredentials; + readAccount: (did: string) => Promise<{ + did: string; + email: string; + handle: string; + pdsId: string; + pdsUrl?: string; + status: string; + } | null>; + readBinding: (did: string) => Promise<{ userId: string } | null>; + readDocument: (did: string) => Promise; + /** Configured host for a placement, or undefined when it is not configured. */ + placement: (pdsId: string) => { url: string; did: string } | undefined; + authentication: BrowserAuthentication; + checkCsrf: (request: BrowserRequest, browser: unknown) => void; + loadBrowser: (request: BrowserRequest) => Promise; + rateLimit: (subject: string) => Promise; +}) { + const owner = createArrivalOwner({ arrivals, ownership }); + const requireFreshProof = createFreshArrivalProof({ + authentication, + checkCsrf, + loadBrowser, + rateLimit, + }); + const nextVersion = (outcome: ArrivalOutcome): number => { + if (outcome.kind === "reconciliation-required") + throw recoveryRequired( + "Credential association requires recovery; keep the arrival pending", + ); + return outcome.version; + }; + const sessionFields = async ( + arrival: ArrivalRecord, + ): Promise> => ({ + did: arrival.did, + handle: arrival.handle, + email: arrival.email, + emailConfirmed: true, + didDoc: await readDocument(arrival.did), + active: false, + status: "deactivated", + }); + /** Saved facts that must agree before a family may exist or be replaced. */ + const assertSavedFacts = async ( + aggregate: ArrivalAggregate, + { unresolved }: { unresolved: "refuse" | "allow" }, + ) => { + const { arrival } = aggregate; + const host = placement(arrival.pdsId); + if (!host || host.url !== arrival.endpoint) + throw new DomainError( + "OperationConflict", + 409, + "The saved arrival placement is not the configured host", + ); + const [account, binding] = await Promise.all([ + readAccount(arrival.did), + readBinding(arrival.did), + ]); + if ( + !account || + account.status !== "provisioning" || + account.email !== arrival.email || + account.handle !== arrival.handle || + account.pdsId !== arrival.pdsId + ) + throw new DomainError( + "OperationConflict", + 409, + "The saved account no longer matches this arrival", + ); + if (binding?.userId !== arrival.userId) + throw new DomainError( + "AccountMismatch", + 403, + "The saved user binding does not match this arrival", + ); + if (unresolved === "refuse" && hasUnresolvedAttempt(aggregate)) + throw recoveryRequired( + "An unresolved external attempt must be recovered before credentials change", + ); + }; + const install = async ( + claim: OperationClaim, + aggregate: ArrivalAggregate, + expectedVersion: number, + replace: boolean, + ): Promise => { + const arrival = aggregate.arrival; + if (arrival.version !== expectedVersion) throw versionConflict(); + assertBoundPending(aggregate); + await assertSavedFacts(aggregate, { unresolved: "refuse" }); + // Remote DID resolution and signing finish before the authority transaction. + const fields = await sessionFields(arrival); + const minted = await signer.prepare({ + did: arrival.did, + pdsId: arrival.pdsId, + }); + await transact(async () => { + const families = await arrivals.readArrivalFamilies(arrival.operationId); + if (!replace && families.length > 0) + throw new DomainError( + "OperationConflict", + 409, + "Credentials were already issued for this arrival; recover them with a fresh email code", + ); + let version = expectedVersion; + if (replace) { + // M3: the replacement and every prior family's revocation commit together. + await signer.revoke( + families + .filter((family) => family.revokedAt === null) + .map((family) => family.familyId), + "arrival-recovered", + ); + version = nextVersion( + await arrivals.revokeArrivalCredentialFamilies({ + owner: claim, + operationId: arrival.operationId, + expectedVersion: version, + }), + ); + } + await signer.persist(minted); + nextVersion( + await arrivals.recordCredentialFamily({ + owner: claim, + operationId: arrival.operationId, + expectedVersion: version, + familyId: minted.familyId, + did: arrival.did, + pdsId: arrival.pdsId, + }), + ); + }); + return { ...fields, ...minted.tokens } as unknown as TrackedArrivalSession; + }; + const identify = async ( + bearer: unknown, + ): Promise => { + const access = await signer.readAccess(bearer); + const tracked = await arrivals.readArrivalFamily(access.familyId); + const projection = await arrivals.readArrivalAccess(access.did); + if ( + !tracked || + !projection || + projection.operationId !== tracked.operationId || + projection.pdsId !== tracked.pdsId || + placement(projection.pdsId)?.did !== access.pdsDid + ) + throw invalidToken(); + if (tracked.revokedAt !== null) throw expiredToken(); + if (!projection.bound) + throw new HttpError(403, "AccountUnavailable", "Account is unavailable"); + return { + operationId: projection.operationId, + did: projection.did, + userId: projection.userId, + familyId: tracked.familyId, + complete: projection.complete, + }; + }; + return { + /** First tracked session for a bound-pending arrival, for the creation + * response. `userId` is the saved verified user from the normalized browser + * principal, never a request value. Wrong user and unknown operation are the + * same `AccountNotFound`. A second call is a conflict: use recovery. */ + async issueArrivalSession( + userId: string, + operationId: string, + expectedVersion: number, + ): Promise { + const parsed = parseArrivalInput({ operationId, expectedVersion }); + const initial = await owner.read(parsed.operationId, userId); + return owner.resume(initial.arrival, (claim, current) => + install(claim, current, parsed.expectedVersion, false), + ); + }, + /** First tracked session as the continuation of an accepted creation, for the + * standard `createAccount` response, which carries no browser cookie. + * + * Gating, from C1/C3: the saved user is never supplied. It is the user saved + * on the arrival, reached only through the current, unexpired arrival code + * (the capability preparation handed to the tool; renewal supersedes it and + * it is hashed at rest) for the same DID, so an operation id alone mints + * nothing. The arrival must also carry an accepted `createAccount` admission + * for that saved user and DID with a recorded code generation, and be bound. + * The caller (012) has already verified the source JWT at admission. The + * version is optional: the tool cannot know it, so it is read under the fence; + * a repeat issuance is still a conflict. */ + async issueCreationSession(input: { + did: string; + operationId: string; + arrivalCode: string; + }): Promise { + const refuse = () => + new HttpError( + 409, + "ArrivalExpired", + "This arrival code is no longer valid", + ); + if ( + typeof input?.arrivalCode !== "string" || + typeof input.did !== "string" || + typeof input.operationId !== "string" + ) + throw new HttpError(400, "InvalidRequest", "Invalid creation request"); + const record = await arrivals.consumeArrivalCode({ + codeHash: arrivalCodeHash(input.arrivalCode), + did: input.did, + method: incomingCreationMethod, + }); + if (record?.operationId !== input.operationId) throw refuse(); + const initial = await owner.read(record.operationId, record.userId); + return owner.resume(initial.arrival, (claim, current) => { + const accepted = current.admissions.find( + (item) => item.method === incomingCreationMethod, + ); + if ( + !accepted || + accepted.userId !== current.arrival.userId || + accepted.did !== current.arrival.did || + !isRecordedAdmissionGeneration( + accepted.generation, + current.arrival.generation, + ) + ) + throw new DomainError( + "AccountMismatch", + 403, + "An accepted saved creation is required", + ); + return install(claim, current, current.arrival.version, false); + }); + }, + /** Rotates a tracked refresh credential. Replay revokes its family as for + * ordinary sessions. Only a family tracked against a bound, unfinished + * arrival qualifies; other families keep the ordinary refresh route. */ + async refreshArrivalSession( + refreshCredential: unknown, + ): Promise { + const { familyId, did } = await signer.readRefresh(refreshCredential); + const tracked = await arrivals.readArrivalFamily(familyId); + const access = await arrivals.readArrivalAccess(did); + if (!tracked || !access || access.operationId !== tracked.operationId) + throw invalidToken(); + if (tracked.revokedAt !== null) throw expiredToken(); + const initial = await owner.read(access.operationId, access.userId); + assertBoundPending(initial); + const refreshed = await owner.resume( + initial.arrival, + async (_claim, current) => { + assertBoundPending(current); + await assertSavedFacts(current, { unresolved: "allow" }); + const stillTracked = async (family: { id: string }) => { + const saved = await arrivals.readArrivalFamily(family.id); + if ( + !saved || + saved.operationId !== current.arrival.operationId || + saved.pdsId !== current.arrival.pdsId + ) + throw invalidToken(); + if (saved.revokedAt !== null) throw expiredToken(); + }; + return signer.refresh(refreshCredential, { + account: async (family) => { + await stillTracked(family); + if (family.did !== current.arrival.did) throw invalidToken(); + return { did: family.did }; + }, + details: async () => sessionFields(current.arrival), + }); + }, + ); + return refreshed as unknown as TrackedArrivalSession; + }, + /** Saved-user recovery after a lost response or credential. Requires fresh + * destination proof for the same saved user and the exact saved version. It + * never requires a source JWT and never reprovisions anything. */ + async recoverArrivalSession( + request: BrowserRequest, + otp: string, + input: unknown, + ): Promise { + let parsed: { operationId: string; expectedVersion: number } | undefined; + const principal = await requireFreshProof( + request, + otp, + "incoming-recover", + () => { + parsed = parseArrivalInput(input); + }, + ); + const { operationId, expectedVersion } = parsed!; + const initial = await owner.read(operationId, principal.userId); + assertBoundPending(initial); + return owner.resume(initial.arrival, (claim, current) => + install(claim, current, expectedVersion, true), + ); + }, + /** Authorizes an arrival action from a live tracked access credential: exact + * subject, PDS audience, type and main-access scope, a tracked unrevoked + * family for this arrival, and a bound unfinished arrival. */ + async authorizeArrivalAccess( + bearer: unknown, + ): Promise { + const { complete, ...access } = await identify(bearer); + if (complete) + throw new HttpError( + 403, + "AccountUnavailable", + "Account is unavailable", + ); + return access; + }, + /** Like `authorizeArrivalAccess`, but also identifies a credential whose own + * tracked family belongs to a finished arrival, for retrying activation after + * a lost final response. It verifies exactly as before (live unrevoked family + * tracked against this arrival, same DID, host and scope pins), so it reveals + * nothing for any other bearer, and a cancelled arrival never qualifies. */ + identifyArrivalAccess: identify, + }; +} diff --git a/src/features/external-migration/arrival-lifecycle.test.mjs b/src/features/external-migration/arrival-lifecycle.test.mjs index d718247e..9ae49451 100644 --- a/src/features/external-migration/arrival-lifecycle.test.mjs +++ b/src/features/external-migration/arrival-lifecycle.test.mjs @@ -90,6 +90,7 @@ async function fixture() { { did: value, user_id: boundUser }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => accounts.activatePlacedAccount(subject), insertPlacedAccount: (input) => accounts.insertAccount( { diff --git a/src/features/external-migration/arrival-owner.ts b/src/features/external-migration/arrival-owner.ts new file mode 100644 index 00000000..f1c67881 --- /dev/null +++ b/src/features/external-migration/arrival-owner.ts @@ -0,0 +1,101 @@ +import { DomainError } from "../../accounts/errors.js"; +import { HttpError } from "../../http/http-error.mjs"; +import type { OperationOwnership } from "../../accounts/operation-ownership.js"; +import type { ArrivalTransactor } from "../../database/migration-journal.port.js"; +import type { OperationClaim } from "../../database/operation-ownership.port.js"; +import type { ArrivalAggregate, ArrivalRecord } from "./arrival-types.js"; + +export const notFound = () => + new DomainError("AccountNotFound", 404, "Arrival not found"); + +export const versionConflict = () => + new DomainError( + "OperationConflict", + 409, + "The saved arrival changed; reload the operation and retry", + ); + +export const recoveryRequired = (message: string) => + new DomainError("OperationRecoveryRequired", 409, message); + +/** Saved-arrival reads and live ownership for credential and activation work. + * The owner is the arrival's pending `arrival:` operation; every callback + * re-reads the aggregate after the fence is held, so earlier unowned reads can + * only select the operation, never authorize a change. */ +export function createArrivalOwner({ + arrivals, + ownership, +}: { + arrivals: ArrivalTransactor; + ownership: OperationOwnership; +}) { + /** Unknown operation and another user's operation are the same 404. */ + const read = async ( + operationId: string, + userId: string, + ): Promise => { + const aggregate = await arrivals.readArrivalAggregate(operationId, userId); + if (!aggregate) throw notFound(); + return aggregate; + }; + const resume = ( + saved: ArrivalRecord, + work: (owner: OperationClaim, current: ArrivalAggregate) => Promise, + ): Promise => + ownership.resumePending( + `arrival:${saved.did}`, + saved.operationId, + { + kind: "public-arrival", + request: { + did: saved.did, + handle: saved.handle, + userId: saved.userId, + }, + }, + async () => { + const owner = ownership.currentClaim; + if (!owner) + throw new DomainError( + "OperationLeaseLost", + 409, + "Arrival owner unavailable", + ); + await ownership.assertActive(); + return work(owner, await read(saved.operationId, saved.userId)); + }, + ); + return { read, resume }; +} + +/** Uncertainty that must be resolved before authority is added or replaced. */ +export const hasUnresolvedAttempt = (aggregate: ArrivalAggregate): boolean => + Boolean(aggregate.reservation?.uncertainReason) || + aggregate.attempts.some((attempt) => attempt.reason.startsWith("external:")); + +/** The one input shape for saved-user arrival operations. */ +export function parseArrivalInput(input: unknown): { + operationId: string; + expectedVersion: number; +} { + const value = input as Record | null; + if ( + !value || + typeof value !== "object" || + typeof value.operationId !== "string" || + value.operationId.length < 1 || + value.operationId.length > 200 || + typeof value.expectedVersion !== "number" || + !Number.isSafeInteger(value.expectedVersion) || + value.expectedVersion < 1 + ) + throw new HttpError( + 400, + "InvalidRequest", + "An operation and expected version are required", + ); + return { + operationId: value.operationId, + expectedVersion: value.expectedVersion, + }; +} diff --git a/src/features/external-migration/arrival-types.ts b/src/features/external-migration/arrival-types.ts index 7e9b013e..433303c3 100644 --- a/src/features/external-migration/arrival-types.ts +++ b/src/features/external-migration/arrival-types.ts @@ -102,7 +102,16 @@ export interface ArrivalExternalAttempt { readonly operationId: string; readonly did: string; readonly externalAttemptId: string; - readonly step: "incoming-creation" | "incoming-pause"; + readonly step: "incoming-creation" | "incoming-pause" | "incoming-activation"; +} + +/** One credential family tracked against an arrival. Metadata only: the + * signed tokens and the family's refresh state live in the legacy credential store. */ +export interface ArrivalCredentialFamily { + readonly familyId: string; + readonly operationId: string; + readonly pdsId: string; + readonly revokedAt: number | null; } export interface ArrivalReplayFacts { diff --git a/src/oauth/legacy-credentials.mjs b/src/oauth/legacy-credentials.mjs index e7aca817..151d6b79 100644 --- a/src/oauth/legacy-credentials.mjs +++ b/src/oauth/legacy-credentials.mjs @@ -412,21 +412,23 @@ export async function createLegacy({ db, config, accounts }) { } return { family }; }; - const refreshSession = async (input) => { + // `resolve` supplies the account for one family. Ordinary refresh requires a + // live account; migration-tracked refresh supplies its own pending-arrival checks. + const refreshWith = async (input, resolve) => { const payload = await parseToken(input, "refresh"); const initial = await transaction(async () => await refreshFamily(payload)); if (initial.error) throw initial.error; - const account = await currentAccount(initial.family); + const account = await resolve.account(initial.family); const timestamp = now(); const nextId = identifier(); const [details, tokens] = await Promise.all([ - sessionDetails(account), + resolve.details(account), tokensFor(initial.family, nextId, timestamp), ]); const committed = await transaction(async () => { const current = await refreshFamily(payload); if (current.error) return current; - await currentAccount(current.family); + await resolve.account(current.family); await set("refresh", payload.jti, { ...(await get("refresh", payload.jti)), usedAt: timestamp, @@ -446,6 +448,11 @@ export async function createLegacy({ db, config, accounts }) { if (committed.error) throw committed.error; return { ...details, ...tokens }; }; + const refreshSession = async (input) => + await refreshWith(input, { + account: currentAccount, + details: sessionDetails, + }); const deleteSession = async (input) => { const payload = await parseToken(input, "refresh", { allowExpired: true }); await transaction(async () => { @@ -610,7 +617,83 @@ export async function createLegacy({ db, config, accounts }) { throw new HttpError(404, "SessionNotFound", "Session not found"); await invalidateFamily(family, "account-session-revoked"); }); + // Migration-tracked families (incoming arrivals). These helpers never decide + // whether an arrival may hold credentials and never open their own association: + // the arrival feature calls them inside the one transaction that also records + // the family against its arrival, so a family cannot persist untracked. + const arrivalSessions = { + /** Signs a first family for a bound-pending account. Persists nothing, so a + * failed later step leaves no usable family and no token ever leaves. */ + async prepare({ did, pdsId }) { + const pds = config.pds.find((candidate) => candidate.id === pdsId); + if (!pds) + throw new HttpError( + 403, + "AccountUnavailable", + "Account PDS is unavailable", + ); + const timestamp = now(); + const family = { + id: identifier(), + did, + pdsDid: pds.did, + scope: LEGACY_SCOPES.access, + currentJti: identifier(), + createdAt: timestamp, + lastRefreshedAt: timestamp, + expiresAt: timestamp + REFRESH_SECONDS, + }; + return { + familyId: family.id, + family, + tokens: await tokensFor(family, family.currentJti, timestamp), + }; + }, + /** Must run inside the caller's authority transaction. */ + async persist({ family }) { + await set("sessions", family.id, family); + await set("refresh", family.currentJti, { + familyId: family.id, + did: family.did, + expiresAt: family.expiresAt, + }); + }, + /** Must run inside the caller's authority transaction. */ + async revoke(familyIds, reason) { + for (const id of familyIds) + await invalidateFamily(await get("sessions", id), reason); + }, + /** Stateless token checks plus a live family, without any account-status + * rule. Exact subject, PDS audience, type and main-access scope are required; + * app-password scopes are never an arrival credential. */ + async readAccess(input) { + const payload = await parseToken(input, "access"); + if (payload.exp <= now()) throw revoked(); + const family = await get("sessions", payload.sid); + if (!familyActive(family)) throw revoked(); + if ( + family.did !== payload.sub || + family.pdsDid !== payload.aud || + family.scope !== payload.scope || + payload.scope !== LEGACY_SCOPES.access || + family.appPasswordId !== undefined + ) + throw invalid(); + return { familyId: family.id, did: family.did, pdsDid: family.pdsDid }; + }, + /** Verifies a refresh credential's signature, type, audience and shape only. */ + async readRefresh(input) { + const payload = await parseToken(input, "refresh"); + return { familyId: payload.sid, did: payload.sub }; + }, + /** Replay and rotation follow the ordinary rules; `account` and `details` + * replace the live-account check with the caller's pending-arrival checks. */ + async refresh(input, resolve) { + return await refreshWith(input, resolve); + }, + }; return { + arrivalSessions, setPassword, removePassword, hasPassword, diff --git a/src/pds/arrival-client.ts b/src/pds/arrival-client.ts index 1f634bf4..6edc6c70 100644 --- a/src/pds/arrival-client.ts +++ b/src/pds/arrival-client.ts @@ -142,6 +142,18 @@ export class ArrivalPdsClient { }; } public async pauseAccount(authorization: () => string): Promise { + await this.#setDeactivated(authorization, true); + } + /** The existing lifecycle hook with `applied: false`; stock `activateAccount` + * delegates to Entryway, so this administrator call is the one backend effect + * of guarded activation. */ + public async activateAccount(authorization: () => string): Promise { + await this.#setDeactivated(authorization, false); + } + async #setDeactivated( + authorization: () => string, + applied: boolean, + ): Promise { const method = "com.atproto.admin.updateSubjectStatus"; const response = await fetch(this.#url(method), { method: "POST", @@ -154,7 +166,7 @@ export class ArrivalPdsClient { $type: "com.atproto.admin.defs#repoRef", did: this.options.did, }, - deactivated: { applied: true }, + deactivated: { applied }, }), redirect: "error", signal: AbortSignal.timeout(30_000), diff --git a/tests/contracts/incoming-activation.test.mjs b/tests/contracts/incoming-activation.test.mjs new file mode 100644 index 00000000..a5b47336 --- /dev/null +++ b/tests/contracts/incoming-activation.test.mjs @@ -0,0 +1,770 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import * as plc from "@did-plc/lib"; +import { cidForCbor } from "@atproto/common"; +import { + fixture, + admitProvisioning, +} from "../support/helpers/incoming-arrival-fixture.mjs"; +import { query, verifiedUser } from "../support/database-fixture.mjs"; +import { createOperationOwnership } from "../../dist/src/accounts/operation-ownership.js"; +import { createOperationOwnershipStore } from "../../dist/src/database/drizzle/operation-ownership.js"; +import { assertActivationReady } from "../../dist/src/features/external-migration/activation-checks.js"; + +const codeOf = (error) => error.code ?? error.error; +const hasCode = (code) => (error) => codeOf(error) === code; + +async function bound(t, { issued = true } = {}) { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + const op = prepared.operationId; + const result = await f.composed.continueCreation(f.request, op); + assert.equal(result.state, "pending"); + const session = issued + ? await f.composed.issueArrivalSession(f.request, op, result.version) + : null; + return { f, op, session }; +} +const version = async (f, op) => + (await f.arrivals.readArrivalAggregate(op, f.principal.userId)).arrival + .version; +const asUser = async (f, op, expected, otp = "fresh-otp") => + f.composed.activateArrivalAsUser(f.request, otp, { + operationId: op, + expectedVersion: expected ?? (await version(f, op)), + }); +const accountStatus = async (f) => + (await query(f.db, "SELECT status FROM accounts"))[0].status; +const activationRows = (f) => + query(f.db, "SELECT id FROM external_operation_attempts"); +const activationAttempts = (f) => + query( + f.db, + "SELECT id FROM external_operation_attempts WHERE step = 'incoming-activation'", + ); +const approveObserve = async (f) => { + const pending = await f.store.pendingExternal(`arrival:${f.did}`); + await f.store.approveRecovery({ + operationId: pending.operationId, + externalAttemptId: pending.id, + executionAttemptId: pending.executionAttemptId, + target: pending.target, + dispatcherIsolationReference: "test-dispatcher-isolated", + upstreamDrainReference: "test-upstream-drained", + action: "observe", + }); +}; +/** A refusal sends nothing, journals nothing and completes nothing. */ +const assertUntouched = async (f, op) => { + assert.equal(f.backendState.activations, 0); + assert.equal((await activationAttempts(f)).length, 0); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); + assert.equal(await f.store.pendingExternal(`arrival:${f.did}`), null); + assert.ok(op); +}; + +test("saved-user activation journals, observes the backend and completes local authority once", async (t) => { + const { f, op, session } = await bound(t); + const effects = { + creates: f.backendState.creates, + pauses: f.backendState.pauses, + reservations: f.reservations(), + publications: f.publicationAttempts.length, + credentials: f.credentialsIssued(), + }; + const result = await asUser(f, op); + assert.equal(result.state, "active"); + assert.equal(result.operationId, op); + assert.equal(f.backendState.activations, 1); + assert.equal(f.backendState.deactivated, false); + assert.equal(await accountStatus(f), "active"); + const access = await f.arrivals.readArrivalAccess(f.did); + assert.equal(access.complete, true); + assert.equal(access.unresolvedAttempt, false); + assert.equal(result.version, access.version); + assert.deepEqual( + { + creates: f.backendState.creates, + pauses: f.backendState.pauses, + reservations: f.reservations(), + publications: f.publicationAttempts.length, + credentials: f.credentialsIssued(), + }, + effects, + ); + assert.equal( + (await query(f.db, "SELECT * FROM operation_admissions")).length, + 0, + ); + // A lost response retries into the committed result with no new effect. + assert.deepEqual(await asUser(f, op, result.version), result); + assert.equal(f.backendState.activations, 1); + // The tracked family is now an ordinary account session. + assert.equal( + (await f.legacy.verifyAccess(session.accessJwt)).account.did, + f.did, + ); + await assert.rejects( + f.composed.authorizeArrivalAccess(session.accessJwt), + hasCode("AccountUnavailable"), + ); +}); + +test("an authorized client activates with its live tracked access credential", async (t) => { + const { f, op, session } = await bound(t); + const result = await f.composed.activateArrivalWithCredential( + session.accessJwt, + ); + assert.equal(result.state, "active"); + assert.equal(result.operationId, op); + assert.equal(f.backendState.activations, 1); + assert.equal(await accountStatus(f), "active"); + // A lost final response: the same credential retries into the committed result. + const effects = [ + f.backendState.activations, + f.backendState.calls.length, + (await activationRows(f)).length, + ]; + const aggregate = await f.arrivals.readArrivalAggregate( + op, + f.principal.userId, + ); + assert.deepEqual( + await f.composed.activateArrivalWithCredential(session.accessJwt), + result, + ); + assert.deepEqual( + [ + f.backendState.activations, + f.backendState.calls.length, + (await activationRows(f)).length, + ], + effects, + ); + assert.deepEqual( + await f.arrivals.readArrivalAggregate(op, f.principal.userId), + aggregate, + ); + // The pending-only authorization is unchanged for a finished arrival. + await assert.rejects( + f.composed.authorizeArrivalAccess(session.accessJwt), + hasCode("AccountUnavailable"), + ); +}); + +test("after completion only the arrival's own live tracked family may retry", async (t) => { + const { f, op, session } = await bound(t); + const done = await f.composed.activateArrivalWithCredential( + session.accessJwt, + ); + const reads = f.backendState.calls.length; + // Another bearer, an unrelated ordinary session and a replaced family get nothing. + const unrelated = await f.legacy.createAccountSession(f.did); + await assert.rejects( + f.composed.activateArrivalWithCredential(unrelated.accessJwt), + (error) => ["InvalidToken", "AccountUnavailable"].includes(codeOf(error)), + ); + await assert.rejects( + f.composed.activateArrivalWithCredential(session.refreshJwt), + hasCode("InvalidToken"), + ); + await assert.rejects( + f.composed.activateArrivalWithCredential("not-a-token"), + hasCode("InvalidToken"), + ); + await query(f.db, "UPDATE arrival_families SET revoked_at = 1", [], "run"); + await assert.rejects( + f.composed.activateArrivalWithCredential(session.accessJwt), + hasCode("ExpiredToken"), + ); + assert.equal(f.backendState.calls.length, reads); + assert.equal(done.state, "active"); + assert.ok(op); +}); + +test("a family tracked for another host cannot retry a finished arrival", async (t) => { + const { f, session } = await bound(t); + await f.composed.activateArrivalWithCredential(session.accessJwt); + await query(f.db, "UPDATE arrival_families SET pds_id = 'pds2'", [], "run"); + await assert.rejects( + f.composed.activateArrivalWithCredential(session.accessJwt), + hasCode("InvalidToken"), + ); +}); + +test("credential activation refuses refresh tokens, replaced families and unknown bearers without dispatch", async (t) => { + const { f, op, session } = await bound(t); + await assert.rejects( + f.composed.activateArrivalWithCredential(session.refreshJwt), + hasCode("InvalidToken"), + ); + await assert.rejects( + f.composed.activateArrivalWithCredential("not-a-token"), + hasCode("InvalidToken"), + ); + await f.composed.recoverArrivalSession(f.request, "fresh-otp", { + operationId: op, + expectedVersion: await version(f, op), + }); + await assert.rejects( + f.composed.activateArrivalWithCredential(session.accessJwt), + hasCode("ExpiredToken"), + ); + await assertUntouched(f, op); +}); + +test("intent without authority is refused: stale proof, version, wrong owner and unbound arrival", async (t) => { + const { f, op } = await bound(t); + const current = await version(f, op); + await assert.rejects( + asUser(f, op, current, "stale"), + hasCode("ArrivalProofRequired"), + ); + await assert.rejects( + asUser(f, op, current + 1), + hasCode("OperationConflict"), + ); + const unknown = await asUser(f, "no-such-operation", 1).catch((e) => e); + f.principal.userId = "someone-else"; + const wrongOwner = await asUser(f, op, current).catch((e) => e); + f.principal.userId = "destination-user"; + assert.equal(codeOf(unknown), "AccountNotFound"); + assert.equal(codeOf(wrongOwner), "AccountNotFound"); + assert.equal(wrongOwner.message, unknown.message); + await assertUntouched(f, op); +}); + +test("activation is refused before the arrival is bound", async (t) => { + const early = await fixture(t); + const prepared = await admitProvisioning(early); + await assert.rejects( + asUser(early, prepared.operationId), + hasCode("OperationConflict"), + ); + assert.equal(early.backendState.activations, 0); + assert.equal((await activationAttempts(early)).length, 0); +}); + +const moveHead = async (f) => { + const last = f.audit.at(-1); + const next = await plc.createUpdateOp(last.operation, f.hot, (n) => ({ + ...n, + alsoKnownAs: [...n.alsoKnownAs, "at://other.example.test"], + })); + f.audit.push({ + did: f.did, + cid: String(await cidForCbor(next)), + operation: next, + nullified: false, + createdAt: new Date().toISOString(), + }); +}; + +const refusals = [ + ["canonical head moved past the saved move", "IdentityConflict", moveHead], + [ + "saved move is not the canonical head", + "IdentityConflict", + async (f) => { + await query( + f.db, + "UPDATE arrival_signed_operations SET cid = 'bafyother' WHERE kind = 'destination-move'", + [], + "run", + ); + }, + ], + [ + "saved user binding changed", + "AccountMismatch", + async (f) => { + await verifiedUser(f.db, "other-user", "other@example.test"); + await query( + f.db, + "UPDATE account_bindings SET user_id = 'other-user'", + [], + "run", + ); + }, + ], + [ + "backend absent", + "AccountUnavailable", + async (f) => { + f.backendState.exists = false; + }, + ], + [ + "backend identity differs", + "AccountUnavailable", + async (f) => { + f.backendState.mode = "wrong-did"; + }, + ], + [ + "backend already active without a journaled activation", + "OperationRecoveryRequired", + async (f) => { + f.backendState.deactivated = false; + }, + ], + [ + "unresolved external attempt", + "OperationRecoveryRequired", + async (f) => { + await query( + f.db, + "INSERT INTO arrival_attempts (attempt_binding, ownership_operation_id, attempt_id, operation_id, reason, recorded_at, fence) SELECT 'b', operation_id, 'a', operation_id, 'external:incoming-pause', 1, 1 FROM arrivals", + [], + "run", + ); + }, + ], + [ + "account no longer provisioning", + "OperationConflict", + async (f) => { + await query( + f.db, + "UPDATE accounts SET status = 'deactivated', data = replace(data, '\"provisioning\"', '\"deactivated\"')", + [], + "run", + ); + }, + ], +]; +for (const [name, code, mutate] of refusals) + test(`activation refuses ${name} without dispatch`, async (t) => { + const { f, op } = await bound(t); + await mutate(f); + await assert.rejects(asUser(f, op), hasCode(code)); + assert.equal(f.backendState.activations, 0); + assert.equal((await activationAttempts(f)).length, 0); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); + }); + +test("changed placement and unavailable backend refuse without dispatch", async (t) => { + const { f, op } = await bound(t); + f.config.pds[0].url = "https://elsewhere.example.test"; + await assert.rejects(asUser(f, op), hasCode("OperationConflict")); + f.config.pds[0].url = "https://destination.example.test"; + f.backendState.mode = "network"; + await assert.rejects(asUser(f, op), hasCode("AccountUnavailable")); + f.backendState.mode = "normal"; + await assertUntouched(f, op); +}); + +test("a lost activation acknowledgement keeps uncertainty until recovery observes the exact effect", async (t) => { + const { f, op } = await bound(t); + f.backendState.mode = "activation-lost"; + await assert.rejects(asUser(f, op), hasCode("AccountUnavailable")); + assert.equal(f.backendState.activations, 1); + assert.equal(f.backendState.deactivated, false); + f.backendState.mode = "normal"; + // The backend status already matches, but status alone never completes. + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); + assert.equal(f.backendState.activations, 1); + await approveObserve(f); + const result = await asUser(f, op); + assert.equal(result.state, "active"); + assert.equal(f.backendState.activations, 1); + assert.equal(await accountStatus(f), "active"); + assert.equal( + (await f.arrivals.readArrivalAccess(f.did)).unresolvedAttempt, + false, + ); +}); + +const receipts = (f) => + query( + f.db, + "SELECT state, result FROM external_operation_attempts WHERE step = 'incoming-activation' ORDER BY created_at", + ); + +test("an accepted but unobserved activation leaves its receipt unresolved", async (t) => { + const { f, op } = await bound(t); + f.backendState.mode = "activation-ignored"; + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); + // Not acknowledged: the inside-send observation decides, not the later check. + assert.deepEqual( + (await receipts(f)).map((row) => row.state), + ["dispatched"], + ); +}); + +for (const mode of ["activation-rejected", "activation-dropped"]) + test(`a ${mode} activation stays unresolved, is not blindly observed applied, and one approved retry completes`, async (t) => { + const { f, op } = await bound(t); + f.backendState.mode = mode; + await assert.rejects(asUser(f, op), hasCode("AccountUnavailable")); + assert.equal(f.backendState.activations, 1); + assert.equal(f.backendState.deactivated, true); + // Second call stops at the pending receipt with no new backend write. + f.backendState.mode = "normal"; + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(f.backendState.activations, 1); + const pending = await f.store.pendingExternal(`arrival:${f.did}`); + const approval = { + operationId: pending.operationId, + externalAttemptId: pending.id, + executionAttemptId: pending.executionAttemptId, + target: pending.target, + dispatcherIsolationReference: "test-dispatcher-isolated", + upstreamDrainReference: "test-upstream-drained", + }; + await f.store.approveRecovery({ ...approval, action: "observe" }); + // Observation finds it unapplied: that is not acknowledged and not retried. + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(f.backendState.activations, 1); + assert.deepEqual( + (await receipts(f)).map((row) => row.state), + ["recovery-approved"], + ); + assert.equal(await accountStatus(f), "provisioning"); + const latest = await f.store.pendingExternal(`arrival:${f.did}`); + await f.store.approveRecovery({ + ...approval, + action: "retry-if-safe", + previousAuthorization: latest.recovery, + }); + assert.equal((await asUser(f, op)).state, "active"); + assert.equal(f.backendState.activations, 2); + const access = await f.arrivals.readArrivalAccess(f.did); + assert.equal(access.complete, true); + // The superseded attempt's association is retired with the replacement. + assert.equal(access.unresolvedAttempt, false); + }); + +test("a backend made active by another actor before send is not completed by status match", async (t) => { + const { f, op } = await bound(t); + const checks = f.backendState; + const before = checks.onActivate; + assert.equal(before, null); + // Becomes active after the precheck: intercept the first activation-free send + // by flipping state during the journaling read. + const resume = f.ownership.dispatch.bind(f.ownership); + f.ownership.dispatch = async (input, callbacks) => { + f.backendState.deactivated = false; + return resume(input, callbacks); + }; + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(f.backendState.activations, 0); + assert.deepEqual( + (await receipts(f)).map((row) => row.state), + ["dispatched"], + ); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); +}); + +test("canonical identity is rechecked after dispatch before authority completes", async (t) => { + const { f, op } = await bound(t); + f.backendState.onActivate = () => moveHead(f); + await assert.rejects(asUser(f, op), hasCode("IdentityConflict")); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); +}); + +test("a family replaced before the fence cannot activate", async (t) => { + const { f, session } = await bound(t); + const resume = f.ownership.resumePending.bind(f.ownership); + f.ownership.resumePending = async (...args) => { + f.ownership.resumePending = resume; + await query(f.db, "UPDATE arrival_families SET revoked_at = 1", [], "run"); + return resume(...args); + }; + await assert.rejects( + f.composed.activateArrivalWithCredential(session.accessJwt), + hasCode("ExpiredToken"), + ); + assert.equal(f.backendState.activations, 0); + assert.equal((await activationAttempts(f)).length, 0); +}); + +test("a delayed data write is neither serialized nor certified by activation", async (t) => { + const { f, op } = await bound(t); + const before = f.backendState.calls.length; + f.backendState.onActivate = async () => { + // A transfer write landing mid-activation is accepted by the backend. + await fetch( + "https://destination.example.test/xrpc/com.atproto.repo.importRepo", + { method: "POST" }, + ); + }; + assert.equal((await asUser(f, op)).state, "active"); + assert.equal(f.backendState.dataWrites, 1); + // Entryway read no repository or blob inventory: only status observation, + // the one activation write and the delayed client write were sent. + assert.deepEqual([...new Set(f.backendState.calls.slice(before))].sort(), [ + "com.atproto.admin.getAccountInfo", + "com.atproto.admin.updateSubjectStatus", + "com.atproto.repo.importRepo", + ]); + assert.equal(f.backendState.activations, 1); +}); + +test("a lost local commit resumes the exact acknowledged operation without a second backend write", async (t) => { + const { f, op } = await bound(t); + const original = f.storage.activatePlacedAccount; + f.storage.activatePlacedAccount = async () => { + throw new Error("local commit lost"); + }; + await assert.rejects(asUser(f, op), /local commit lost/); + f.storage.activatePlacedAccount = original; + // Nothing partial: arrival, attempt settlement and account all rolled back. + assert.equal(await accountStatus(f), "provisioning"); + const access = await f.arrivals.readArrivalAccess(f.did); + assert.equal(access.complete, false); + assert.equal(access.unresolvedAttempt, true); + assert.equal(f.backendState.activations, 1); + const result = await asUser(f, op); + assert.equal(result.state, "active"); + assert.equal(f.backendState.activations, 1); + assert.equal(await accountStatus(f), "active"); + assert.equal( + (await f.arrivals.readArrivalAccess(f.did)).unresolvedAttempt, + false, + ); +}); + +test("a backend paused again before the local commit is not completed as active", async (t) => { + const { f, op } = await bound(t); + const original = f.storage.activatePlacedAccount; + f.storage.activatePlacedAccount = async () => { + throw new Error("local commit lost"); + }; + await assert.rejects(asUser(f, op), /local commit lost/); + f.storage.activatePlacedAccount = original; + assert.equal(f.backendState.activations, 1); + // The activation was acknowledged, then something paused the backend again. + f.backendState.deactivated = true; + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); + assert.equal(f.backendState.activations, 1); +}); + +test("a stale owner cannot finish activation", async (t) => { + const { f, op } = await bound(t); + f.backendState.onActivate = async () => { + f.backendState.onActivate = null; + await query( + f.db, + "UPDATE authority_operations SET lease_expires_at = 1 WHERE pending = 1", + [], + "run", + ); + const successor = createOperationOwnership({ + store: createOperationOwnershipStore(f.db), + heartbeatMs: 0, + }); + await successor.resumePending( + `arrival:${f.did}`, + op, + { + kind: "public-arrival", + request: { + did: f.did, + handle: "destination.example.test", + userId: "destination-user", + }, + }, + async () => {}, + ); + }; + await assert.rejects(asUser(f, op), hasCode("OperationLeaseLost")); + assert.equal(await accountStatus(f), "provisioning"); + assert.equal((await f.arrivals.readArrivalAccess(f.did)).complete, false); + assert.equal(f.backendState.activations, 1); + assert.deepEqual( + (await receipts(f)).map((row) => row.state), + ["dispatched"], + ); + // A fresh owner must recover the receipt; it sends nothing new. + await assert.rejects(asUser(f, op), hasCode("OperationRecoveryRequired")); + assert.equal(f.backendState.activations, 1); +}); + +const ready = (over = {}) => { + const arrival = { + did: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", + handle: "me.example.test", + email: "me@example.test", + pdsId: "pds1", + endpoint: "https://pds.example.test", + userId: "user", + signingKey: "did:key:zRepo", + approvedRotationKeys: ["did:key:zA", "did:key:zB"], + }; + return { + arrival, + move: { cid: "cid-move" }, + directory: { + sourcePlcHead: "cid-move", + rotationKeys: ["did:key:zA", "did:key:zB"], + source: { + services: { + atproto_pds: { + type: "AtprotoPersonalDataServer", + endpoint: "https://pds.example.test", + }, + }, + verificationMethods: { atproto: "did:key:zRepo" }, + alsoKnownAs: ["at://me.example.test"], + }, + }, + account: { + did: arrival.did, + email: arrival.email, + handle: arrival.handle, + pdsId: "pds1", + pdsUrl: "https://pds.example.test", + status: "provisioning", + }, + binding: { userId: "user" }, + configuredEndpoint: "https://pds.example.test", + backend: { did: arrival.did, handle: arrival.handle, deactivated: true }, + activationJournaled: false, + ...over, + }; +}; +const withDirectory = (patch) => { + const base = ready(); + return { + directory: { + ...base.directory, + ...patch, + source: { ...base.directory.source, ...(patch.source ?? {}) }, + }, + }; +}; + +test("activation readiness accepts exactly the saved canonical facts", () => { + assert.doesNotThrow(() => assertActivationReady(ready())); + // A resumed, journaled activation may already see an active backend. + assert.doesNotThrow(() => + assertActivationReady( + ready({ + activationJournaled: true, + backend: { ...ready().backend, deactivated: false }, + }), + ), + ); +}); + +for (const [name, code, over] of [ + ["head", "IdentityConflict", withDirectory({ sourcePlcHead: "other" })], + [ + "endpoint", + "IdentityConflict", + withDirectory({ + source: { + services: { + atproto_pds: { + type: "AtprotoPersonalDataServer", + endpoint: "https://other.example.test", + }, + }, + }, + }), + ], + [ + "service type", + "IdentityConflict", + withDirectory({ + source: { + services: { + atproto_pds: { type: "Other", endpoint: "https://pds.example.test" }, + }, + }, + }), + ], + [ + "repository key", + "IdentityConflict", + withDirectory({ + source: { verificationMethods: { atproto: "did:key:zOther" } }, + }), + ], + [ + "rotation custody removed", + "IdentityConflict", + withDirectory({ rotationKeys: ["did:key:zA"] }), + ], + [ + "rotation custody reordered", + "IdentityConflict", + withDirectory({ rotationKeys: ["did:key:zB", "did:key:zA"] }), + ], + [ + "handle", + "IdentityConflict", + withDirectory({ source: { alsoKnownAs: ["at://other.example.test"] } }), + ], + [ + "configured host", + "OperationConflict", + { configuredEndpoint: "https://x.example.test" }, + ], + ["missing host", "OperationConflict", { configuredEndpoint: undefined }], + ["missing account", "OperationConflict", { account: null }], + [ + "account status", + "OperationConflict", + { account: { ...ready().account, status: "active" } }, + ], + [ + "account email", + "OperationConflict", + { account: { ...ready().account, email: "x@example.test" } }, + ], + [ + "account handle", + "OperationConflict", + { account: { ...ready().account, handle: "x.example.test" } }, + ], + [ + "account placement", + "OperationConflict", + { account: { ...ready().account, pdsId: "pds2" } }, + ], + [ + "account host", + "OperationConflict", + { account: { ...ready().account, pdsUrl: "https://x.example.test" } }, + ], + ["missing binding", "AccountMismatch", { binding: null }], + ["binding user", "AccountMismatch", { binding: { userId: "other" } }], + ["missing backend", "AccountUnavailable", { backend: null }], + [ + "backend did", + "AccountUnavailable", + { backend: { ...ready().backend, did: "did:plc:x" } }, + ], + [ + "backend handle", + "AccountUnavailable", + { backend: { ...ready().backend, handle: "x.example.test" } }, + ], + [ + "backend active unjournaled", + "OperationRecoveryRequired", + { backend: { ...ready().backend, deactivated: false } }, + ], + [ + "missing reserved key", + "IdentityConflict", + { arrival: { ...ready().arrival, signingKey: null } }, + ], +]) + test(`activation readiness refuses a wrong ${name}`, () => { + assert.throws( + () => assertActivationReady(ready(over)), + (error) => error.code === code, + ); + }); diff --git a/tests/contracts/incoming-arrival-admission.test.mjs b/tests/contracts/incoming-arrival-admission.test.mjs index e06e201e..5a0d6f9f 100644 --- a/tests/contracts/incoming-arrival-admission.test.mjs +++ b/tests/contracts/incoming-arrival-admission.test.mjs @@ -1,3 +1,4 @@ +import { createLegacy } from "../../dist/src/oauth/legacy-credentials.mjs"; import assert from "node:assert/strict"; import test from "node:test"; import { generateKeyPairSync } from "node:crypto"; @@ -75,6 +76,7 @@ async function fixture() { { did: value, user_id: userId }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => accounts.activatePlacedAccount(subject), insertPlacedAccount: (input) => accounts.insertAccount( { @@ -165,6 +167,7 @@ async function admissionFixture(required = true) { arrivals: f.arrivals, config, accounts, + legacy: await createLegacy({ db: f.db, config, accounts }), browserFlow: { checkCsrf() {}, loadBrowser() {} }, }); const arrival = await f.prepare(); diff --git a/tests/contracts/incoming-arrival-composition.test.mjs b/tests/contracts/incoming-arrival-composition.test.mjs index a58760ac..6d7c36e1 100644 --- a/tests/contracts/incoming-arrival-composition.test.mjs +++ b/tests/contracts/incoming-arrival-composition.test.mjs @@ -1,446 +1,32 @@ -import { Secp256k1MigrationPlcSigner } from "../../dist/src/plc/signing.js"; import assert from "node:assert/strict"; import test from "node:test"; -import { generateKeyPairSync } from "node:crypto"; -import { createServiceJwt } from "@atproto/xrpc-server"; import { incomingHandoffMethod, incomingCreationMethod, } from "../../dist/src/features/external-migration/incoming-authorization.js"; import { arrivalCodeHash } from "../../dist/src/features/external-migration/prepare-arrival.js"; import { parseArrivalRequest } from "../../dist/src/features/external-migration/arrival-request.js"; -import { mkdtempSync, rmSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; import { eq } from "drizzle-orm"; -import { Secp256k1Keypair } from "@atproto/crypto"; import { cidForCbor } from "@atproto/common"; import * as plc from "@did-plc/lib"; import { ArrivalPdsClient } from "../../dist/src/pds/arrival-client.js"; -import { composeIncomingArrival } from "../../dist/src/compose-incoming-arrival.mjs"; -import { createBrowserFlow } from "../../dist/src/http/browser-flow.mjs"; import { createOperationOwnership } from "../../dist/src/accounts/operation-ownership.js"; import { createOperationOwnershipStore } from "../../dist/src/database/drizzle/operation-ownership.js"; -import { createAccountStorage } from "../../dist/src/database/drizzle/account-storage.js"; -import { createArrivalStorage } from "../../dist/src/database/drizzle/migration-arrival.js"; import { validateIncomingHandoff } from "../../dist/src/plc/policy.js"; import { failureTrigger, removeFailureTrigger, hasFailure, - openTestDatabase, - verifiedUser, query, } from "../support/database-fixture.mjs"; - -const endpoint = "https://destination.example.test"; -const sourceEndpoint = "https://source.example.test"; -const email = "destination@example.test"; -const handle = "destination.example.test"; - -async function fixture(t, mode = "modern", mutation = "", fault = "") { - const directory = mkdtempSync(join(tmpdir(), "arrival-preparation-")); - const path = join(directory, "authority.sqlite"); - let db = await openTestDatabase(path); - t.after(async () => { - await db.close(); - rmSync(directory, { recursive: true, force: true }); - }); - const source = await Secp256k1Keypair.create(); - const recovery = await Secp256k1Keypair.create(); - const hot = await Secp256k1Keypair.create({ exportable: true }); - const repository = await Secp256k1Keypair.create(); - let predecessor; - if (mode === "legacy") { - predecessor = await plc.deprecatedSignCreate( - { - type: "create", - signingKey: source.did(), - recoveryKey: recovery.did(), - handle, - service: sourceEndpoint, - prev: null, - }, - recovery, - ); - } else { - const keys = [recovery.did(), source.did()]; - if (mutation === "full") - for (let index = 0; index < 3; index++) - keys.push((await Secp256k1Keypair.create()).did()); - predecessor = await plc.signOperation( - plc.formatAtprotoOp({ - signingKey: source.did(), - handle: mutation === "distinct-handle" ? "source.example.test" : handle, - pds: sourceEndpoint, - rotationKeys: keys, - prev: null, - }), - recovery, - ); - } - const did = await plc.didForCreateOp(predecessor); - const head = String(await cidForCbor(predecessor)); - const audit = [ - { - did, - cid: head, - operation: predecessor, - nullified: false, - createdAt: new Date().toISOString(), - }, - ]; - if (mutation === "wrong-did") audit[0].did = `did:plc:${"a".repeat(24)}`; - if (mutation === "signature") { - audit[0].operation = { ...predecessor, sig: "invalid" }; - audit[0].cid = String(await cidForCbor(audit[0].operation)); - } - if (mutation === "cid") audit[0].cid = "wrong"; - if (mutation === "nullified") audit[0].nullified = true; - if (mutation === "tombstone") { - const operation = await plc.signOperation( - { type: "plc_tombstone", prev: head }, - source, - ); - audit.push({ - did, - operation, - cid: String(await cidForCbor(operation)), - nullified: false, - createdAt: new Date().toISOString(), - }); - } - const hosts = [ - { id: "pds1", url: endpoint, did: "did:web:destination.example.test" }, - ]; - const storage = createAccountStorage(db, hosts); - const arrivalStorage = () => - createArrivalStorage(db, hosts, { - readAccount: (value) => storage.getByDid(value), - readBinding: (value) => storage.getVerifiedBinding(value), - reserveEmailClaim: (...args) => storage.reserveEmail(...args), - reserveHandleClaim: (...args) => storage.reserveHandle(...args), - recordSavedUserBinding: (subject, userId) => - db.insert( - "account_bindings", - { did: subject, user_id: userId }, - { ignoreConflict: true }, - ), - insertPlacedAccount: (input) => - storage.insertAccount( - { - did: input.did, - email: input.email, - emailVerified: true, - handle: input.handle, - pdsId: input.pdsId, - pdsUrl: input.pdsUrl, - status: "provisioning", - createdAt: new Date().toISOString(), - }, - input.userId, - ), - }); - const arrivals = arrivalStorage(); - if (fault.startsWith("after-commit")) - arrivals.recordAllocationIntent = async () => { - throw new Error("interrupted before allocation intent"); - }; - await verifiedUser(db, "destination-user", email); - const principal = { - userId: "destination-user", - email, - emailVerified: true, - sessionId: "session", - kind: "better-auth", - authenticatedAt: new Date(), - }; - let verifications = 0; - const authentication = { - requireSession: async () => principal, - verifySignInCode: async ({ email: destinationEmail, otp }) => { - verifications++; - assert.equal(destinationEmail, email); - return { - ok: otp === "fresh-otp", - principal: { - ...principal, - ...(mutation === "wrong-user" ? { userId: "other-user" } : {}), - }, - }; - }, - }; - const config = { - inviteCodeRequired: true, - pds: hosts, - issuer: "https://entryway.example.test", - clientUrl: "https://client.example.test", - serviceDid: "did:web:entryway.example.test", - betterAuthSecret: "unit-test-secret", - jwtJwk: generateKeyPairSync("ec", { - namedCurve: "secp256k1", - }).privateKey.export({ format: "jwk" }), - }; - const store = createOperationOwnershipStore(db); - const ownership = createOperationOwnership({ - store: { - ...store, - async checkpoint(...args) { - if ( - fault === "after-commit-complete-fails" && - args[1].phase === "complete" && - !completionFailed - ) { - completionFailed = true; - throw new Error("completion interrupted"); - } - if (fault === "before-checkpoint") throw new Error("checkpoint fault"); - await store.checkpoint(...args); - if (fault === "after-checkpoint") throw new Error("checkpoint fault"); - }, - release: fault === "after-commit-crash" ? async () => {} : store.release, - }, - heartbeatMs: 0, - }); - let completionFailed = false; - let publicationMode = "normal"; - let directoryReads = 0; - let credentialsIssued = 0; - const publicationAttempts = []; - const accounts = { - ownership, - storage, - get: (value) => storage.get(value), - plcSigner: await Secp256k1MigrationPlcSigner.fromHex( - Buffer.from(await hot.export()).toString("hex"), - ), - plcClient: { - url: "https://plc.example.test", - getAuditableLog: async () => { - if ( - backendState.mode === "directory-outage" && - backendState.creates > 0 - ) - throw new Error("directory unavailable"); - return structuredClone(audit); - }, - getDocument: async () => { - directoryReads++; - return plc.formatDidDoc({ - did, - ...plc.normalizeOp(audit.at(-1).operation), - }); - }, - sendOperation: async (subject, operation) => { - assert.equal(subject, did); - const admissions = await query(db, "SELECT * FROM arrival_replay"); - const signed = await query( - db, - "SELECT * FROM arrival_signed_operations", - ); - assert.equal( - admissions.filter((item) => item.method === incomingHandoffMethod) - .length, - 1, - ); - assert.equal(signed.length, 1); - assert.deepEqual(JSON.parse(signed[0].operation), operation); - publicationAttempts.push(structuredClone(operation)); - if (publicationMode === "lost-unapplied") - throw new Error("response lost"); - audit.push({ - did, - cid: String(await cidForCbor(operation)), - operation: structuredClone(operation), - nullified: false, - createdAt: new Date().toISOString(), - }); - if (publicationMode === "lost-applied") - throw new Error("response lost"); - }, - getLastOp: async () => - mutation === "race" - ? { ...predecessor, sig: "changed" } - : audit.at(-1).operation, - }, - }; - const browserFlow = createBrowserFlow({ - db, - config, - provider: { - deviceManager: { load: async () => ({ deviceId: "browser" }) }, - }, - }); - const request = { headers: { origin: config.issuer }, body: {} }; - request.body.csrf = (await browserFlow.loadBrowser(request)).csrf; - let reservations = 0; - const backendState = { - exists: false, - deactivated: false, - creates: 0, - pauses: 0, - mode: "normal", - exactMove: null, - adminExtras: {}, - }; - - const originalFetch = globalThis.fetch; - t.after(() => { - globalThis.fetch = originalFetch; - }); - globalThis.fetch = async (url, options) => { - const parsedUrl = new URL(url); - if (parsedUrl.pathname.endsWith("getAccountInfo")) { - assert.match(options.headers.authorization, /^Basic /); - if (backendState.mode === "network") - throw new Error("network unavailable"); - if (backendState.mode === "malformed") return Response.json({ did }); - if (!backendState.exists) - return Response.json({ error: "NotFound" }, { status: 404 }); - return Response.json({ - did: backendState.mode === "wrong-did" ? "did:plc:wrong" : did, - handle, - indexedAt: new Date().toISOString(), - ...backendState.adminExtras, - ...(backendState.deactivated - ? { deactivatedAt: new Date().toISOString() } - : {}), - }); - } - if (parsedUrl.pathname.endsWith("createAccount")) { - backendState.creates++; - const body = JSON.parse(options.body); - const recorded = ( - await query( - db, - "SELECT operation FROM arrival_signed_operations WHERE kind = 'destination-move'", - ) - )[0]; - assert.deepEqual(body.plcOp, JSON.parse(recorded.operation)); - assert.equal((await arrivals.readArrivalAccess(did)).bound, false); - assert.equal(body.handle, handle); - assert.equal(body.did, did); - assert.equal(body.plcOp.verificationMethods.atproto, repository.did()); - assert.equal(body.plcOp.services.atproto_pds.endpoint, endpoint); - assert.equal(typeof body.plcOp.sig, "string"); - assert.ok(body.plcOp.sig.length > 0); - backendState.exactMove = body.plcOp; - if (backendState.mode === "creation-rejected") - return Response.json({ error: "InvalidRequest" }, { status: 400 }); - if (backendState.mode !== "unchanged-head") - audit.push({ - did, - operation: body.plcOp, - cid: String(await cidForCbor(body.plcOp)), - nullified: false, - createdAt: new Date().toISOString(), - }); - if (backendState.mode === "malformed-head") audit.at(-1).cid = "invalid"; - if (backendState.mode !== "published-absent") backendState.exists = true; - if (["creation-lost", "published-absent"].includes(backendState.mode)) - throw new Error("creation response lost"); - return Response.json({ - did, - handle, - accessJwt: "discarded-access", - refreshJwt: "discarded-refresh", - }); - } - if (parsedUrl.pathname.endsWith("updateSubjectStatus")) { - backendState.pauses++; - assert.deepEqual(JSON.parse(options.body), { - subject: { $type: "com.atproto.admin.defs#repoRef", did }, - deactivated: { applied: true }, - }); - assert.equal((await arrivals.readArrivalAccess(did)).bound, false); - if (backendState.mode === "pause-rejected") - return Response.json({ error: "InvalidRequest" }, { status: 400 }); - backendState.deactivated = true; - if (backendState.mode === "pause-lost") - throw new Error("pause response lost"); - return Response.json({}); - } - reservations++; - assert.equal( - String(url), - `${endpoint}/xrpc/com.atproto.server.reserveSigningKey`, - ); - assert.deepEqual(JSON.parse(options.body), { did }); - assert.equal(options.headers.authorization, undefined); - const rows = await query(db, "SELECT * FROM arrival_reservations"); - assert.equal(rows.length, 1); - assert.equal(rows[0].signing_key, null); - if (mutation === "lost") throw new Error("reservation response lost"); - if (mutation === "http") return new Response("{}", { status: 503 }); - return Response.json({ signingKey: repository.did() }); - }; - const composed = await composeIncomingArrival({ - db, - arrivals, - config, - accounts, - authentication, - browserFlow, - }); - return { - get db() { - return db; - }, - arrivals, - backendState, - async reopen() { - await db.close(); - db = await openTestDatabase(path); - return arrivalStorage(); - }, - request, - config, - principal, - ownership, - store, - audit, - publicationAttempts, - setPublicationMode: (value) => { - publicationMode = value; - }, - directoryReads: () => directoryReads, - credentialsIssued: () => credentialsIssued, - async credential(method = incomingHandoffMethod, overrides = {}) { - credentialsIssued++; - if (overrides.jti !== undefined) { - const now = Math.floor(Date.now() / 1000); - const header = Buffer.from( - JSON.stringify({ typ: "JWT", alg: "ES256K" }), - ).toString("base64url"); - const payload = Buffer.from( - JSON.stringify({ - iss: did, - aud: config.serviceDid, - lxm: method, - iat: now, - exp: now + 120, - ...overrides, - }), - ).toString("base64url"); - const bytes = `${header}.${payload}`; - return `Bearer ${bytes}.${Buffer.from(await source.sign(Buffer.from(bytes))).toString("base64url")}`; - } - return `Bearer ${await createServiceJwt({ iss: did, aud: config.serviceDid, lxm: method, keypair: source, ...overrides })}`; - }, - did, - predecessor, - head, - source, - hot, - repository, - composed, - reservations: () => reservations, - verifications: () => verifications, - prepare: (otp = "fresh-otp") => - composed.prepareArrival(request, otp, { did, handle }), - }; -} - +import { + fixture, + admitProvisioning, + endpoint, + sourceEndpoint, + email, + handle, +} from "../support/helpers/incoming-arrival-fixture.mjs"; for (const mode of ["modern", "legacy"]) { test(`composed ${mode} preparation retains signed predecessor and reserves only after durable intent`, async (t) => { const f = await fixture(t, mode); @@ -486,6 +72,13 @@ for (const mode of ["modern", "legacy"]) { "continueHandoff", "continueCreation", "reconcileArrival", + "issueArrivalSession", + "issueCreationSession", + "refreshArrivalSession", + "recoverArrivalSession", + "authorizeArrivalAccess", + "activateArrivalAsUser", + "activateArrivalWithCredential", ].sort(), ); assert.equal( @@ -1047,43 +640,6 @@ test("verified credential jti cannot admit another incoming method", async (t) = assert.equal((await query(f.db, "SELECT * FROM arrival_replay")).length, 1); }); -async function admitProvisioning(f, interruptHandoff = false) { - const prepared = await f.prepare(); - const operation = await plc.signOperation(prepared.handoff, f.source); - const dispatch = f.ownership.dispatch; - if (interruptHandoff) - f.ownership.dispatch = async () => { - throw new Error("interrupted before handoff dispatch"); - }; - const handoff = f.composed.admitIncoming(f.request, { - operationId: prepared.operationId, - method: incomingHandoffMethod, - body: { operation }, - presentation: await f.credential(), - arrivalCode: prepared.arrivalCode, - }); - if (interruptHandoff) - await assert.rejects(handoff, /interrupted before handoff dispatch/); - else await handoff; - f.ownership.dispatch = dispatch; - const { createInvites } = - await import("../../dist/src/features/account-registration/invites.mjs"); - const invites = await createInvites({ - db: f.db, - config: f.config, - accounts: { get: async () => null }, - }); - const { code } = await invites.createInviteCode({ useCount: 1 }); - await f.composed.admitIncoming(f.request, { - operationId: prepared.operationId, - method: incomingCreationMethod, - body: { handle, inviteCode: code }, - presentation: await f.credential(incomingCreationMethod), - arrivalCode: prepared.arrivalCode, - }); - return prepared; -} - test("reconciliation publishes the accepted unpublished handoff before admitted creation", async (t) => { const f = await fixture(t); const prepared = await admitProvisioning(f, true); diff --git a/tests/contracts/incoming-arrival-storage.test.mjs b/tests/contracts/incoming-arrival-storage.test.mjs index ae4de2a4..3880af87 100644 --- a/tests/contracts/incoming-arrival-storage.test.mjs +++ b/tests/contracts/incoming-arrival-storage.test.mjs @@ -102,6 +102,7 @@ async function fixture() { { did: value, user_id: userId }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => accounts.activatePlacedAccount(subject), insertPlacedAccount: (input) => accounts.insertAccount( { @@ -1183,7 +1184,7 @@ test("activation completion is separate and requires exact version and observed }); assert.deepEqual(await claimSnapshot(db), completedSnapshot); } - assert.equal((await accounts.getByDid(did))?.status, "provisioning"); + assert.equal((await accounts.getByDid(did))?.status, "active"); await assert.rejects(complete({ expectedVersion: bound.version + 1 }), { code: "OperationConflict", }); @@ -1192,6 +1193,98 @@ test("activation completion is separate and requires exact version and observed } }); +const completion = (arrivals, claim, expectedVersion) => + arrivals.completeArrivalActivation({ + owner: claim, + operationId: "op-1", + expectedVersion, + did, + userId: "user-a", + activation: { + backendActiveObserved: true, + method: "com.atproto.admin.updateSubjectStatus", + observedAt: Date.now(), + }, + }); +const accountState = async (db) => + (await query(db, "SELECT status FROM accounts"))[0].status; + +test("completion activates the placed account in the same transaction", async () => { + const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); + try { + const bound = await bind(await allocate((await prepare()).version)); + assert.equal(await accountState(db), "provisioning"); + assert.equal( + (await completion(arrivals, claim, bound.version)).kind, + "applied", + ); + assert.equal(await accountState(db), "active"); + assert.equal((await arrivals.readArrivalAccess(did)).complete, true); + } finally { + await db.close(); + } +}); + +test("a failure after the account flip rolls back the flip and the completion", async () => { + const { db, accounts, arrivals, claim, prepare, allocate, bind } = + await fixture(); + try { + const bound = await bind(await allocate((await prepare()).version)); + const original = accounts.activatePlacedAccount; + accounts.activatePlacedAccount = async (subject) => { + await original(subject); + assert.equal((await accounts.getByDid(subject)).status, "active"); + throw new Error("after account flip"); + }; + await assert.rejects( + completion(arrivals, claim, bound.version), + /after account flip/, + ); + accounts.activatePlacedAccount = original; + assert.equal(await accountState(db), "provisioning"); + const access = await arrivals.readArrivalAccess(did); + assert.equal(access.complete, false); + assert.equal(access.version, bound.version); + assert.equal( + (await completion(arrivals, claim, bound.version)).kind, + "applied", + ); + assert.equal(await accountState(db), "active"); + } finally { + await db.close(); + } +}); + +for (const [name, statement] of [ + [ + "not provisioning", + "UPDATE accounts SET status = 'deactivated', data = replace(data, '\"provisioning\"', '\"deactivated\"')", + ], + [ + "a different handle", + "UPDATE accounts SET handle = 'other.entryway.test', data = replace(data, 'dest.entryway.test', 'other.entryway.test')", + ], + [ + "a different email", + "UPDATE accounts SET email = 'other@example.test', data = replace(data, 'dest@example.test', 'other@example.test')", + ], +]) + test(`completion refuses an account that is ${name}`, async () => { + const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); + try { + const bound = await bind(await allocate((await prepare()).version)); + await query(db, statement, [], "run"); + const before = await query(db, "SELECT status FROM accounts"); + await assert.rejects(completion(arrivals, claim, bound.version), { + code: "OperationConflict", + }); + assert.deepEqual(await query(db, "SELECT status FROM accounts"), before); + assert.equal((await arrivals.readArrivalAccess(did)).complete, false); + } finally { + await db.close(); + } + }); + test("activation completion is rejected when the operation owner changed", async () => { const { db, arrivals, claim, prepare, allocate, bind } = await fixture(); try { @@ -1504,6 +1597,8 @@ test( { did: value, user_id: userId }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => + accounts.activatePlacedAccount(subject), insertPlacedAccount: (input) => accounts.insertAccount( { @@ -1626,6 +1721,8 @@ test( { did: value, user_id: userId }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => + accounts.activatePlacedAccount(subject), insertPlacedAccount: (input) => accounts.insertAccount( { @@ -3257,6 +3354,63 @@ test("generic arrival attempts settle only exact acknowledged receipts without a } }); +test("settlement accepts only a null result or an approved safe-retry disposition", async () => { + const f = await fixture(); + const store = createOperationOwnershipStore(f.db); + try { + let version = await f.allocate((await f.prepare()).version); + const receipt = await store.beginExternal(f.claim, { + step: "incoming-activation", + target: endpoint, + method: "com.atproto.admin.updateSubjectStatus", + intentDigest: hash("f"), + }); + const input = { + operationId: "op-1", + did, + externalAttemptId: receipt.id, + step: "incoming-activation", + }; + version = ( + await f.arrivals.associateArrivalAttempt(f.claim, version, input) + ).version; + await store.acknowledgeExternal(f.claim, receipt, null); + for (const result of [ + '{"recovery":"applied"}', + '{"recovery":"unapplied","extra":1}', + '{"recovery":"unapplied"} ', + '{"recovery":null}', + '"null"', + "true", + "{}", + ]) { + await query( + f.db, + "UPDATE external_operation_attempts SET result = ? WHERE id = ?", + [result, receipt.id], + "run", + ); + await assert.rejects( + f.arrivals.settleArrivalAttempt(f.claim, version, input), + { code: "OperationRecoveryRequired" }, + result, + ); + } + await query( + f.db, + "UPDATE external_operation_attempts SET result = ? WHERE id = ?", + ['{"recovery":"replay-safe"}', receipt.id], + "run", + ); + assert.equal( + (await f.arrivals.settleArrivalAttempt(f.claim, version, input)).kind, + "applied", + ); + } finally { + await f.db.close(); + } +}); + test("completed generic receipt association never clears allocation uncertainty", async () => { const f = await fixture(); const store = createOperationOwnershipStore(f.db); diff --git a/tests/contracts/incoming-credentials.test.mjs b/tests/contracts/incoming-credentials.test.mjs new file mode 100644 index 00000000..98e1ff86 --- /dev/null +++ b/tests/contracts/incoming-credentials.test.mjs @@ -0,0 +1,756 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { decodeJwt, decodeProtectedHeader, importJWK, SignJWT } from "jose"; +import { + fixture, + admitProvisioning, +} from "../support/helpers/incoming-arrival-fixture.mjs"; +import { hashPassword } from "../../dist/src/authentication/password-crypto.mjs"; +import { createAccountPrimitives } from "../../dist/src/accounts/primitives.mjs"; +import { + verifiedUser, + failureTrigger, + removeFailureTrigger, + hasFailure, + query, +} from "../support/database-fixture.mjs"; + +const codeOf = (error) => error.code ?? error.error; +const hasCode = (code) => (error) => codeOf(error) === code; +const pdsDid = "did:web:destination.example.test"; + +async function bound(t) { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + f.arrivalCode = prepared.arrivalCode; + const result = await f.composed.continueCreation( + f.request, + prepared.operationId, + ); + assert.equal(result.state, "pending"); + return { f, op: prepared.operationId }; +} +const version = async (f, op) => + (await f.arrivals.readArrivalAggregate(op, f.principal.userId)).arrival + .version; +const issue = async (f, op, expected) => + f.composed.issueArrivalSession( + f.request, + op, + expected ?? (await version(f, op)), + ); +const recover = async (f, op, expected, otp = "fresh-otp") => + f.composed.recoverArrivalSession(f.request, otp, { + operationId: op, + expectedVersion: expected ?? (await version(f, op)), + }); +const families = (f) => + query(f.db, "SELECT family_id, revoked_at FROM arrival_families"); +const sessions = (f) => + query( + f.db, + "SELECT value FROM key_value_state WHERE namespace = 'legacy:sessions'", + ); +const refreshRows = (f) => + query( + f.db, + "SELECT key FROM key_value_state WHERE namespace = 'legacy:refresh'", + ); +const sign = async (f, claims, typ = "at+jwt") => + new SignJWT(claims.payload) + .setProtectedHeader({ typ, alg: "ES256K" }) + .setIssuer(f.config.issuer) + .setSubject(claims.sub) + .setAudience(claims.aud) + .setIssuedAt() + .setExpirationTime("5m") + .setJti(claims.jti ?? "j".repeat(43)) + .sign(await importJWK(f.config.jwtJwk, "ES256K")); +const remoteEffects = (f) => ({ + creates: f.backendState.creates, + pauses: f.backendState.pauses, + activations: f.backendState.activations, + reservations: f.reservations(), + publications: f.publicationAttempts.length, + credentials: f.credentialsIssued(), +}); + +test("issuance returns exact tracked claims only after the committed association", async (t) => { + const { f, op } = await bound(t); + const before = await version(f, op); + const session = await issue(f, op); + const access = decodeJwt(session.accessJwt); + const refresh = decodeJwt(session.refreshJwt); + assert.equal(decodeProtectedHeader(session.accessJwt).typ, "at+jwt"); + assert.equal(decodeProtectedHeader(session.refreshJwt).typ, "refresh+jwt"); + assert.equal(access.sub, f.did); + assert.equal(access.aud, pdsDid); + assert.equal(access.scope, "com.atproto.access"); + assert.equal(access.iss, f.config.issuer); + assert.equal(refresh.sub, f.did); + assert.equal(refresh.aud, f.config.serviceDid); + assert.equal(refresh.scope, "com.atproto.refresh"); + assert.equal(access.sid, refresh.sid); + assert.equal(session.did, f.did); + assert.equal(session.active, false); + assert.equal(session.status, "deactivated"); + assert.equal(session.emailConfirmed, true); + const rows = await families(f); + assert.deepEqual( + rows.map((row) => row.family_id), + [access.sid], + ); + assert.equal(rows[0].revoked_at, null); + assert.equal(await version(f, op), before + 1); + assert.equal((await sessions(f)).length, 1); +}); + +test("no credentials before provisioning, deactivation and binding", async (t) => { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + const op = prepared.operationId; + await assert.rejects(issue(f, op), hasCode("OperationConflict")); + await assert.rejects(recover(f, op), hasCode("OperationConflict")); + assert.equal((await families(f)).length, 0); + assert.equal((await sessions(f)).length, 0); +}); + +test("wrong owner, unknown operation, stale version, repeated issuance and wrong host are refused", async (t) => { + const { f, op } = await bound(t); + const current = await version(f, op); + const unknown = await issue(f, "no-such-operation", 1).catch((e) => e); + f.principal.userId = "someone-else"; + const wrongOwner = await issue(f, op, current).catch((e) => e); + f.principal.userId = "destination-user"; + assert.equal(codeOf(unknown), "AccountNotFound"); + assert.equal(codeOf(wrongOwner), "AccountNotFound"); + assert.equal(wrongOwner.message, unknown.message); + assert.equal(wrongOwner.status, unknown.status); + await assert.rejects(issue(f, op, current + 1), hasCode("OperationConflict")); + assert.equal((await families(f)).length, 0); + // A configured host that no longer matches the saved placement is refused. + f.config.pds[0].url = "https://elsewhere.example.test"; + await assert.rejects(issue(f, op, current), hasCode("OperationConflict")); + f.config.pds[0].url = "https://destination.example.test"; + assert.equal((await families(f)).length, 0); + await issue(f, op, current); + await assert.rejects(issue(f, op), hasCode("OperationConflict")); + assert.equal((await families(f)).length, 1); +}); + +test("ordinary login, access and refresh never accept a pending arrival credential", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + await assert.rejects( + f.legacy.verifyAccess(session.accessJwt), + hasCode("AccountUnavailable"), + ); + await assert.rejects( + f.legacy.refreshSession(session.refreshJwt), + hasCode("AccountUnavailable"), + ); + await assert.rejects( + f.legacy.createAccountSession(f.did), + hasCode("AccountUnavailable"), + ); + // A real main password must still not open a pending account. + await f.db.set("legacy:passwords", f.did, { + hash: await hashPassword("correct-horse-battery"), + revision: "r1", + updatedAt: new Date(), + }); + await assert.rejects( + f.legacy.createSession({ + identifier: f.did, + password: "correct-horse-battery", + }), + hasCode("AccountUnavailable"), + ); + await assert.rejects( + f.legacy.createSession({ identifier: f.did, password: "wrong-password!!" }), + hasCode("AuthenticationRequired"), + ); + // The ordinary refusals did not consume or revoke the tracked family. + assert.equal((await families(f))[0].revoked_at, null); + const refreshed = await f.composed.refreshArrivalSession(session.refreshJwt); + assert.ok(refreshed.accessJwt); +}); + +test("refresh rotates, replay revokes the family and non-refresh tokens are rejected", async (t) => { + const { f, op } = await bound(t); + const first = await issue(f, op); + await assert.rejects( + f.composed.refreshArrivalSession(first.accessJwt), + hasCode("InvalidToken"), + ); + const second = await f.composed.refreshArrivalSession(first.refreshJwt); + assert.notEqual(second.refreshJwt, first.refreshJwt); + assert.equal(decodeJwt(second.accessJwt).sid, decodeJwt(first.accessJwt).sid); + assert.equal(second.status, "deactivated"); + await assert.rejects( + f.composed.refreshArrivalSession(first.refreshJwt), + hasCode("ExpiredToken"), + ); + // Replay revoked the whole family, including the rotated credential. + await assert.rejects( + f.composed.refreshArrivalSession(second.refreshJwt), + hasCode("ExpiredToken"), + ); + assert.ok(JSON.parse((await sessions(f))[0].value).revokedAt); +}); + +test("a refresh credential for an untracked family is not an arrival credential", async (t) => { + const { f, op } = await bound(t); + await issue(f, op); + const forged = await sign( + f, + { + payload: { scope: "com.atproto.refresh", sid: "s".repeat(43) }, + sub: f.did, + aud: f.config.serviceDid, + }, + "refresh+jwt", + ); + await assert.rejects( + f.composed.refreshArrivalSession(forged), + hasCode("InvalidToken"), + ); +}); + +test("concurrent refreshes of one credential succeed at most once", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + const results = await Promise.allSettled([ + f.composed.refreshArrivalSession(session.refreshJwt), + f.composed.refreshArrivalSession(session.refreshJwt), + ]); + assert.equal(results.filter((r) => r.status === "fulfilled").length, 1); + const failure = results.find((r) => r.status === "rejected"); + assert.equal(codeOf(failure.reason), "ExpiredToken"); +}); + +test("concurrent refresh and recovery leave exactly one usable family", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + const expected = await version(f, op); + const [refreshed, recovered] = await Promise.allSettled([ + f.composed.refreshArrivalSession(session.refreshJwt), + recover(f, op, expected), + ]); + assert.equal(recovered.status, "fulfilled"); + if (refreshed.status === "fulfilled") + await assert.rejects( + f.composed.refreshArrivalSession(refreshed.value.refreshJwt), + hasCode("ExpiredToken"), + ); + else assert.equal(codeOf(refreshed.reason), "ExpiredToken"); + assert.equal( + (await families(f)).filter((r) => r.revoked_at === null).length, + 1, + ); + const usable = await f.composed.refreshArrivalSession( + recovered.value.refreshJwt, + ); + assert.ok(usable.accessJwt); +}); + +test("recovery replaces every prior refresh family in the same commit (M3) without remote effects", async (t) => { + const { f, op } = await bound(t); + const first = await issue(f, op); + const effects = remoteEffects(f); + // The source key/JWT is irrelevant after cutover, and the arrival code has expired. + await query( + f.db, + "UPDATE arrival_code SET issued_at = 1, expires_at = 2", + [], + "run", + ); + const second = await recover(f, op); + assert.deepEqual(remoteEffects(f), effects); + await assert.rejects( + f.composed.refreshArrivalSession(first.refreshJwt), + hasCode("ExpiredToken"), + ); + await assert.rejects( + f.composed.authorizeArrivalAccess(first.accessJwt), + hasCode("ExpiredToken"), + ); + const rows = await families(f); + assert.equal(rows.length, 2); + assert.deepEqual( + rows.filter((r) => r.revoked_at === null).map((r) => r.family_id), + [decodeJwt(second.accessJwt).sid], + ); + // The legacy family itself is revoked, not only the arrival metadata, so it + // cannot be refreshed through ordinary routes after completion either. + const legacyRows = (await sessions(f)).map((row) => JSON.parse(row.value)); + assert.deepEqual( + legacyRows.filter((row) => row.revokedAt).map((row) => row.id), + [decodeJwt(first.accessJwt).sid], + ); + assert.equal( + legacyRows.find((row) => row.revokedAt).revocationReason, + "arrival-recovered", + ); + // A lost response is recovered again: still one active replacement family. + const third = await recover(f, op); + await assert.rejects( + f.composed.refreshArrivalSession(second.refreshJwt), + hasCode("ExpiredToken"), + ); + assert.equal( + (await families(f)).filter((r) => r.revoked_at === null).length, + 1, + ); + assert.ok( + (await f.composed.refreshArrivalSession(third.refreshJwt)).accessJwt, + ); + assert.deepEqual(remoteEffects(f), effects); +}); + +test("recovery needs the saved user, fresh proof and exact version; wrong owner equals unknown", async (t) => { + const { f, op } = await bound(t); + await issue(f, op); + const current = await version(f, op); + await assert.rejects( + recover(f, op, current, "stale-otp"), + hasCode("ArrivalProofRequired"), + ); + await assert.rejects( + recover(f, op, current - 1), + hasCode("OperationConflict"), + ); + await assert.rejects( + f.composed.recoverArrivalSession(f.request, "fresh-otp", { + operationId: op, + expectedVersion: "1", + }), + hasCode("InvalidRequest"), + ); + const unknown = await recover(f, "no-such-operation", 1).catch((e) => e); + f.principal.userId = "someone-else"; + const wrongOwner = await recover(f, op, current).catch((e) => e); + f.principal.userId = "destination-user"; + assert.equal(codeOf(unknown), "AccountNotFound"); + assert.equal(codeOf(wrongOwner), "AccountNotFound"); + assert.equal(wrongOwner.message, unknown.message); + assert.equal((await families(f)).length, 1); + assert.equal((await families(f))[0].revoked_at, null); +}); + +test("a failed association leaves no usable or untracked family and revokes nothing", async (t) => { + const { f, op } = await bound(t); + await failureTrigger( + f.db, + "reject_family", + "arrival_families", + "family rollback", + ); + const before = await version(f, op); + await assert.rejects(issue(f, op), hasFailure("family rollback")); + assert.equal((await sessions(f)).length, 0); + assert.equal((await refreshRows(f)).length, 0); + assert.equal(await version(f, op), before); + await removeFailureTrigger(f.db, "reject_family", "arrival_families"); + const session = await issue(f, op); + await failureTrigger( + f.db, + "reject_family", + "arrival_families", + "family rollback", + ); + await assert.rejects(recover(f, op), hasFailure("family rollback")); + // The previous family survives untouched and the failed replacement left no rows. + assert.equal((await sessions(f)).length, 1); + assert.equal( + (await families(f)).filter((r) => r.revoked_at === null).length, + 1, + ); + await removeFailureTrigger(f.db, "reject_family", "arrival_families"); + assert.ok( + (await f.composed.refreshArrivalSession(session.refreshJwt)).accessJwt, + ); +}); + +test("refresh and access credentials expire", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + t.mock.timers.enable({ apis: ["Date"], now: Date.now() }); + t.mock.timers.tick(6 * 60 * 1000); + await assert.rejects( + f.composed.authorizeArrivalAccess(session.accessJwt), + hasCode("ExpiredToken"), + ); + t.mock.timers.tick(91 * 24 * 60 * 60 * 1000); + await assert.rejects( + f.composed.refreshArrivalSession(session.refreshJwt), + hasCode("ExpiredToken"), + ); +}); + +test("access authorization requires exact subject, audience, type, scope and a tracked family", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + const sid = decodeJwt(session.accessJwt).sid; + const good = { + payload: { scope: "com.atproto.access", sid }, + sub: f.did, + aud: pdsDid, + }; + const authorized = await f.composed.authorizeArrivalAccess(session.accessJwt); + assert.equal(authorized.did, f.did); + assert.equal(authorized.operationId, op); + assert.equal(authorized.userId, "destination-user"); + for (const [name, claims, typ, code] of [ + [ + "wrong subject", + { ...good, sub: "did:plc:" + "b".repeat(24) }, + "at+jwt", + "InvalidToken", + ], + [ + "wrong audience", + { ...good, aud: "did:web:other.example.test" }, + "at+jwt", + "InvalidToken", + ], + [ + "app-password scope", + { ...good, payload: { scope: "com.atproto.appPass", sid } }, + "at+jwt", + "InvalidToken", + ], + ["refresh type", good, "refresh+jwt", "InvalidToken"], + [ + "untracked family", + { + ...good, + payload: { scope: "com.atproto.access", sid: "u".repeat(43) }, + }, + "at+jwt", + "ExpiredToken", + ], + ]) + await assert.rejects( + f.composed.authorizeArrivalAccess(await sign(f, claims, typ)), + hasCode(code), + name, + ); + await assert.rejects( + f.composed.authorizeArrivalAccess(session.refreshJwt), + hasCode("InvalidToken"), + ); +}); + +const tamper = { + "saved binding": [ + "AccountMismatch", + async (f) => { + await verifiedUser(f.db, "other-user", "other@example.test"); + await query( + f.db, + "UPDATE account_bindings SET user_id = 'other-user'", + [], + "run", + ); + }, + ], + "account status": [ + "OperationConflict", + async (f) => { + await query( + f.db, + "UPDATE accounts SET status = 'deactivated', data = replace(data, '\"provisioning\"', '\"deactivated\"')", + [], + "run", + ); + }, + ], + "unresolved attempt": [ + "OperationRecoveryRequired", + async (f) => { + await query( + f.db, + "INSERT INTO arrival_attempts (attempt_binding, ownership_operation_id, attempt_id, operation_id, reason, recorded_at, fence) SELECT 'b', operation_id, 'a', operation_id, 'external:incoming-pause', 1, 1 FROM arrivals", + [], + "run", + ); + }, + ], +}; +for (const [name, [code, mutate]] of Object.entries(tamper)) + for (const action of ["issue", "recover"]) + test(`${action} refuses a changed ${name} and mints nothing`, async (t) => { + const { f, op } = await bound(t); + if (action === "recover") await issue(f, op); + const rows = (await families(f)).length; + await mutate(f); + await assert.rejects( + action === "issue" ? issue(f, op) : recover(f, op), + hasCode(code), + ); + assert.equal((await families(f)).length, rows); + assert.equal((await sessions(f)).length, rows); + }); + +test("refresh is refused when the saved account facts changed, and never refreshes then", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + await tamper["account status"][1](f); + await assert.rejects( + f.composed.refreshArrivalSession(session.refreshJwt), + hasCode("OperationConflict"), + ); +}); + +test("an unresolved attempt alone does not stop a refresh", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + await tamper["unresolved attempt"][1](f); + assert.ok( + (await f.composed.refreshArrivalSession(session.refreshJwt)).accessJwt, + ); +}); + +for (const [name, mutate, code] of [ + [ + "cancelled arrival", + (f) => + query( + f.db, + "UPDATE arrivals SET cancelled_at = 1, did_root = NULL, active = 0", + [], + "run", + ), + "ArrivalExpired", + ], + [ + "changed account", + (f) => tamper["account status"][1](f), + "OperationConflict", + ], +]) + test(`refresh rechecks pending state and saved facts under the fence: ${name}`, async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + const resume = f.ownership.resumePending.bind(f.ownership); + f.ownership.resumePending = async (...args) => { + f.ownership.resumePending = resume; + await mutate(f); + return resume(...args); + }; + await assert.rejects( + f.composed.refreshArrivalSession(session.refreshJwt), + hasCode(code), + ); + assert.ok(op); + }); + +test("concurrent recoveries leave exactly one replacement family", async (t) => { + const { f, op } = await bound(t); + await issue(f, op); + const expected = await version(f, op); + const results = await Promise.allSettled([ + recover(f, op, expected), + recover(f, op, expected), + ]); + assert.equal(results.filter((r) => r.status === "fulfilled").length, 1); + assert.equal( + codeOf(results.find((r) => r.status === "rejected").reason), + "OperationConflict", + ); + assert.equal( + (await families(f)).filter((r) => r.revoked_at === null).length, + 1, + ); + assert.equal((await families(f)).length, 2); +}); + +test("recovery needs no source credential and the source key is no longer current", async (t) => { + const { f, op } = await bound(t); + await issue(f, op); + const issued = f.credentialsIssued(); + const head = f.audit.at(-1).operation; + assert.notEqual(head.verificationMethods.atproto, f.source.did()); + assert.ok((await recover(f, op)).accessJwt); + assert.equal(f.credentialsIssued(), issued); +}); + +test("ordinary account changes remain refused for a pending arrival", async (t) => { + const { f, op } = await bound(t); + const primitives = createAccountPrimitives({ + db: f.db, + config: f.config, + storage: f.storage, + ownership: f.ownership, + }); + await assert.rejects( + primitives.assertNoMigration(f.did), + hasCode("MigrationPending"), + ); + const row = await f.storage.getByDid(f.did); + await assert.rejects( + f.storage.saveAccount({ ...row, status: "active" }), + hasCode("IdentityConflict"), + ); + assert.ok(op); +}); + +const retrack = async (f, sid, patch) => { + const row = await f.db.get("legacy:sessions", sid); + await f.db.set("legacy:sessions", sid, { ...row, ...patch }); +}; +test("access authorization pins scope, audience and host independently of the token", async (t) => { + const { f, op } = await bound(t); + const session = await issue(f, op); + const sid = decodeJwt(session.accessJwt).sid; + const other = "did:web:other.example.test"; + const claims = (aud, scope) => ({ + payload: { scope, sid }, + sub: f.did, + aud, + }); + // Family stored on another host: the token matches it, the arrival's placement does not. + await retrack(f, sid, { pdsDid: other }); + await assert.rejects( + f.composed.authorizeArrivalAccess( + await sign(f, claims(other, "com.atproto.access")), + ), + hasCode("InvalidToken"), + ); + await retrack(f, sid, { pdsDid: pdsDid }); + // A token for another configured PDS cannot use this family. + await assert.rejects( + f.composed.authorizeArrivalAccess( + await sign(f, claims(other, "com.atproto.access")), + ), + hasCode("InvalidToken"), + ); + // An app-password family is never an arrival credential, even if its token matches. + await retrack(f, sid, { scope: "com.atproto.appPass" }); + await assert.rejects( + f.composed.authorizeArrivalAccess( + await sign(f, claims(pdsDid, "com.atproto.appPass")), + ), + hasCode("InvalidToken"), + ); + await retrack(f, sid, { scope: "com.atproto.access", appPasswordId: "x" }); + await assert.rejects( + f.composed.authorizeArrivalAccess( + await sign(f, claims(pdsDid, "com.atproto.access")), + ), + hasCode("InvalidToken"), + ); + await retrack(f, sid, { appPasswordId: undefined }); + assert.ok((await f.composed.authorizeArrivalAccess(session.accessJwt)).did); + // Tracking metadata for another host is refused as well. + await query(f.db, "UPDATE arrival_families SET pds_id = 'pds2'", [], "run"); + await assert.rejects( + f.composed.authorizeArrivalAccess(session.accessJwt), + hasCode("InvalidToken"), + ); +}); + +test("cookie-less creation issuance is the continuation of an accepted, bound creation", async (t) => { + const f = await fixture(t); + const prepared = await admitProvisioning(f); + const op = prepared.operationId; + const input = { + did: f.did, + operationId: op, + arrivalCode: prepared.arrivalCode, + }; + // Not bound yet. + await assert.rejects( + f.composed.issueCreationSession(input), + hasCode("OperationConflict"), + ); + await f.composed.continueCreation(f.request, op); + // No browser request is involved; the code and operation select the saved user. + for (const bad of [ + { ...input, arrivalCode: "wrong-code" }, + { ...input, did: "did:plc:" + "b".repeat(24) }, + { ...input, operationId: "other-operation" }, + ]) + await assert.rejects( + f.composed.issueCreationSession(bad), + hasCode("ArrivalExpired"), + ); + assert.equal((await families(f)).length, 0); + const session = await f.composed.issueCreationSession(input); + assert.equal(decodeJwt(session.accessJwt).sub, f.did); + assert.equal((await families(f)).length, 1); + await assert.rejects( + f.composed.issueCreationSession(input), + hasCode("OperationConflict"), + ); + assert.equal((await families(f)).length, 1); +}); + +test("creation issuance needs an accepted creation admission for the saved user", async (t) => { + const { f, op } = await bound(t); + await query( + f.db, + "DELETE FROM arrival_replay WHERE method = 'com.atproto.server.createAccount'", + [], + "run", + ); + await assert.rejects( + f.composed.issueCreationSession({ + did: f.did, + operationId: op, + arrivalCode: f.arrivalCode, + }), + hasCode("AccountMismatch"), + ); + assert.equal((await families(f)).length, 0); +}); + +test("creation issuance rolls back completely on a failed association", async (t) => { + const { f, op } = await bound(t); + await failureTrigger( + f.db, + "reject_family", + "arrival_families", + "family rollback", + ); + await assert.rejects( + f.composed.issueCreationSession({ + did: f.did, + operationId: op, + arrivalCode: f.arrivalCode, + }), + hasFailure("family rollback"), + ); + assert.equal((await sessions(f)).length, 0); + assert.equal((await families(f)).length, 0); +}); + +for (const [name, statement] of [ + [ + "another user", + "UPDATE arrival_replay SET user_id = 'other-user' WHERE method = 'com.atproto.server.createAccount'", + ], + [ + "another DID", + "UPDATE arrival_replay SET did = 'did:plc:bbbbbbbbbbbbbbbbbbbbbbbb' WHERE method = 'com.atproto.server.createAccount'", + ], + [ + "an unrecorded code generation", + "UPDATE arrival_replay SET generation = 99 WHERE method = 'com.atproto.server.createAccount'", + ], +]) + test(`creation issuance refuses an admission recorded for ${name}`, async (t) => { + const { f, op } = await bound(t); + await verifiedUser(f.db, "other-user", "other@example.test"); + await query(f.db, statement, [], "run"); + await assert.rejects( + f.composed.issueCreationSession({ + did: f.did, + operationId: op, + arrivalCode: f.arrivalCode, + }), + hasCode("AccountMismatch"), + ); + assert.equal((await families(f)).length, 0); + }); diff --git a/tests/support/discover-contracts.mjs b/tests/support/discover-contracts.mjs index 4b781b87..6bfea7f3 100644 --- a/tests/support/discover-contracts.mjs +++ b/tests/support/discover-contracts.mjs @@ -7,6 +7,8 @@ const unitContracts = new Set([ "incoming-arrival-admission.test.mjs", "incoming-arrival-composition.test.mjs", "incoming-handoff.test.mjs", + "incoming-credentials.test.mjs", + "incoming-activation.test.mjs", "custody-history.test.mjs", "plc-policy.test.mjs", "plc-signing.test.mjs", diff --git a/tests/support/helpers/incoming-arrival-fixture.mjs b/tests/support/helpers/incoming-arrival-fixture.mjs new file mode 100644 index 00000000..551f7f6b --- /dev/null +++ b/tests/support/helpers/incoming-arrival-fixture.mjs @@ -0,0 +1,504 @@ +import { Secp256k1MigrationPlcSigner } from "../../../dist/src/plc/signing.js"; +import assert from "node:assert/strict"; +import { generateKeyPairSync } from "node:crypto"; +import { createServiceJwt } from "@atproto/xrpc-server"; +import { + incomingHandoffMethod, + incomingCreationMethod, +} from "../../../dist/src/features/external-migration/incoming-authorization.js"; +import { mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { Secp256k1Keypair } from "@atproto/crypto"; +import { cidForCbor } from "@atproto/common"; +import * as plc from "@did-plc/lib"; +import { createLegacy } from "../../../dist/src/oauth/legacy-credentials.mjs"; +import { composeIncomingArrival } from "../../../dist/src/compose-incoming-arrival.mjs"; +import { createBrowserFlow } from "../../../dist/src/http/browser-flow.mjs"; +import { createOperationOwnership } from "../../../dist/src/accounts/operation-ownership.js"; +import { createOperationOwnershipStore } from "../../../dist/src/database/drizzle/operation-ownership.js"; +import { createAccountStorage } from "../../../dist/src/database/drizzle/account-storage.js"; +import { createArrivalStorage } from "../../../dist/src/database/drizzle/migration-arrival.js"; +import { openTestDatabase, verifiedUser, query } from "../database-fixture.mjs"; + +export const endpoint = "https://destination.example.test"; +export const sourceEndpoint = "https://source.example.test"; +export const email = "destination@example.test"; +export const handle = "destination.example.test"; + +export async function fixture(t, mode = "modern", mutation = "", fault = "") { + const directory = mkdtempSync(join(tmpdir(), "arrival-preparation-")); + const path = join(directory, "authority.sqlite"); + let db = await openTestDatabase(path); + t.after(async () => { + await db.close(); + rmSync(directory, { recursive: true, force: true }); + }); + const source = await Secp256k1Keypair.create(); + const recovery = await Secp256k1Keypair.create(); + const hot = await Secp256k1Keypair.create({ exportable: true }); + const repository = await Secp256k1Keypair.create(); + let predecessor; + if (mode === "legacy") { + predecessor = await plc.deprecatedSignCreate( + { + type: "create", + signingKey: source.did(), + recoveryKey: recovery.did(), + handle, + service: sourceEndpoint, + prev: null, + }, + recovery, + ); + } else { + const keys = [recovery.did(), source.did()]; + if (mutation === "full") + for (let index = 0; index < 3; index++) + keys.push((await Secp256k1Keypair.create()).did()); + predecessor = await plc.signOperation( + plc.formatAtprotoOp({ + signingKey: source.did(), + handle: mutation === "distinct-handle" ? "source.example.test" : handle, + pds: sourceEndpoint, + rotationKeys: keys, + prev: null, + }), + recovery, + ); + } + const did = await plc.didForCreateOp(predecessor); + const head = String(await cidForCbor(predecessor)); + const audit = [ + { + did, + cid: head, + operation: predecessor, + nullified: false, + createdAt: new Date().toISOString(), + }, + ]; + if (mutation === "wrong-did") audit[0].did = `did:plc:${"a".repeat(24)}`; + if (mutation === "signature") { + audit[0].operation = { ...predecessor, sig: "invalid" }; + audit[0].cid = String(await cidForCbor(audit[0].operation)); + } + if (mutation === "cid") audit[0].cid = "wrong"; + if (mutation === "nullified") audit[0].nullified = true; + if (mutation === "tombstone") { + const operation = await plc.signOperation( + { type: "plc_tombstone", prev: head }, + source, + ); + audit.push({ + did, + operation, + cid: String(await cidForCbor(operation)), + nullified: false, + createdAt: new Date().toISOString(), + }); + } + const hosts = [ + { id: "pds1", url: endpoint, did: "did:web:destination.example.test" }, + { + id: "pds2", + url: "https://other.example.test", + did: "did:web:other.example.test", + }, + ]; + const storage = createAccountStorage(db, hosts); + const arrivalStorage = () => + createArrivalStorage(db, hosts, { + readAccount: (value) => storage.getByDid(value), + readBinding: (value) => storage.getVerifiedBinding(value), + reserveEmailClaim: (...args) => storage.reserveEmail(...args), + reserveHandleClaim: (...args) => storage.reserveHandle(...args), + recordSavedUserBinding: (subject, userId) => + db.insert( + "account_bindings", + { did: subject, user_id: userId }, + { ignoreConflict: true }, + ), + activatePlacedAccount: (subject) => + storage.activatePlacedAccount(subject), + insertPlacedAccount: (input) => + storage.insertAccount( + { + did: input.did, + email: input.email, + emailVerified: true, + handle: input.handle, + pdsId: input.pdsId, + pdsUrl: input.pdsUrl, + status: "provisioning", + createdAt: new Date().toISOString(), + }, + input.userId, + ), + }); + const arrivals = arrivalStorage(); + if (fault.startsWith("after-commit")) + arrivals.recordAllocationIntent = async () => { + throw new Error("interrupted before allocation intent"); + }; + await verifiedUser(db, "destination-user", email); + const principal = { + userId: "destination-user", + email, + emailVerified: true, + sessionId: "session", + kind: "better-auth", + authenticatedAt: new Date(), + }; + let verifications = 0; + const authentication = { + requireSession: async () => principal, + verifySignInCode: async ({ email: destinationEmail, otp }) => { + verifications++; + assert.equal(destinationEmail, email); + return { + ok: otp === "fresh-otp", + principal: { + ...principal, + ...(mutation === "wrong-user" ? { userId: "other-user" } : {}), + }, + }; + }, + }; + const config = { + inviteCodeRequired: true, + pds: hosts, + issuer: "https://entryway.example.test", + clientUrl: "https://client.example.test", + serviceDid: "did:web:entryway.example.test", + betterAuthSecret: "unit-test-secret", + jwtJwk: generateKeyPairSync("ec", { + namedCurve: "secp256k1", + }).privateKey.export({ format: "jwk" }), + }; + const store = createOperationOwnershipStore(db); + const ownership = createOperationOwnership({ + store: { + ...store, + async checkpoint(...args) { + if ( + fault === "after-commit-complete-fails" && + args[1].phase === "complete" && + !completionFailed + ) { + completionFailed = true; + throw new Error("completion interrupted"); + } + if (fault === "before-checkpoint") throw new Error("checkpoint fault"); + await store.checkpoint(...args); + if (fault === "after-checkpoint") throw new Error("checkpoint fault"); + }, + release: fault === "after-commit-crash" ? async () => {} : store.release, + }, + heartbeatMs: 0, + }); + let completionFailed = false; + let publicationMode = "normal"; + let directoryReads = 0; + let credentialsIssued = 0; + const publicationAttempts = []; + const accounts = { + ownership, + storage, + get: (value) => storage.getByDid(value), + plcSigner: await Secp256k1MigrationPlcSigner.fromHex( + Buffer.from(await hot.export()).toString("hex"), + ), + plcClient: { + url: "https://plc.example.test", + getAuditableLog: async () => { + if ( + backendState.mode === "directory-outage" && + backendState.creates > 0 + ) + throw new Error("directory unavailable"); + return structuredClone(audit); + }, + getDocument: async () => { + directoryReads++; + return plc.formatDidDoc({ + did, + ...plc.normalizeOp(audit.at(-1).operation), + }); + }, + sendOperation: async (subject, operation) => { + assert.equal(subject, did); + const admissions = await query(db, "SELECT * FROM arrival_replay"); + const signed = await query( + db, + "SELECT * FROM arrival_signed_operations", + ); + assert.equal( + admissions.filter((item) => item.method === incomingHandoffMethod) + .length, + 1, + ); + assert.equal(signed.length, 1); + assert.deepEqual(JSON.parse(signed[0].operation), operation); + publicationAttempts.push(structuredClone(operation)); + if (publicationMode === "lost-unapplied") + throw new Error("response lost"); + audit.push({ + did, + cid: String(await cidForCbor(operation)), + operation: structuredClone(operation), + nullified: false, + createdAt: new Date().toISOString(), + }); + if (publicationMode === "lost-applied") + throw new Error("response lost"); + }, + getLastOp: async () => + mutation === "race" + ? { ...predecessor, sig: "changed" } + : audit.at(-1).operation, + }, + }; + const browserFlow = createBrowserFlow({ + db, + config, + provider: { + deviceManager: { load: async () => ({ deviceId: "browser" }) }, + }, + }); + const request = { headers: { origin: config.issuer }, body: {} }; + request.body.csrf = (await browserFlow.loadBrowser(request)).csrf; + let reservations = 0; + const backendState = { + exists: false, + deactivated: false, + creates: 0, + pauses: 0, + activations: 0, + dataWrites: 0, + calls: [], + onActivate: null, + mode: "normal", + exactMove: null, + adminExtras: {}, + }; + + const originalFetch = globalThis.fetch; + t.after(() => { + globalThis.fetch = originalFetch; + }); + globalThis.fetch = async (url, options) => { + const parsedUrl = new URL(url); + backendState.calls.push(parsedUrl.pathname.split("/").at(-1)); + if (parsedUrl.pathname.endsWith("importRepo")) { + backendState.dataWrites++; + return Response.json({}); + } + if (parsedUrl.pathname.endsWith("getAccountInfo")) { + assert.match(options.headers.authorization, /^Basic /); + if (backendState.mode === "network") + throw new Error("network unavailable"); + if (backendState.mode === "malformed") return Response.json({ did }); + if (!backendState.exists) + return Response.json({ error: "NotFound" }, { status: 404 }); + return Response.json({ + did: backendState.mode === "wrong-did" ? "did:plc:wrong" : did, + handle, + indexedAt: new Date().toISOString(), + ...backendState.adminExtras, + ...(backendState.deactivated + ? { deactivatedAt: new Date().toISOString() } + : {}), + }); + } + if (parsedUrl.pathname.endsWith("createAccount")) { + backendState.creates++; + const body = JSON.parse(options.body); + const recorded = ( + await query( + db, + "SELECT operation FROM arrival_signed_operations WHERE kind = 'destination-move'", + ) + )[0]; + assert.deepEqual(body.plcOp, JSON.parse(recorded.operation)); + assert.equal((await arrivals.readArrivalAccess(did)).bound, false); + assert.equal(body.handle, handle); + assert.equal(body.did, did); + assert.equal(body.plcOp.verificationMethods.atproto, repository.did()); + assert.equal(body.plcOp.services.atproto_pds.endpoint, endpoint); + assert.equal(typeof body.plcOp.sig, "string"); + assert.ok(body.plcOp.sig.length > 0); + backendState.exactMove = body.plcOp; + if (backendState.mode === "creation-rejected") + return Response.json({ error: "InvalidRequest" }, { status: 400 }); + if (backendState.mode !== "unchanged-head") + audit.push({ + did, + operation: body.plcOp, + cid: String(await cidForCbor(body.plcOp)), + nullified: false, + createdAt: new Date().toISOString(), + }); + if (backendState.mode === "malformed-head") audit.at(-1).cid = "invalid"; + if (backendState.mode !== "published-absent") backendState.exists = true; + if (["creation-lost", "published-absent"].includes(backendState.mode)) + throw new Error("creation response lost"); + return Response.json({ + did, + handle, + accessJwt: "discarded-access", + refreshJwt: "discarded-refresh", + }); + } + if ( + parsedUrl.pathname.endsWith("updateSubjectStatus") && + JSON.parse(options.body).deactivated.applied === false + ) { + backendState.activations++; + assert.equal(options.headers.authorization.startsWith("Basic "), true); + await backendState.onActivate?.(); + if (backendState.mode === "activation-dropped") + throw new Error("activation request dropped"); + if (backendState.mode === "activation-rejected") + return Response.json({ error: "InvalidRequest" }, { status: 400 }); + if (backendState.mode !== "activation-ignored") + backendState.deactivated = false; + if (backendState.mode === "activation-lost") + throw new Error("activation response lost"); + return Response.json({}); + } + if (parsedUrl.pathname.endsWith("updateSubjectStatus")) { + backendState.pauses++; + assert.deepEqual(JSON.parse(options.body), { + subject: { $type: "com.atproto.admin.defs#repoRef", did }, + deactivated: { applied: true }, + }); + assert.equal((await arrivals.readArrivalAccess(did)).bound, false); + if (backendState.mode === "pause-rejected") + return Response.json({ error: "InvalidRequest" }, { status: 400 }); + backendState.deactivated = true; + if (backendState.mode === "pause-lost") + throw new Error("pause response lost"); + return Response.json({}); + } + reservations++; + assert.equal( + String(url), + `${endpoint}/xrpc/com.atproto.server.reserveSigningKey`, + ); + assert.deepEqual(JSON.parse(options.body), { did }); + assert.equal(options.headers.authorization, undefined); + const rows = await query(db, "SELECT * FROM arrival_reservations"); + assert.equal(rows.length, 1); + assert.equal(rows[0].signing_key, null); + if (mutation === "lost") throw new Error("reservation response lost"); + if (mutation === "http") return new Response("{}", { status: 503 }); + return Response.json({ signingKey: repository.did() }); + }; + const legacy = await createLegacy({ db, config, accounts }); + const composed = await composeIncomingArrival({ + db, + arrivals, + config, + accounts, + legacy, + authentication, + browserFlow, + }); + return { + get db() { + return db; + }, + legacy, + storage, + arrivals, + backendState, + async reopen() { + await db.close(); + db = await openTestDatabase(path); + return arrivalStorage(); + }, + request, + config, + principal, + ownership, + store, + audit, + publicationAttempts, + setPublicationMode: (value) => { + publicationMode = value; + }, + directoryReads: () => directoryReads, + credentialsIssued: () => credentialsIssued, + async credential(method = incomingHandoffMethod, overrides = {}) { + credentialsIssued++; + if (overrides.jti !== undefined) { + const now = Math.floor(Date.now() / 1000); + const header = Buffer.from( + JSON.stringify({ typ: "JWT", alg: "ES256K" }), + ).toString("base64url"); + const payload = Buffer.from( + JSON.stringify({ + iss: did, + aud: config.serviceDid, + lxm: method, + iat: now, + exp: now + 120, + ...overrides, + }), + ).toString("base64url"); + const bytes = `${header}.${payload}`; + return `Bearer ${bytes}.${Buffer.from(await source.sign(Buffer.from(bytes))).toString("base64url")}`; + } + return `Bearer ${await createServiceJwt({ iss: did, aud: config.serviceDid, lxm: method, keypair: source, ...overrides })}`; + }, + did, + predecessor, + head, + source, + hot, + repository, + composed, + reservations: () => reservations, + verifications: () => verifications, + prepare: (otp = "fresh-otp") => + composed.prepareArrival(request, otp, { did, handle }), + }; +} + +export async function admitProvisioning(f, interruptHandoff = false) { + const prepared = await f.prepare(); + const operation = await plc.signOperation(prepared.handoff, f.source); + const dispatch = f.ownership.dispatch; + if (interruptHandoff) + f.ownership.dispatch = async () => { + throw new Error("interrupted before handoff dispatch"); + }; + const handoff = f.composed.admitIncoming(f.request, { + operationId: prepared.operationId, + method: incomingHandoffMethod, + body: { operation }, + presentation: await f.credential(), + arrivalCode: prepared.arrivalCode, + }); + if (interruptHandoff) + await assert.rejects(handoff, /interrupted before handoff dispatch/); + else await handoff; + f.ownership.dispatch = dispatch; + const { createInvites } = + await import("../../../dist/src/features/account-registration/invites.mjs"); + const invites = await createInvites({ + db: f.db, + config: f.config, + accounts: { get: async () => null }, + }); + const { code } = await invites.createInviteCode({ useCount: 1 }); + await f.composed.admitIncoming(f.request, { + operationId: prepared.operationId, + method: incomingCreationMethod, + body: { handle, inviteCode: code }, + presentation: await f.credential(incomingCreationMethod), + arrivalCode: prepared.arrivalCode, + }); + return prepared; +} diff --git a/tests/support/helpers/incoming-arrival-live.mjs b/tests/support/helpers/incoming-arrival-live.mjs index dc38525d..ad311a3e 100644 --- a/tests/support/helpers/incoming-arrival-live.mjs +++ b/tests/support/helpers/incoming-arrival-live.mjs @@ -1,3 +1,4 @@ +import { createLegacy } from "../../../dist/src/oauth/legacy-credentials.mjs"; import assert from "node:assert/strict"; import { readFile, writeFile, mkdir } from "node:fs/promises"; import { createOperationOwnershipStore } from "../../../dist/src/database/drizzle/operation-ownership.js"; @@ -112,6 +113,7 @@ export async function qualifyIncomingArrival(t, fault = "normal") { { did, user_id: userId }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => storage.activatePlacedAccount(subject), insertPlacedAccount: (input) => storage.insertAccount( { @@ -132,6 +134,7 @@ export async function qualifyIncomingArrival(t, fault = "normal") { arrivals, config, accounts, + legacy: await createLegacy({ db, config, accounts }), authentication, browserFlow, }); diff --git a/tests/support/helpers/incoming-arrival-restart.mjs b/tests/support/helpers/incoming-arrival-restart.mjs index f604b3b2..eb12cb53 100644 --- a/tests/support/helpers/incoming-arrival-restart.mjs +++ b/tests/support/helpers/incoming-arrival-restart.mjs @@ -1,3 +1,4 @@ +import { createLegacy } from "../../../dist/src/oauth/legacy-credentials.mjs"; import assert from "node:assert/strict"; import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -124,6 +125,7 @@ const arrivals = createArrivalStorage(db, hosts, { { did, user_id: owner }, { ignoreConflict: true }, ), + activatePlacedAccount: (subject) => storage.activatePlacedAccount(subject), insertPlacedAccount: (input) => storage.insertAccount( { @@ -327,17 +329,19 @@ const config = { namedCurve: "secp256k1", }).privateKey.export({ format: "jwk" }), }; +const fixtureAccounts = { + ownership, + storage, + get: (did) => storage.getByDid(did), + plcClient: client, + plcSigner: signer, +}; const composed = await composeIncomingArrival({ db, arrivals, config, - accounts: { - ownership, - storage, - get: (did) => storage.get(did), - plcClient: client, - plcSigner: signer, - }, + legacy: await createLegacy({ db, config, accounts: fixtureAccounts }), + accounts: fixtureAccounts, authentication: { requireSession: async () => { if (phase === "resume-unexpected-gate")