diff --git a/doc/2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md b/doc/2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md index 755accaf8..840b59f61 100644 --- a/doc/2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md +++ b/doc/2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md @@ -384,6 +384,52 @@ The importing node verifies before ingesting anything: hosted-origin objects are indistinguishable from self-hosted ones at the object layer. +### 6.3 Object-model mapping (slice 4b, #13157) + +The wiring from a live per-user store to the §6.1 format settles the +mapping between the store's object model and the export's: + +- **Bytes.** An export object's bytes are the stored signed envelope + (the p2panda header) **verbatim**. The store of record keeps the + received bytes as the event and never re-encodes or re-signs them; + the export doesn't either. The producer never re-signs an object + with any key — it holds none it could sign with. +- **Hash.** The object's export hash is SHA-256 of the envelope + bytes. It is the export-layer digest: canonical (hash) order and + the manifest's concatenated-hash digest are computed over it. The + envelope's own BLAKE3 operation id remains its identity at the + object layer; neither hash replaces the other. +- **Signer and signature.** The signer is the envelope's author and + the signature is the envelope's own — Ed25519 over the canonical + header encoding, the object's native scheme. §6.2 step 3's "hash + and signature verify" therefore reads: the hash is SHA-256 of the + received bytes, and the signature verifies by decoding the + envelope exactly as the native decoder does, with the decoded + author equal to the named signer and the signer a key in the + binding chain (§6.2 step 2's chain). +- **Blob citations.** A `document.put` envelope cites its content + by BLAKE3 (`DocumentRef.content`, the native blob identity), + while hosted R2 blobs are SHA-256-addressed (the per-user + reference table is the access path). The producer resolves + citations by content: a fetched blob whose BLAKE3 equals the + citation is the cited blob, and the export names it — in the + blob set and in the object's references — by its SHA-256 hash. + A citation no referenced blob satisfies, or a referenced blob R2 + cannot produce, fails the export loudly, naming the hash; an + export is never silently incomplete. Blobs no exported object + cites are not exported (§6.1 item 2, §6.2's unreferenced-blob + rule). +- **Object set.** The exported objects are the store's *applied* + events — the graph. Waiting-pool events (dependencies unmet, not + yet graph objects) and fork-proof headers (evidence about the + graph) are not exported. + +Production lives in the hosted data plane (`hosted-worker/src/ +export.ts`, served by the DO's `GET /v1/bridge/export` route under +the bridge's ID-key proof); assembly into the full export +(manifest, binding record, rebind records) is `build_export` on +the binding-service side. + ## 7. Client-side-encryption option Offered at binding time (and changeable later only by re-encrypting via diff --git a/pkgs/id/hosted-worker/README.md b/pkgs/id/hosted-worker/README.md index 160db9770..58caea604 100644 --- a/pkgs/id/hosted-worker/README.md +++ b/pkgs/id/hosted-worker/README.md @@ -71,6 +71,17 @@ serves no authoritative snapshot. ceiling. Design record: `doc/2026-11-23T05-00-00Z_design_bridge_v1_implementation/`. Cross-language fixtures: `pkgs/id/tests/bridge_fixtures.rs`. +- `src/export.ts` — §6 export production (slice 4b of #2852, + #13157): enumerates the DO's applied events and the R2 blobs + they cite into the object/blob sets `build_export` + (`pkgs/id/src/hosted_export.rs`) assembles, under the + object-model mapping recorded in the spec as §6.3. Route: + `GET /v1/bridge/export`, ID-key proof like the other bridge + HTTPS legs; a pure read, available at cap, and a referenced + blob R2 cannot produce fails it loudly (502 naming the hash). + The produced sets are pinned to + `test/fixtures/hosted-export-sets.json`, which the Rust suite + verifies through `build_export` + `verify_import`. ## Tests diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index e08e733b8..60921f899 100644 --- a/pkgs/id/hosted-worker/package.json +++ b/pkgs/id/hosted-worker/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "wrangler dev", "typecheck": "tsc --noEmit", - "test": "node --experimental-transform-types --test test/routing.test.ts test/admission-gate.test.ts test/provisioning.test.ts test/provisioning-surface.test.ts test/blobs.test.ts test/canonical-cbor.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts test/id-uri-vectors.test.ts test/bridge-blake3.test.ts test/bridge-event.test.ts test/bridge-range.test.ts test/bridge-store.test.ts test/bridge-session.test.ts test/bridge-do.test.ts", + "test": "node --experimental-transform-types --test test/routing.test.ts test/admission-gate.test.ts test/provisioning.test.ts test/provisioning-surface.test.ts test/blobs.test.ts test/canonical-cbor.test.ts test/usage.test.ts test/currency.test.ts test/front-door.test.ts test/id-uri-vectors.test.ts test/bridge-blake3.test.ts test/bridge-event.test.ts test/bridge-range.test.ts test/bridge-store.test.ts test/bridge-session.test.ts test/bridge-do.test.ts test/export.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/src/bridge-auth.ts b/pkgs/id/hosted-worker/src/bridge-auth.ts index 71acc0677..9d968c99b 100644 --- a/pkgs/id/hosted-worker/src/bridge-auth.ts +++ b/pkgs/id/hosted-worker/src/bridge-auth.ts @@ -27,7 +27,7 @@ import type { BridgeStore } from "./bridge-store.ts"; export const NONCE_TTL_MS = 5 * 60 * 1000; export const RESUME_TOKEN_TTL_MS = 24 * 3600 * 1000; -export type AuthContext = "push" | "pull" | "heads" | "ws"; +export type AuthContext = "push" | "pull" | "heads" | "ws" | "export"; export function authTranscript( bindingId: string, diff --git a/pkgs/id/hosted-worker/src/bridge-store.ts b/pkgs/id/hosted-worker/src/bridge-store.ts index 200fb0d73..ae6e2568b 100644 --- a/pkgs/id/hosted-worker/src/bridge-store.ts +++ b/pkgs/id/hosted-worker/src/bridge-store.ts @@ -264,6 +264,23 @@ export class BridgeStore { .filter((e): e is HeldEvent => e !== null); } + /** The applied chain events — the graph itself, in (author, seq) + * order. The §6 export set (export.ts) is exactly these: waiting + * events are not yet graph objects (their dependencies are unmet) + * and fork-proof headers are evidence about the graph, not part + * of it, so neither is enumerated here. */ + appliedEvents(): HeldEvent[] { + return this.sql + .exec("SELECT author, seq, id, bytes FROM bridge_events ORDER BY author, seq") + .toArray() + .map((r) => ({ + author: r.author as string, + seq: Number(r.seq), + id: r.id as string, + bytes: blobBytes(r.bytes), + })); + } + /** Bytes stored by this store, for the storage ceiling. */ storedBytes(): number { const rows = this.sql.exec( diff --git a/pkgs/id/hosted-worker/src/event.ts b/pkgs/id/hosted-worker/src/event.ts index 89c033a06..9867db84d 100644 --- a/pkgs/id/hosted-worker/src/event.ts +++ b/pkgs/id/hosted-worker/src/event.ts @@ -76,6 +76,11 @@ export interface SignedEvent { bytes: Uint8Array; author: Uint8Array; authorHex: string; + /** The envelope's own Ed25519 signature (over the signing bytes), + * carried verbatim: the §6 export mapping (export.ts) names it as + * the object's signature — a stored event is never re-signed. */ + signature: Uint8Array; + signatureHex: string; seq: number; backlink: Uint8Array | null; backlinkHex: string | null; @@ -321,6 +326,8 @@ function parseEventParts(bytes: Uint8Array): EventParts { bytes, author, authorHex: bytesToHex(author), + signature, + signatureHex: bytesToHex(signature), seq, backlink, backlinkHex: backlink ? bytesToHex(backlink) : null, diff --git a/pkgs/id/hosted-worker/src/export.ts b/pkgs/id/hosted-worker/src/export.ts new file mode 100644 index 000000000..ed291a0ee --- /dev/null +++ b/pkgs/id/hosted-worker/src/export.ts @@ -0,0 +1,232 @@ +// §6 export production (spec §6.1 items 1–2; #2852 slice 4b, +// #13157): enumerate a per-user DO's applied signed objects and the +// R2 blobs they cite, as the object/blob sets `build_export` +// (pkgs/id/src/hosted_export.rs) assembles into a `HostedExport`. +// The binding record, its rebind records, and the manifest live on +// the binding-service side; this module is the data-plane half — +// everything the DO itself can produce, as a pure read. Export +// therefore stays available from a read-only, at-cap store (§5.4): +// nothing here writes. +// +// The object-model mapping this wiring settles (spec §6.3): +// +// - `bytes` is the stored envelope bytes verbatim. The bridge never +// re-encodes or re-signs a stored event; the export doesn't +// either. +// - `hash` is SHA-256 of the envelope bytes: the export-layer +// digest that canonical (hash) order and the manifest's +// concatenated-hash digest are computed over. The envelope's own +// BLAKE3 id remains its identity at the object layer. +// - `signer` is the envelope's author key and `signature` is the +// envelope's own signature, over the canonical header encoding — +// the object's own signature scheme, verified at import by +// decoding the envelope exactly as chain.rs `decode` does. The +// producer never re-signs: it holds no key it could sign with. +// - Payload bodies are not held by this store (the bridge keeps +// headers; a header's payload_hash commits to off-store data) +// and are not §6 blobs of this store — document content is the +// blob path, mapped as follows. +// - Blob citations: a `document.put` envelope cites its content by +// BLAKE3 (`DocumentRef.content`, the native blob identity), while +// this store's R2 blobs are SHA-256-addressed (the slice-A +// reference table). Citations are resolved by content: a fetched +// blob whose BLAKE3 equals the citation is the cited blob, and +// the export names it by its SHA-256 hash (§6 form). A citation +// no referenced blob satisfies — or a referenced blob R2 cannot +// produce — fails the export loudly, naming the hash; an export +// is never silently incomplete. Blobs no applied object cites +// are not exported (§6.1 item 2, §6.2's unreferenced-blob rule). + +import { decodeCanonical, type CborValue } from "./canonical-cbor.ts"; +import { blake3 } from "./blake3.ts"; +import { bytesToHex } from "./ed25519.ts"; +import { parseEvent } from "./event.ts"; +import type { HeldEvent } from "./bridge-store.ts"; + +/** One §6 object (§6.1 item 1) in the `ExportObject` wire shape, + * with bytes still binary; `exportSetsToWire` renders the JSON + * form serde expects on the Rust side. */ +export interface ExportObjectSet { + hash: string; + signer: string; + signature: string; + blob_refs: string[]; + bytes: Uint8Array; +} + +/** One §6 blob (§6.1 item 2) in the `ExportBlob` wire shape. */ +export interface ExportBlobSet { + hash: string; + bytes: Uint8Array; +} + +/** The object/blob sets of a §6 export, in canonical (hash) + * order, with the manifest's counts and concatenated-hash digest + * (§6.1 item 4) computed over exactly these sets. */ +export interface ExportSets { + objects: ExportObjectSet[]; + blobs: ExportBlobSet[]; + object_count: number; + blob_count: number; + objects_digest: string; +} + +/** A named export-production failure. `hash` is the hash the + * failure names: the cited content hash (BLAKE3) an object needs + * and no referenced blob produces, or the reference hash (SHA-256) + * whose stored bytes R2 cannot produce or cannot verify. */ +export class ExportProductionError extends Error { + readonly hash: string; + constructor(hash: string, message: string) { + super(message); + this.hash = hash; + } +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource); + return bytesToHex(new Uint8Array(digest)); +} + +function mapGet(map: CborValue, key: string): CborValue | undefined { + if (map.kind !== "map") return undefined; + for (const [k, v] of map.value) { + if (k.kind === "text" && k.value === key) return v; + } + return undefined; +} + +/** The BLAKE3 content hashes an envelope cites: the `content` of + * its `document` payload (`document.put`), and nothing else — in + * the current `ChainExt` form one envelope cites at most one + * content. The envelope was verified at ingest; a document payload + * that does not carry a 32-byte content hash is corruption, and is + * refused as such rather than silently uncited. */ +export function citedContentHashes(bytes: Uint8Array, eventId: string): string[] { + const root = decodeCanonical(bytes); + if (root.kind !== "array" || root.value.length === 0) { + throw new ExportProductionError(eventId, `stored event ${eventId} is not a header array`); + } + const ext = root.value[root.value.length - 1]; + const document = mapGet(ext, "document"); + if (document === undefined) return []; + const content = mapGet(document, "content"); + if (!content || content.kind !== "bytes" || content.value.length !== 32) { + throw new ExportProductionError( + eventId, + `stored event ${eventId} carries a document payload with no 32-byte content hash`, + ); + } + return [bytesToHex(content.value)]; +} + +/** Produce the §6 object/blob sets from a store enumeration. + * + * `events` is the store's applied events (`BridgeStore + * .appliedEvents()`); `blobRefs` is the user's blob reference + * table (SHA-256 hashes, the slice-A access path); `fetchBlob` + * reads one blob's bytes from R2 by its reference hash, returning + * null when R2 cannot produce it. */ +export async function produceExportSets( + events: HeldEvent[], + blobRefs: { hash: string }[], + fetchBlob: (hash: string) => Promise, +): Promise { + // Fetch and verify every referenced blob first: the export is + // assembled only from bytes that hash to their reference. + const blobsBySha = new Map(); + const shaByContent = new Map(); + for (const ref of blobRefs) { + const bytes = await fetchBlob(ref.hash); + if (bytes === null) { + throw new ExportProductionError( + ref.hash, + `blob ${ref.hash} is referenced by this store but R2 cannot produce it`, + ); + } + const actual = await sha256Hex(bytes); + if (actual !== ref.hash) { + throw new ExportProductionError( + ref.hash, + `blob bytes fetched for ${ref.hash} hash to ${actual}; the stored blob is corrupt`, + ); + } + blobsBySha.set(ref.hash, { hash: ref.hash, bytes }); + shaByContent.set(bytesToHex(blake3(bytes)), ref.hash); + } + + const objects: ExportObjectSet[] = []; + const citedShas = new Set(); + for (const held of events) { + const event = parseEvent(held.bytes); + const refs: string[] = []; + for (const cited of citedContentHashes(held.bytes, held.id)) { + const sha = shaByContent.get(cited); + if (sha === undefined) { + throw new ExportProductionError( + cited, + `object ${held.id} cites content ${cited} but no referenced blob produces it`, + ); + } + refs.push(sha); + citedShas.add(sha); + } + refs.sort(); + objects.push({ + hash: await sha256Hex(held.bytes), + signer: event.authorHex, + signature: event.signatureHex, + blob_refs: [...new Set(refs)], + bytes: held.bytes, + }); + } + objects.sort((a, b) => (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0)); + + const blobs = [...citedShas].map((sha) => blobsBySha.get(sha) as ExportBlobSet); + blobs.sort((a, b) => (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0)); + + // §6.1 item 4: SHA-256 of the concatenated object hash bytes, + // objects in canonical (hash) order — the same computation + // hosted_export.rs performs over the received set. + const concatenated = new Uint8Array(objects.length * 32); + objects.forEach((object, i) => { + for (let j = 0; j < 32; j++) { + concatenated[i * 32 + j] = parseInt(object.hash.slice(j * 2, j * 2 + 2), 16); + } + }); + const objects_digest = await sha256Hex(concatenated); + + return { + objects, + blobs, + object_count: objects.length, + blob_count: blobs.length, + objects_digest, + }; +} + +/** The JSON wire form of the sets: byte fields as number arrays, + * exactly the serde shape of `ExportObject` / `ExportBlob` in + * hosted_export.rs, so the binding-service side can feed the sets + * to `build_export` without a translation layer. */ +export function exportSetsToWire(sets: ExportSets): { + objects: { hash: string; signer: string; signature: string; blob_refs: string[]; bytes: number[] }[]; + blobs: { hash: string; bytes: number[] }[]; + object_count: number; + blob_count: number; + objects_digest: string; +} { + return { + objects: sets.objects.map((o) => ({ + hash: o.hash, + signer: o.signer, + signature: o.signature, + blob_refs: o.blob_refs, + bytes: [...o.bytes], + })), + blobs: sets.blobs.map((b) => ({ hash: b.hash, bytes: [...b.bytes] })), + object_count: sets.object_count, + blob_count: sets.blob_count, + objects_digest: sets.objects_digest, + }; +} diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 85bf8df4d..eb13c047b 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -46,6 +46,7 @@ import { type FrameTransport, } from "./bridge-session.ts"; import type { IngestOutcome } from "./bridge-store.ts"; +import { ExportProductionError, exportSetsToWire, produceExportSets } from "./export.ts"; export const SCHEMA_VERSION = 3; @@ -509,6 +510,35 @@ export class UserDO { }, }); } + if (url.pathname === "/v1/bridge/export" && req.method === "GET") { + // §6 export production (slice 4b, #13157): the applied + // objects and the blobs they cite, as the sets build_export + // assembles. A pure read — like every read it stays + // available from a read-only, at-cap store (§5.4) — and a + // blob the store references but R2 cannot produce fails + // the export loudly (502 naming the hash), never silently + // incomplete. + const irohHex = this.requireIroh(req); + const store = await this.bridgeProof(req, bindingId, irohHex, "export", new Uint8Array(0)); + const bucket = blobsBindingFor(this.env, jurisdiction as Jurisdiction); + const blobRows = this.state.storage.sql + .exec("SELECT hash FROM blobs ORDER BY hash") + .toArray() + .map((r) => ({ hash: String(r.hash) })); + try { + const sets = await produceExportSets(store.appliedEvents(), blobRows, async (hash) => { + const obj = await bucket.get(hash); + if (!obj) return null; + return new Uint8Array(await new Response(obj.body).arrayBuffer()); + }); + return json(exportSetsToWire(sets)); + } catch (e) { + if (e instanceof ExportProductionError) { + throw new FailClosed(502, "export_production_failed", e.message); + } + throw e; + } + } if (url.pathname === "/v1/bridge/ws" && req.method === "GET") { const irohHex = this.requireIroh(req); if ((req.headers.get("upgrade") ?? "").toLowerCase() !== "websocket") { diff --git a/pkgs/id/hosted-worker/test/export.test.ts b/pkgs/id/hosted-worker/test/export.test.ts new file mode 100644 index 000000000..9b19447a3 --- /dev/null +++ b/pkgs/id/hosted-worker/test/export.test.ts @@ -0,0 +1,337 @@ +// §6 export production at the Durable Object boundary (slice 4b, +// #13157): a seeded per-user DO — signed events pushed through the +// bridge, blobs uploaded through the slice-A routes — produces the +// §6 object/blob sets through GET /v1/bridge/export. The produced +// sets are pinned to a committed fixture +// (test/fixtures/hosted-export-sets.json) that the Rust suite in +// pkgs/id/src/hosted_export.rs feeds through build_export + +// verify_import: the two suites pin the same mapping from both +// ends. Regenerate the fixture with UPDATE_EXPORT_FIXTURE=1. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import { readFileSync, writeFileSync } from "node:fs"; +import { HDR_BINDING, HDR_IROH, HDR_JURISDICTION, HDR_ROUTED, UserDO } from "../src/user-do.ts"; +import { authTranscript, bodyHashHex, type AuthContext } from "../src/bridge-auth.ts"; +import { blake3 } from "../src/blake3.ts"; +import { bytesToHex, importIdKey, type IdKey } from "../src/ed25519.ts"; +import { signEvent, type SignedEvent } from "../src/event.ts"; +import { encodeBatch } from "../src/bridge-session.ts"; +import type { CborValue } from "../src/canonical-cbor.ts"; + +const BINDING = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const FIXTURE_PATH = new URL("./fixtures/hosted-export-sets.json", import.meta.url); + +/** The fixture author's seed: the Rust fixture test rebuilds the + * binding with this same seed as its root key. */ +const AUTHOR_SEED = new Uint8Array(32).fill(7); + +const BLOB_ALPHA = new TextEncoder().encode("export fixture blob alpha"); +const BLOB_BETA = new TextEncoder().encode("export fixture blob beta — second content"); + +function fakeSql() { + const db = new DatabaseSync(":memory:"); + return { + exec(query: string, ...params: unknown[]) { + const stmt = db.prepare(query); + if (/^\s*select/i.test(query)) { + const rows = stmt.all(...(params as never[])) as Record[]; + return { toArray: () => rows }; + } + stmt.run(...(params as never[])); + return { toArray: () => [] as Record[] }; + }, + }; +} + +function fakeBucket() { + const objects = new Map(); + return { + objects, + async head(key: string) { + const v = objects.get(key); + return v ? { size: v.byteLength } : null; + }, + async get(key: string) { + const v = objects.get(key); + if (!v) return null; + return { + size: v.byteLength, + body: new ReadableStream({ + start(c) { + c.enqueue(v); + c.close(); + }, + }), + }; + }, + async put(key: string, value: ArrayBuffer | Uint8Array) { + objects.set(key, value instanceof Uint8Array ? value : new Uint8Array(value)); + }, + async delete(key: string) { + objects.delete(key); + }, + }; +} + +type Bucket = ReturnType; +type Sql = ReturnType; + +function makeDO(sql: Sql, bucket: Bucket, env: Record = {}) { + const state = { + id: { name: BINDING }, + storage: { sql }, + blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), + }; + return new UserDO(state as never, { BLOBS: bucket, ...env } as never); +} + +function routed(path: string, irohHex: string | null, init: RequestInit = {}): Request { + const headers = new Headers(init.headers); + headers.set(HDR_BINDING, BINDING); + headers.set(HDR_JURISDICTION, "us"); + headers.set(HDR_ROUTED, "restricted"); + if (irohHex !== null) headers.set(HDR_IROH, irohHex); + return new Request("https://do" + path, { ...init, headers }); +} + +async function challenge(doA: UserDO, irohHex: string): Promise { + const res = await doA.fetch(routed("/v1/bridge/challenge", irohHex)); + assert.equal(res.status, 200); + const body = (await res.json()) as { nonce: string }; + return body.nonce; +} + +async function proofHeaders( + key: IdKey, + nonce: string, + context: AuthContext, + body: Uint8Array, +): Promise> { + const transcript = authTranscript(BINDING, nonce, context, bodyHashHex(body)); + const signature = await key.sign(transcript); + return { "x-id-nonce": nonce, "x-id-proof": bytesToHex(signature) }; +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource); + return bytesToHex(new Uint8Array(digest)); +} + +const T = (v: string): CborValue => ({ kind: "text", value: v }); +const B = (v: Uint8Array): CborValue => ({ kind: "bytes", value: v }); +const U = (v: bigint): CborValue => ({ kind: "uint", value: v }); + +function documentExtra(content: Uint8Array, size: number): [string, CborValue] { + return [ + "document", + { + kind: "map", + value: [ + [T("media_type"), T("text/plain")], + [T("content"), B(blake3(content))], + [T("size"), U(BigInt(size))], + ], + }, + ]; +} + +interface Seeded { + doA: UserDO; + sql: Sql; + bucket: Bucket; + key: IdKey; + events: SignedEvent[]; + blobHashes: { alpha: string; beta: string }; +} + +/** Seeds the fixture store: two blobs through the slice-A routes, + * then a four-event chain through the bridge — a plain message, a + * document citing alpha, a document citing beta, and a second + * document citing alpha again. */ +async function seedStore(): Promise { + const sql = fakeSql(); + const bucket = fakeBucket(); + const doA = makeDO(sql, bucket); + const key = await importIdKey(AUTHOR_SEED); + + const putBlob = async (bytes: Uint8Array): Promise => { + const res = await doA.fetch(routed("/v1/blobs", null, { method: "PUT", body: bytes as BodyInit })); + assert.equal(res.status, 200); + const body = (await res.json()) as { hash: string }; + return body.hash; + }; + const alpha = await putBlob(BLOB_ALPHA); + const beta = await putBlob(BLOB_BETA); + assert.equal(alpha, await sha256Hex(BLOB_ALPHA)); + assert.equal(beta, await sha256Hex(BLOB_BETA)); + + const drafts: [string, [string, CborValue] | null][] = [ + ["message", null], + ["document.put", documentExtra(BLOB_ALPHA, BLOB_ALPHA.byteLength)], + ["document.put", documentExtra(BLOB_BETA, BLOB_BETA.byteLength)], + ["document.put", documentExtra(BLOB_ALPHA, BLOB_ALPHA.byteLength)], + ]; + const events: SignedEvent[] = []; + for (let seq = 0; seq < drafts.length; seq++) { + const [kind, extra] = drafts[seq]; + events.push( + await signEvent(key, { + seq, + backlink: seq === 0 ? null : events[seq - 1].idBytes, + kind, + extra: extra ? [extra] : [], + }), + ); + } + const batch = encodeBatch(events.map((e) => e.bytes)); + const nonce = await challenge(doA, key.publicHex); + const headers = await proofHeaders(key, nonce, "push", batch); + const push = await doA.fetch( + routed("/v1/bridge/push", key.publicHex, { method: "POST", headers, body: batch as BodyInit }), + ); + assert.equal(push.status, 200); + const pushBody = (await push.json()) as { outcomes: { kind: string }[] }; + assert.deepEqual( + pushBody.outcomes.map((o) => o.kind), + ["accepted", "accepted", "accepted", "accepted"], + ); + return { doA, sql, bucket, key, events, blobHashes: { alpha, beta } }; +} + +async function callExport(doA: UserDO, key: IdKey): Promise { + const nonce = await challenge(doA, key.publicHex); + const headers = await proofHeaders(key, nonce, "export", new Uint8Array(0)); + return doA.fetch(routed("/v1/bridge/export", key.publicHex, { headers })); +} + +interface WireSets { + objects: { hash: string; signer: string; signature: string; blob_refs: string[]; bytes: number[] }[]; + blobs: { hash: string; bytes: number[] }[]; + object_count: number; + blob_count: number; + objects_digest: string; +} + +test("export production: seeded DO yields the §6 sets, pinned to the fixture", async () => { + const { doA, key, events, blobHashes } = await seedStore(); + const res = await callExport(doA, key); + assert.equal(res.status, 200); + const wire = (await res.json()) as WireSets; + + assert.equal(wire.object_count, 4); + assert.equal(wire.blob_count, 2); + assert.equal(wire.objects.length, 4); + assert.equal(wire.blobs.length, 2); + + // Canonical (hash) order, strictly ascending. + const hashes = wire.objects.map((o) => o.hash); + assert.deepEqual(hashes, [...hashes].sort()); + const blobHashList = wire.blobs.map((b) => b.hash); + assert.deepEqual(blobHashList, [...blobHashList].sort()); + + // Every object maps its stored envelope verbatim: bytes are the + // pushed bytes, signer is the author, signature is the envelope's + // own — nothing re-encoded, nothing re-signed. + const byHash = new Map(wire.objects.map((o) => [o.hash, o])); + for (const event of events) { + const object = byHash.get(await sha256Hex(event.bytes)); + assert.ok(object, `event ${event.id} is in the export`); + assert.deepEqual(object.bytes, [...event.bytes]); + assert.equal(object.signer, event.authorHex); + assert.equal(object.signature, event.signatureHex); + } + + // Citations resolved by content to the §6 (SHA-256) blob names: + // alpha cited by two objects, beta by one; each blob carried once. + const docRefs = wire.objects.filter((o) => o.blob_refs.length > 0).map((o) => o.blob_refs[0]); + assert.deepEqual( + docRefs.sort(), + [blobHashes.alpha, blobHashes.alpha, blobHashes.beta].sort(), + ); + assert.deepEqual(blobHashList, [blobHashes.alpha, blobHashes.beta].sort()); + const blobBytes = new Map(wire.blobs.map((b) => [b.hash, b.bytes])); + assert.deepEqual(blobBytes.get(blobHashes.alpha), [...BLOB_ALPHA]); + assert.deepEqual(blobBytes.get(blobHashes.beta), [...BLOB_BETA]); + + // The digest is SHA-256 of the concatenated object hash bytes in + // canonical order, computed here independently of the producer. + const concatenated = new Uint8Array(hashes.length * 32); + hashes.forEach((hash, i) => { + for (let j = 0; j < 32; j++) { + concatenated[i * 32 + j] = parseInt(hash.slice(j * 2, j * 2 + 2), 16); + } + }); + assert.equal(wire.objects_digest, await sha256Hex(concatenated)); + + // The cross-language contract: the Rust suite verifies an export + // assembled from exactly these sets. + if (process.env.UPDATE_EXPORT_FIXTURE) { + writeFileSync(FIXTURE_PATH, JSON.stringify(wire, null, 2) + "\n"); + } else { + const fixture = JSON.parse(readFileSync(FIXTURE_PATH, "utf8")) as WireSets; + assert.deepEqual(wire, fixture); + } +}); + +test("export stays available from a read-only, at-cap store", async () => { + const { doA, sql, bucket, key } = await seedStore(); + const usage = (await (await doA.fetch(routed("/v1/usage", null))).json()) as { + storage_bytes: number; + }; + // A second DO over the same store, capped at exactly its current + // usage: writes fail closed there, reads and export remain. + const capped = makeDO(sql, bucket, { USER_CEILING_BYTES: String(usage.storage_bytes) }); + const res = await callExport(capped, key); + assert.equal(res.status, 200); + const wire = (await res.json()) as WireSets; + assert.equal(wire.object_count, 4); + assert.equal(wire.blob_count, 2); +}); + +test("a referenced blob R2 cannot produce fails the export loudly, naming the hash", async () => { + const { doA, bucket, key, blobHashes } = await seedStore(); + bucket.objects.delete(blobHashes.beta); + const res = await callExport(doA, key); + assert.equal(res.status, 502); + const body = (await res.json()) as { error: string; message: string }; + assert.equal(body.error, "export_production_failed"); + assert.ok( + body.message.includes(blobHashes.beta), + `failure names the missing blob hash: ${body.message}`, + ); +}); + +test("an object citing content no referenced blob produces fails loudly, naming the cited hash", async () => { + const sql = fakeSql(); + const bucket = fakeBucket(); + const doA = makeDO(sql, bucket); + const key = await importIdKey(AUTHOR_SEED); + const ghost = new TextEncoder().encode("content that was never uploaded"); + const event = await signEvent(key, { + seq: 0, + kind: "document.put", + extra: [documentExtra(ghost, ghost.byteLength)], + }); + const batch = encodeBatch([event.bytes]); + const nonce = await challenge(doA, key.publicHex); + const headers = await proofHeaders(key, nonce, "push", batch); + const push = await doA.fetch( + routed("/v1/bridge/push", key.publicHex, { method: "POST", headers, body: batch as BodyInit }), + ); + assert.equal(push.status, 200); + const res = await callExport(doA, key); + assert.equal(res.status, 502); + const body = (await res.json()) as { error: string; message: string }; + assert.equal(body.error, "export_production_failed"); + assert.ok( + body.message.includes(bytesToHex(blake3(ghost))), + `failure names the cited content hash: ${body.message}`, + ); +}); + +test("the export leg fails closed without a proof, like every bridge leg", async () => { + const { doA, key } = await seedStore(); + const res = await doA.fetch(routed("/v1/bridge/export", key.publicHex)); + assert.equal(res.status, 401); +}); diff --git a/pkgs/id/hosted-worker/test/fixtures/hosted-export-sets.json b/pkgs/id/hosted-worker/test/fixtures/hosted-export-sets.json new file mode 100644 index 000000000..306975195 --- /dev/null +++ b/pkgs/id/hosted-worker/test/fixtures/hosted-export-sets.json @@ -0,0 +1,1093 @@ +{ + "objects": [ + { + "hash": "26ebf41231873c299579abc200fe0fda70e295849e64b7d3b96d84cc5cb97016", + "signer": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c", + "signature": "6735baa4aac7c6411c33d9f31b1b7c1188d9a7111b081479a179810fcb577dc461eef7c4add2e85e52e3c1ddd84ff6bd0f99d7666e05b0a8a7304cfcebb4ec0c", + "blob_refs": [ + "747ad0246b0f6d6b8f3bca9f7b62fea5d16eada3bf50b13c4408dd6fa7478436" + ], + "bytes": [ + 135, + 1, + 88, + 32, + 234, + 74, + 108, + 99, + 226, + 156, + 82, + 10, + 190, + 245, + 80, + 123, + 19, + 46, + 197, + 249, + 149, + 71, + 118, + 174, + 190, + 190, + 123, + 146, + 66, + 30, + 234, + 105, + 20, + 70, + 210, + 44, + 88, + 64, + 103, + 53, + 186, + 164, + 170, + 199, + 198, + 65, + 28, + 51, + 217, + 243, + 27, + 27, + 124, + 17, + 136, + 217, + 167, + 17, + 27, + 8, + 20, + 121, + 161, + 121, + 129, + 15, + 203, + 87, + 125, + 196, + 97, + 238, + 247, + 196, + 173, + 210, + 232, + 94, + 82, + 227, + 193, + 221, + 216, + 79, + 246, + 189, + 15, + 153, + 215, + 102, + 110, + 5, + 176, + 168, + 167, + 48, + 76, + 252, + 235, + 180, + 236, + 12, + 0, + 2, + 88, + 32, + 25, + 194, + 216, + 53, + 0, + 122, + 55, + 177, + 105, + 74, + 94, + 199, + 43, + 200, + 174, + 162, + 29, + 41, + 143, + 202, + 53, + 52, + 228, + 88, + 188, + 150, + 44, + 144, + 172, + 184, + 148, + 241, + 165, + 100, + 107, + 105, + 110, + 100, + 108, + 100, + 111, + 99, + 117, + 109, + 101, + 110, + 116, + 46, + 112, + 117, + 116, + 101, + 97, + 102, + 116, + 101, + 114, + 128, + 101, + 103, + 114, + 111, + 117, + 112, + 246, + 102, + 100, + 111, + 109, + 97, + 105, + 110, + 108, + 105, + 100, + 46, + 101, + 118, + 101, + 110, + 116, + 115, + 46, + 118, + 49, + 104, + 100, + 111, + 99, + 117, + 109, + 101, + 110, + 116, + 163, + 100, + 115, + 105, + 122, + 101, + 24, + 43, + 103, + 99, + 111, + 110, + 116, + 101, + 110, + 116, + 88, + 32, + 126, + 152, + 226, + 250, + 174, + 129, + 182, + 105, + 227, + 157, + 211, + 116, + 117, + 199, + 109, + 92, + 124, + 60, + 139, + 72, + 34, + 227, + 57, + 32, + 49, + 165, + 165, + 196, + 126, + 3, + 101, + 207, + 106, + 109, + 101, + 100, + 105, + 97, + 95, + 116, + 121, + 112, + 101, + 106, + 116, + 101, + 120, + 116, + 47, + 112, + 108, + 97, + 105, + 110 + ] + }, + { + "hash": "5a8bd3ac5b961462282634b7113a939884b37913827a3cbe4755ec407bb0ab39", + "signer": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c", + "signature": "0133a0cd6b42f8480ae80a81371312ffc206960eb1a693b0f3c6f32bfbe2889981338cf7e00c87fae580ade9bd1c02bba04e788e53429f2031346c6f36bf0a0f", + "blob_refs": [ + "8b8e421a9547932f90af7f1dd385596349e374a225773638d3e41adb3c6235bc" + ], + "bytes": [ + 135, + 1, + 88, + 32, + 234, + 74, + 108, + 99, + 226, + 156, + 82, + 10, + 190, + 245, + 80, + 123, + 19, + 46, + 197, + 249, + 149, + 71, + 118, + 174, + 190, + 190, + 123, + 146, + 66, + 30, + 234, + 105, + 20, + 70, + 210, + 44, + 88, + 64, + 1, + 51, + 160, + 205, + 107, + 66, + 248, + 72, + 10, + 232, + 10, + 129, + 55, + 19, + 18, + 255, + 194, + 6, + 150, + 14, + 177, + 166, + 147, + 176, + 243, + 198, + 243, + 43, + 251, + 226, + 136, + 153, + 129, + 51, + 140, + 247, + 224, + 12, + 135, + 250, + 229, + 128, + 173, + 233, + 189, + 28, + 2, + 187, + 160, + 78, + 120, + 142, + 83, + 66, + 159, + 32, + 49, + 52, + 108, + 111, + 54, + 191, + 10, + 15, + 0, + 3, + 88, + 32, + 248, + 255, + 74, + 83, + 64, + 53, + 216, + 157, + 89, + 68, + 212, + 154, + 14, + 66, + 37, + 120, + 29, + 130, + 146, + 126, + 53, + 165, + 248, + 131, + 64, + 176, + 132, + 247, + 92, + 165, + 85, + 187, + 165, + 100, + 107, + 105, + 110, + 100, + 108, + 100, + 111, + 99, + 117, + 109, + 101, + 110, + 116, + 46, + 112, + 117, + 116, + 101, + 97, + 102, + 116, + 101, + 114, + 128, + 101, + 103, + 114, + 111, + 117, + 112, + 246, + 102, + 100, + 111, + 109, + 97, + 105, + 110, + 108, + 105, + 100, + 46, + 101, + 118, + 101, + 110, + 116, + 115, + 46, + 118, + 49, + 104, + 100, + 111, + 99, + 117, + 109, + 101, + 110, + 116, + 163, + 100, + 115, + 105, + 122, + 101, + 24, + 25, + 103, + 99, + 111, + 110, + 116, + 101, + 110, + 116, + 88, + 32, + 18, + 58, + 182, + 5, + 218, + 145, + 230, + 183, + 186, + 232, + 19, + 86, + 166, + 252, + 143, + 238, + 40, + 108, + 205, + 72, + 225, + 66, + 72, + 75, + 153, + 29, + 252, + 77, + 11, + 78, + 112, + 116, + 106, + 109, + 101, + 100, + 105, + 97, + 95, + 116, + 121, + 112, + 101, + 106, + 116, + 101, + 120, + 116, + 47, + 112, + 108, + 97, + 105, + 110 + ] + }, + { + "hash": "5c00ef42adf8a1d0ace6f1593bf03a36219c7edb7bd367032559c479e8151df0", + "signer": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c", + "signature": "45b1efcc10fc5d8b6d32cf7bcfafffc3b497fc57324befc9429ac476f20b4faeee04b3b53e20e7d97983775a071f63dfe52ada97088e76f8a837bba2bf0d6c01", + "blob_refs": [ + "8b8e421a9547932f90af7f1dd385596349e374a225773638d3e41adb3c6235bc" + ], + "bytes": [ + 135, + 1, + 88, + 32, + 234, + 74, + 108, + 99, + 226, + 156, + 82, + 10, + 190, + 245, + 80, + 123, + 19, + 46, + 197, + 249, + 149, + 71, + 118, + 174, + 190, + 190, + 123, + 146, + 66, + 30, + 234, + 105, + 20, + 70, + 210, + 44, + 88, + 64, + 69, + 177, + 239, + 204, + 16, + 252, + 93, + 139, + 109, + 50, + 207, + 123, + 207, + 175, + 255, + 195, + 180, + 151, + 252, + 87, + 50, + 75, + 239, + 201, + 66, + 154, + 196, + 118, + 242, + 11, + 79, + 174, + 238, + 4, + 179, + 181, + 62, + 32, + 231, + 217, + 121, + 131, + 119, + 90, + 7, + 31, + 99, + 223, + 229, + 42, + 218, + 151, + 8, + 142, + 118, + 248, + 168, + 55, + 187, + 162, + 191, + 13, + 108, + 1, + 0, + 1, + 88, + 32, + 229, + 59, + 5, + 24, + 58, + 205, + 51, + 238, + 131, + 119, + 172, + 96, + 23, + 160, + 19, + 234, + 17, + 22, + 82, + 186, + 237, + 137, + 69, + 216, + 77, + 128, + 200, + 203, + 194, + 160, + 98, + 233, + 165, + 100, + 107, + 105, + 110, + 100, + 108, + 100, + 111, + 99, + 117, + 109, + 101, + 110, + 116, + 46, + 112, + 117, + 116, + 101, + 97, + 102, + 116, + 101, + 114, + 128, + 101, + 103, + 114, + 111, + 117, + 112, + 246, + 102, + 100, + 111, + 109, + 97, + 105, + 110, + 108, + 105, + 100, + 46, + 101, + 118, + 101, + 110, + 116, + 115, + 46, + 118, + 49, + 104, + 100, + 111, + 99, + 117, + 109, + 101, + 110, + 116, + 163, + 100, + 115, + 105, + 122, + 101, + 24, + 25, + 103, + 99, + 111, + 110, + 116, + 101, + 110, + 116, + 88, + 32, + 18, + 58, + 182, + 5, + 218, + 145, + 230, + 183, + 186, + 232, + 19, + 86, + 166, + 252, + 143, + 238, + 40, + 108, + 205, + 72, + 225, + 66, + 72, + 75, + 153, + 29, + 252, + 77, + 11, + 78, + 112, + 116, + 106, + 109, + 101, + 100, + 105, + 97, + 95, + 116, + 121, + 112, + 101, + 106, + 116, + 101, + 120, + 116, + 47, + 112, + 108, + 97, + 105, + 110 + ] + }, + { + "hash": "616a09d224c6ddd1aaa559b025f3c16bbaa3d785957253206a3e4b0d38352277", + "signer": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c", + "signature": "d2734c4edc475ae59e4a0c1564d2d56c947a5745a11875a7a9024d92cc87d8a5ba60585efb192b968346b5ec659f825d8cffc778a1b610e8407eaa7b5dc1ef00", + "blob_refs": [], + "bytes": [ + 134, + 1, + 88, + 32, + 234, + 74, + 108, + 99, + 226, + 156, + 82, + 10, + 190, + 245, + 80, + 123, + 19, + 46, + 197, + 249, + 149, + 71, + 118, + 174, + 190, + 190, + 123, + 146, + 66, + 30, + 234, + 105, + 20, + 70, + 210, + 44, + 88, + 64, + 210, + 115, + 76, + 78, + 220, + 71, + 90, + 229, + 158, + 74, + 12, + 21, + 100, + 210, + 213, + 108, + 148, + 122, + 87, + 69, + 161, + 24, + 117, + 167, + 169, + 2, + 77, + 146, + 204, + 135, + 216, + 165, + 186, + 96, + 88, + 94, + 251, + 25, + 43, + 150, + 131, + 70, + 181, + 236, + 101, + 159, + 130, + 93, + 140, + 255, + 199, + 120, + 161, + 182, + 16, + 232, + 64, + 126, + 170, + 123, + 93, + 193, + 239, + 0, + 0, + 0, + 164, + 100, + 107, + 105, + 110, + 100, + 103, + 109, + 101, + 115, + 115, + 97, + 103, + 101, + 101, + 97, + 102, + 116, + 101, + 114, + 128, + 101, + 103, + 114, + 111, + 117, + 112, + 246, + 102, + 100, + 111, + 109, + 97, + 105, + 110, + 108, + 105, + 100, + 46, + 101, + 118, + 101, + 110, + 116, + 115, + 46, + 118, + 49 + ] + } + ], + "blobs": [ + { + "hash": "747ad0246b0f6d6b8f3bca9f7b62fea5d16eada3bf50b13c4408dd6fa7478436", + "bytes": [ + 101, + 120, + 112, + 111, + 114, + 116, + 32, + 102, + 105, + 120, + 116, + 117, + 114, + 101, + 32, + 98, + 108, + 111, + 98, + 32, + 98, + 101, + 116, + 97, + 32, + 226, + 128, + 148, + 32, + 115, + 101, + 99, + 111, + 110, + 100, + 32, + 99, + 111, + 110, + 116, + 101, + 110, + 116 + ] + }, + { + "hash": "8b8e421a9547932f90af7f1dd385596349e374a225773638d3e41adb3c6235bc", + "bytes": [ + 101, + 120, + 112, + 111, + 114, + 116, + 32, + 102, + 105, + 120, + 116, + 117, + 114, + 101, + 32, + 98, + 108, + 111, + 98, + 32, + 97, + 108, + 112, + 104, + 97 + ] + } + ], + "object_count": 4, + "blob_count": 2, + "objects_digest": "ecc676582be3ed74101ac5ce68b8a743a46c7cd59c2a8cbbd5f73be409536808" +} diff --git a/pkgs/id/src/hosted_binding.rs b/pkgs/id/src/hosted_binding.rs index 37465481c..8e0886c89 100644 --- a/pkgs/id/src/hosted_binding.rs +++ b/pkgs/id/src/hosted_binding.rs @@ -1873,7 +1873,13 @@ impl HostedBindingService { /// Verify the key signature from the record's own stored transcript /// (§1.2): reconstruct the signed message from `challenge_id`, `sub`, /// `iroh_id`, `nonce`, and `expires_at` with no hosted-service access. - /// Returns `false` on any malformed field or mismatch. + /// The transcript names the key that performed the binding ceremony; + /// after a rebind that is a superseded key, so the transcript's key + /// must be the record's current key or one of its `history` keys — + /// the chain steps themselves are backed separately (§4.4 records, + /// checked by the caller). The record's current shape, current key + /// included, is covered by the service attestation, not by this + /// signature. Returns `false` on any malformed field or mismatch. #[must_use] pub fn verify_key_signature(record: &BindingRecord) -> bool { let transcript = &record.challenge_transcript; @@ -1891,7 +1897,11 @@ impl HostedBindingService { }; if transcript.challenge_id != record.challenge_id || transcript.sub != record.sub - || transcript.iroh_id != record.iroh_id + || (transcript.iroh_id != record.iroh_id + && !record + .history + .iter() + .any(|entry| entry.iroh_id == transcript.iroh_id)) { return false; } diff --git a/pkgs/id/src/hosted_export.rs b/pkgs/id/src/hosted_export.rs index 381e3150a..b3f718d6f 100644 --- a/pkgs/id/src/hosted_export.rs +++ b/pkgs/id/src/hosted_export.rs @@ -13,9 +13,12 @@ //! ## What is here //! //! - [`ExportObject`] / [`ExportBlob`]: self-authenticating content. -//! An object's hash is SHA-256 of its bytes and its signature is the -//! producing key's signature over that hash; a blob's hash is -//! SHA-256 of its bytes. Objects carry the blob hashes they cite. +//! An object's bytes are a stored signed envelope (a p2panda +//! header, the graph's native object form) carried verbatim; its +//! hash is SHA-256 of those bytes and its signature is the +//! envelope's own signature, over the canonical header encoding, +//! by the envelope's author. A blob's hash is SHA-256 of its +//! bytes. Objects carry the blob hashes they cite. //! - [`ExportManifest`]: `{export_id, binding_id, iroh_id, created_at, //! object_count, blob_count, sha256 of the concatenated object //! hashes}` (§6.1 item 4), signed by the user's Iroh root key when @@ -28,15 +31,22 @@ //! ingested. Every refusal is a typed [`ExportError`] naming the //! rule that failed; a partial or tampered export imports nothing. //! -//! ## What is not here +//! ## Production (slice 4b, #13157) //! -//! The enumeration of a live per-user store (the slice-3 DO scaffold) -//! and R2 blob fetching: `build_export` takes the object/blob sets as -//! inputs, so the DO/R2 wiring is a follow-on that feeds it. Ingest -//! itself (§6.2 step 4) lives in [`crate::hosted_ingest`], downstream -//! of a verified import. - -use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +//! The enumeration of a live per-user store and R2 blob fetching +//! live in the hosted data plane: `hosted-worker/src/export.ts` +//! enumerates the DO's applied events and fetches the blobs they +//! cite, and the DO's `GET /v1/bridge/export` route serves the sets +//! in the wire shape of these types for [`build_export`] to +//! assemble. [`ExportObject::from_envelope`] is the same mapping on +//! this side. The object-model mapping the wiring settles — +//! envelope bytes verbatim, SHA-256 as the export-layer digest, +//! the envelope's own signature as the object's signature, blob +//! citations resolved by content from BLAKE3 to SHA-256 — is +//! recorded in the spec as §6.3. Ingest itself (§6.2 step 4) lives +//! in [`crate::hosted_ingest`], downstream of a verified import. + +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -89,39 +99,75 @@ fn verify_hex_signature(public_key_hex: &str, message: &[u8], signature_hex: &st } /// One signed graph object in an export (§6.1 item 1): self- -/// authenticating by construction — `hash` is SHA-256 of `bytes` and -/// `signature` is `signer`'s signature over the hash bytes. +/// authenticating by construction. `bytes` is the stored signed +/// envelope verbatim (never re-encoded, never re-signed), `hash` +/// is SHA-256 of `bytes`, and `signature` is the envelope's own +/// signature over the canonical header encoding, by `signer`, the +/// envelope's author (§6.3). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ExportObject { /// SHA-256 of `bytes`, hex. pub hash: String, /// The producing key (an Iroh root key in the binding chain), hex. pub signer: String, - /// Signature over the 32 hash bytes, hex. + /// The envelope's own signature, hex. pub signature: String, - /// Hashes of the blobs this object cites (§6.2 step 3), hex. + /// Hashes of the blobs this object cites (§6.2 step 3), hex: + /// SHA-256 names, resolved from the envelope's BLAKE3 content + /// citations by content (§6.3). pub blob_refs: Vec, - /// The object bytes. + /// The object bytes: the stored envelope, verbatim. pub bytes: Vec, } impl ExportObject { - /// Build and sign an object from its bytes. - #[must_use] - pub fn new(signing_key: &SigningKey, bytes: Vec, blob_refs: Vec) -> Self { - let hash = sha256_hex(&bytes); - let hash_bytes = hex_decode(&hash, 32).unwrap_or_default(); - let signature = signing_key.sign(&hash_bytes).to_bytes(); - Self { - hash, - signer: hex_encode(&signing_key.verifying_key().to_bytes()), - signature: hex_encode(&signature), + /// Map a stored envelope to its export object (§6.3). The + /// envelope is decoded exactly as [`crate::chain::decode`] + /// does, which verifies its signature; the author and signature + /// are read from the envelope itself — nothing is re-signed, + /// and a stored form that does not decode is refused rather + /// than carried. + /// + /// `blob_refs` are the object's citations already resolved to + /// SHA-256 blob names by content (see + /// [`cited_content_hashes`]); resolving them needs the store's + /// blobs, so it is the producer's step, not this mapping's. + /// + /// # Errors + /// + /// [`ExportError::ObjectSignatureInvalid`] when the bytes are + /// not a verifiable signed envelope. + pub fn from_envelope(bytes: Vec, blob_refs: Vec) -> Result { + let event = + crate::chain::decode(&bytes).map_err(|_| ExportError::ObjectSignatureInvalid)?; + Ok(Self { + hash: sha256_hex(&bytes), + signer: hex_encode(event.header.verifying_key.as_bytes()), + signature: hex_encode(&event.header.signature.to_bytes()), blob_refs, bytes, - } + }) } } +/// The BLAKE3 content hashes an envelope cites: the `content` of +/// its document payload (`document.put`), and nothing else — in +/// the current `ChainExt` form one envelope cites at most one +/// content. The producer resolves each citation to the SHA-256 +/// name of the blob whose bytes hash (BLAKE3) to it (§6.3). +/// +/// # Errors +/// +/// [`ExportError::ObjectSignatureInvalid`] when the bytes are not +/// a verifiable signed envelope. +pub fn cited_content_hashes(bytes: &[u8]) -> Result, ExportError> { + let event = crate::chain::decode(bytes).map_err(|_| ExportError::ObjectSignatureInvalid)?; + Ok(match &event.header.extensions.document { + Some(document) => vec![document.content.to_hex()], + None => Vec::new(), + }) +} + /// One blob in an export (§6.1 item 2), carried by hash: `hash` is /// SHA-256 of `bytes`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -533,11 +579,17 @@ pub fn verify_import( if sha256_hex(&object.bytes) != object.hash { return Err(ExportError::ObjectHashMismatch); } - let Some(hash_bytes) = hex_decode(&object.hash, 32) else { - return Err(ExportError::ObjectHashMismatch); - }; - if !chain_keys.contains(&object.signer.as_str()) - || !verify_hex_signature(&object.signer, &hash_bytes, &object.signature) + // The object's signature verifies in the object's own + // scheme (§6.3): decoding the envelope as chain.rs does + // verifies its signature over the canonical header + // encoding; the decoded author must be the named signer, a + // binding-chain key, and the decoded signature must be the + // carried one. + let event = + crate::chain::decode(&object.bytes).map_err(|_| ExportError::ObjectSignatureInvalid)?; + if hex_encode(event.header.verifying_key.as_bytes()) != object.signer + || !chain_keys.contains(&object.signer.as_str()) + || hex_encode(&event.header.signature.to_bytes()) != object.signature { return Err(ExportError::ObjectSignatureInvalid); } @@ -597,15 +649,63 @@ mod tests { .unwrap() } + fn panda_key(key: &SigningKey) -> p2panda_core::SigningKey { + p2panda_core::SigningKey::from_bytes(&key.to_bytes()) + } + + fn ext(kind: &str, document: Option) -> crate::chain::ChainExt { + crate::chain::ChainExt { + kind: kind.to_owned(), + group: None, + after: Vec::new(), + tag: None, + document, + removes: None, + note: None, + link: None, + checkpoint: None, + rotation: None, + chat: None, + anchor: None, + } + } + + /// A signed envelope authored by `key`, in the form the store + /// holds it. + fn envelope( + key: &SigningKey, + seq: u32, + backlink: Option, + ext: crate::chain::ChainExt, + ) -> crate::chain::Event { + crate::chain::sign(&panda_key(key), seq, backlink, None, ext).unwrap() + } + + fn message_object(key: &SigningKey) -> ExportObject { + let event = envelope(key, 0, None, ext("message", None)); + ExportObject::from_envelope(event.bytes, Vec::new()).unwrap() + } + + /// A `document.put` object citing `content`, with the citation + /// resolved to `blob`'s SHA-256 name as the producer resolves + /// it (§6.3): the envelope cites the content's BLAKE3, the + /// export names the blob by SHA-256. + fn document_object(key: &SigningKey, blob: &ExportBlob, content: &[u8]) -> ExportObject { + let document = crate::documents::DocumentRef::for_bytes("text/plain", content).unwrap(); + let event = envelope(key, 0, None, ext("document.put", Some(document))); + assert_eq!( + cited_content_hashes(&event.bytes).unwrap(), + vec![p2panda_core::Hash::digest(content).to_hex()] + ); + ExportObject::from_envelope(event.bytes, vec![blob.hash.clone()]).unwrap() + } + fn sample_export(cse: Option) -> (HostedBindingService, HostedExport) { let mut svc = service(); let binding = bind(&mut svc, 21, cse); - let blob = ExportBlob::new(b"blob payload".to_vec()); - let object = ExportObject::new( - &root_key(21), - b"object payload".to_vec(), - vec![blob.hash.clone()], - ); + let content = b"blob payload"; + let blob = ExportBlob::new(content.to_vec()); + let object = document_object(&root_key(21), &blob, content); let export = build_export( &svc, &binding, @@ -661,6 +761,18 @@ mod tests { ); } + #[test] + fn forged_object_signature_is_refused() { + // A valid envelope whose carried signature field names a + // different signature: the field is not decorative (§6.3). + let (_svc, mut export) = sample_export(None); + export.objects[0].signature = hex_encode(&[7u8; 64]); + assert_eq!( + verify_import(&export, false), + Err(ExportError::ObjectSignatureInvalid) + ); + } + #[test] fn substituted_blob_is_refused() { // Object signatures and the objects digest do not cover blob @@ -696,7 +808,7 @@ mod tests { fn unkeyed_export_needs_operator_confirmation() { let mut svc = service(); let binding = bind(&mut svc, 21, None); - let object = ExportObject::new(&root_key(21), b"object".to_vec(), Vec::new()); + let object = message_object(&root_key(21)); let export = build_export( &svc, &binding, @@ -745,7 +857,7 @@ mod tests { fn object_from_a_key_outside_the_chain_is_refused() { let mut svc = service(); let binding = bind(&mut svc, 21, None); - let foreign = ExportObject::new(&root_key(77), b"foreign".to_vec(), Vec::new()); + let foreign = message_object(&root_key(77)); let export = build_export( &svc, &binding, @@ -761,4 +873,120 @@ mod tests { Err(ExportError::ObjectSignatureInvalid) ); } + + #[test] + fn envelope_mapping_is_verbatim() { + // §6.3: the export object is the stored envelope — hash is + // SHA-256 of the envelope bytes, signer its author, + // signature the envelope's own; nothing re-signed. + let key = root_key(21); + let event = envelope(&key, 0, None, ext("message", None)); + let object = ExportObject::from_envelope(event.bytes.clone(), Vec::new()).unwrap(); + assert_eq!(object.bytes, event.bytes); + assert_eq!(object.hash, sha256_hex(&event.bytes)); + assert_eq!(object.signer, hex_encode(&key.verifying_key().to_bytes())); + assert_eq!( + object.signature, + hex_encode(&event.header.signature.to_bytes()) + ); + assert!(cited_content_hashes(&event.bytes).unwrap().is_empty()); + // Bytes that are not a verifiable envelope are refused. + assert_eq!( + ExportObject::from_envelope(b"not an envelope".to_vec(), Vec::new()), + Err(ExportError::ObjectSignatureInvalid) + ); + } + + #[test] + fn produced_sets_fixture_verifies() { + // The cross-language contract (slice 4b): the hosted-worker + // suite seeds a per-user DO from the seed-7 key and pins + // the produced sets to this fixture; here the same sets, + // assembled with a binding whose root key is that key, must + // pass verify_import with matching counts and digest. + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/hosted-worker/test/fixtures/hosted-export-sets.json" + ); + let text = std::fs::read_to_string(path).unwrap(); + let wire: serde_json::Value = serde_json::from_str(&text).unwrap(); + let objects: Vec = serde_json::from_value(wire["objects"].clone()).unwrap(); + let blobs: Vec = serde_json::from_value(wire["blobs"].clone()).unwrap(); + + let mut svc = service(); + let binding = bind(&mut svc, 7, None); + let export = build_export( + &svc, + &binding, + Vec::new(), + objects, + blobs, + Some(&root_key(7)), + "export-fixture", + CREATED, + ); + assert_eq!( + export.manifest.objects_digest, + wire["objects_digest"].as_str().unwrap() + ); + let verified = verify_import(&export, false).unwrap(); + assert_eq!( + verified.object_count, + wire["object_count"].as_u64().unwrap() + ); + assert_eq!(verified.blob_count, wire["blob_count"].as_u64().unwrap()); + assert_eq!(verified.object_count, 4); + assert_eq!(verified.blob_count, 2); + } + + #[test] + fn rebind_history_export_verifies() { + // A store with a rebind history: objects authored by the + // old root key and by the current one both verify, backed + // by the rebind record (§6.2 step 2, §4.4). + use crate::hosted_binding::{REBIND_VIA_DELAYED, RebindRecord}; + const T0: u64 = 1_700_000_000; + let mut svc = service(); + svc.set_now_override(Some(T0)); + let binding = bind(&mut svc, 21, None); + let new_key = root_key(22); + + let challenge = svc + .request_challenge(SUB, &new_key.verifying_key().to_bytes()) + .unwrap(); + let proof = new_key.sign(&HostedBindingService::canonical_transcript(&challenge)); + let (request, _) = svc + .request_delayed_rebind(SUB, &challenge.challenge_id, &proof.to_bytes()) + .unwrap(); + let probe = RebindRecord { + rebind_id: String::new(), + binding_id: binding.binding_id.clone(), + old_iroh_id: binding.iroh_id.clone(), + new_iroh_id: hex_encode(&new_key.verifying_key().to_bytes()), + effective_at: String::new(), + via: REBIND_VIA_DELAYED.to_owned(), + service_signature: String::new(), + new_key_countersignature: String::new(), + }; + let counter = new_key.sign(&probe.countersign_bytes()).to_bytes(); + svc.set_now_override(Some(T0 + crate::hosted_binding::REBIND_WAITING_PERIOD_SECS)); + let (updated, record) = svc.effect_due_rebind(&request.rebind_id, &counter).unwrap(); + assert_eq!(updated.history.len(), 1); + + let objects = vec![message_object(&root_key(21)), message_object(&new_key)]; + let export = build_export( + &svc, + &updated, + vec![record], + objects, + Vec::new(), + Some(&new_key), + "export-rebind", + CREATED, + ); + let verified = verify_import(&export, false).unwrap(); + assert_eq!(verified.object_count, 2); + assert_eq!(verified.blob_count, 0); + assert_eq!(verified.iroh_id, updated.iroh_id); + } } diff --git a/pkgs/id/src/hosted_ingest.rs b/pkgs/id/src/hosted_ingest.rs index 0927a2d72..3c04fd0c7 100644 --- a/pkgs/id/src/hosted_ingest.rs +++ b/pkgs/id/src/hosted_ingest.rs @@ -319,7 +319,10 @@ mod tests { use crate::chain::{self, ChainExt, Event}; use crate::hosted_binding::HostedBindingService; - use crate::hosted_export::{build_export, verify_import}; + use sha2::{Digest, Sha256}; + + use crate::hosted_binding::hex_encode; + use crate::hosted_export::{ExportError, build_export, verify_import}; use id_core::waiting::WaitingLimits; use id_store::documents::{DOCUMENT_KIND, DocumentRef}; @@ -395,7 +398,7 @@ mod tests { (Some(blob), DOCUMENT_KIND) => vec![blob.hash.clone()], _ => Vec::new(), }; - ExportObject::new(&dalek_key(SEED), event.bytes.clone(), refs) + ExportObject::from_envelope(event.bytes.clone(), refs).unwrap() }) .collect(); build_export( @@ -472,27 +475,35 @@ mod tests { assert_eq!(second.already_present(), 4); } - #[tokio::test] - async fn an_object_that_is_not_an_event_is_refused_and_named() { - // A wrapper-valid object whose bytes are not an event passes - // §6.2 verification (the export layer authenticates bytes, - // not eventhood) and is refused by the store's normal rules. + #[test] + fn an_object_that_is_not_an_event_is_refused_at_verification() { + // Section 6.3 (slice 4b production, #13157): an export object + // IS its signed envelope, so bytes that are not an event fail + // section 6.2 verification itself. The refusal this test used + // to meet at ingest, under the store's malformed rule, now + // happens one layer earlier, before anything is offered to + // a store. let mut service = HostedBindingService::with_seed("hosted.example", [9u8; 32]); service.signup_account(SUB, None, "free").unwrap(); let binding = service .complete_browser_ceremony(SUB, &dalek_key(SEED), None) .unwrap(); let (events, content) = source_chain(); - let good = ExportObject::new(&dalek_key(SEED), events[0].bytes.clone(), Vec::new()); - let middle = ExportObject::new(&dalek_key(SEED), events[1].bytes.clone(), Vec::new()); - let bogus = ExportObject::new(&dalek_key(SEED), b"not an event".to_vec(), Vec::new()); - let bogus_hash = bogus.hash.clone(); + let good = ExportObject::from_envelope(events[0].bytes.clone(), Vec::new()).unwrap(); + let middle = ExportObject::from_envelope(events[1].bytes.clone(), Vec::new()).unwrap(); let blob = ExportBlob::new(content.clone()); - let citing = ExportObject::new( - &dalek_key(SEED), - events[2].bytes.clone(), - vec![blob.hash.clone()], - ); + let citing = + ExportObject::from_envelope(events[2].bytes.clone(), vec![blob.hash.clone()]).unwrap(); + // Hand-built: `from_envelope` refuses these bytes by + // construction, so the raw struct is the only way to carry + // them - exactly what a hostile producer would send. + let bogus = ExportObject { + hash: hex_encode(&Sha256::digest(b"not an event")), + signer: hex_encode(&dalek_key(SEED).verifying_key().to_bytes()), + signature: hex_encode(&[0u8; 64]), + bytes: b"not an event".to_vec(), + blob_refs: Vec::new(), + }; let export = build_export( &service, &binding, @@ -503,28 +514,10 @@ mod tests { "export-1", CREATED, ); - let verified = verify_import(&export, false).unwrap(); - let (_dir, mut target) = open_store(); - let blobs = blob_store(); - let report = ingest_import(&mut target, &blobs, &export, &verified, 0) - .await - .unwrap(); - assert_eq!(report.refused(), 1, "report: {report:?}"); - let refused: Vec<&ObjectEntry> = report - .objects - .iter() - .filter(|entry| matches!(entry.outcome, EntryOutcome::Refused { .. })) - .collect(); - assert_eq!(refused.len(), 1); - assert_eq!(refused[0].hash, bogus_hash); - match &refused[0].outcome { - EntryOutcome::Refused { rule } => { - assert!(rule.starts_with("malformed"), "rule: {rule}"); - } - other => panic!("expected a refusal, got {other:?}"), - } - // The refusal did not block the other entries. - assert_eq!(report.applied(), 4); // 3 objects + 1 blob + assert_eq!( + verify_import(&export, false).unwrap_err(), + ExportError::ObjectSignatureInvalid + ); } #[tokio::test]