/** * Digital signatures over HTTP against the real fork (native runtime), * in whichever engine isolation the matrix selects (inline worker threads * or the supervised host process: CLOUDPDF_TEST_ISOLATION=host). The * engine-client suite covers the SDK surface; this one pins the wire: * the multipart prepare envelope, the JSON completion, the version * catalog and its immutable reads, the pending guard, and the replay. */ import { createHash } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterAll, beforeAll, describe, expect, test } from 'vitest'; import type { Kysely } from 'kysely'; import { buildDetachedCms, createTestSigner, profileFor } from '@embedpdf/core-signature'; import type { SignatureSubFilter } from '@embedpdf/engine-core/runtime'; import { SIGNATURE_POLICY_VERSION } from '@embedpdf/engine-core/runtime'; import { decodePrepared, encodeAnalysisToken, SignaturePreparedWireSchema, toBase64, } from '@embedpdf/engine-core/wire'; import { createSqliteDb, FsObjectStore, migrate, signDevToken, sqliteMigrations, StorageKeys, type AppBundle, type DbSchema, } from '../src/index'; import { buildAppForTesting } from '../src/app/buildApp'; import { createValidTestLicenseGate } from '../src/licensing/testing'; import { ENGINE, pinOf } from './_helpers/pins'; // What a signing service might hand over is built from the signature package's own parts. import { timestampTokenAttribute } from '../../../packages/core/signature/src/cms/attach'; import { parseCmsInternal } from '../../../packages/core/signature/src/cms/parse'; import { addUnsignedAttribute } from '../../../packages/core/signature/src/cms/splice'; import { signatureValueOf } from '../../../packages/core/signature/src/cms/verify-timestamp'; import { createTimestampAuthorityIdentity } from '../../../packages/core/signature/test/helpers/pki'; import { buildTestToken } from '../../../packages/core/signature/test/helpers/tokens'; const here = dirname(fileURLToPath(import.meta.url)); const fixturePath = resolve( here, '..', '..', '..', 'packages', 'engine', 'main', 'test', 'fixtures', 'unsigned_sigfield.pdf', ); const SECRET = 'signatures-native-secret'; const TENANT = 'tenant-sign-native'; const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); interface Fixture { bundle: AppBundle; db: Kysely; baseUrl: string; storageRoot: string; cacheRoot: string; } let fx: Fixture; beforeAll(async () => { const storageRoot = await mkdtemp(join(tmpdir(), 'sign-native-store-')); const cacheRoot = await mkdtemp(join(tmpdir(), 'sign-native-cache-')); const db = createSqliteDb({ path: ':memory:' }); await migrate(db, { source: { kind: 'inline', migrations: sqliteMigrations } }); const bundle = await buildAppForTesting({ licenseGate: createValidTestLicenseGate(), verifier: { mode: 'hs256', secret: SECRET }, // The built worker entry: worker threads (and the host process) load // plain ESM, and the native runtime lives behind it. workerEntry: new URL('../dist/runtime/worker-entry.js', import.meta.url), poolSize: 1, db, objectStore: new FsObjectStore({ root: storageRoot }), autoProvisionTenant: true, sweepIntervalMs: 0, cacheRoot, cacheMaxBytes: 4 * 1024 * 1024, }); const addr = await bundle.app.listen({ host: '127.0.0.1', port: 0 }); fx = { bundle, db, baseUrl: typeof addr === 'string' ? addr : `http://127.0.0.1:${addr}`, storageRoot, cacheRoot, }; }); afterAll(async () => { await fx.bundle.shutdown(); await fx.db.destroy(); await rm(fx.storageRoot, { recursive: true, force: true }); await rm(fx.cacheRoot, { recursive: true, force: true }); }); async function seed(docId: string): Promise<{ sha: string; size: number }> { const bytes = new Uint8Array(await readFile(fixturePath)); const sha = sha256(bytes); await new FsObjectStore({ root: fx.storageRoot }).put(StorageKeys.basePdf(TENANT, docId), bytes, { contentLength: bytes.byteLength, }); await fx.db .insertInto('tenants') .values({ id: TENANT, name: TENANT }) .onConflict((oc) => oc.column('id').doNothing()) .execute(); const now = Date.now(); await fx.db .insertInto('documents') .values({ id: docId, tenant_id: TENANT, state: 'ready', base_sha: sha, storage_size_bytes: bytes.byteLength, metadata_json: null, idempotency_key: null, failure_reason: null, created_at: now, updated_at: now, created_by: null, }) .execute(); return { sha, size: bytes.byteLength }; } const token = (docId: string, layer: string) => signDevToken(SECRET, { sub: `user-${layer}`, tenant_id: TENANT, doc_id: docId, layer_name: layer, scope: ['*'], }); async function call( method: string, path: string, docId: string, layer: string, body?: BodyInit, contentType?: string, ): Promise { return fetch(`${fx.baseUrl}${path}`, { method, headers: { Authorization: `Bearer ${token(docId, layer)}`, ...(contentType ? { 'Content-Type': contentType } : {}), }, ...(body !== undefined ? { body } : {}), }); } const json = async (res: Response, status = 200): Promise => { const text = await res.text(); expect(res.status, text).toBe(status); return JSON.parse(text) as T; }; function prepareForm(body: unknown): FormData { const form = new FormData(); form.append('body', JSON.stringify(body)); return form; } describe('digital signatures over the wire (native runtime)', () => { test("prepare (multipart) → complete (JSON) makes the layer's own version; the catalog and immutable reads follow", async () => { const docId = 'doc-sign-native-1'; const seeded = await seed(docId); const layer = `/v1/docs/${docId}/layers/alice`; const signer = await createTestSigner({ commonName: 'Wire Signer' }); // A fill first: the edit and the signature share one revision. await json( await call( 'POST', `${layer}/form/fields/${encodeURIComponent('fqn:group.total')}/value`, docId, 'alice', JSON.stringify({ value: { value: 'wire' } }), 'application/json', ), ); const before = await json<{ signatures: Array<{ fieldName: string; signed: boolean }>; revisions: unknown[]; }>(await call('GET', `${layer}/signatures`, docId, 'alice')); expect(before.signatures).toEqual([ expect.objectContaining({ fieldName: 'sig', signed: false }), ]); const preparedRes = await call( 'POST', `${layer}/signatures/prepare`, docId, 'alice', prepareForm({ field: { kind: 'fqn', name: 'sig' }, certify: { permission: 2 }, signer: { name: 'Wire' }, }), ); expect(preparedRes.headers.get('cache-control')).toContain('no-store'); const preparedWire = SignaturePreparedWireSchema.parse(await json(preparedRes)); const prepared = decodePrepared(preparedWire); expect(prepared.expectedVersion).toEqual({ baseSha256: seeded.sha, editsVersion: 2 }); expect(prepared.digest.byteLength).toBe(32); // Pending: the layer refuses writes with a conflict. const blocked = await call( 'POST', `${layer}/form/fields/${encodeURIComponent('fqn:group.total')}/value`, docId, 'alice', JSON.stringify({ value: { value: 'nope' } }), 'application/json', ); expect(blocked.status).toBe(409); expect(((await blocked.json()) as { error: { code: string } }).error.code).toBe( 'SigningPending', ); // The manifest already says so. const pendingManifest = await json<{ layerVersion: number; working: boolean; docVersion: number; }>(await call('GET', `${layer}/manifest`, docId, 'alice')); expect(pendingManifest).toMatchObject({ layerVersion: 2, working: true }); const cms = await buildDetachedCms({ digest: prepared.digest, hash: prepared.algorithm, profile: profileFor(prepared.subFilter as SignatureSubFilter), signer, }); // A stale fence is refused before any byte is touched. const stale = await call( 'POST', `${layer}/signatures/${prepared.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(cms), expectedVersion: { ...prepared.expectedVersion, editsVersion: 99 }, }), 'application/json', ); expect(stale.status).toBe(409); const completed = await json<{ status: string; version: { sha256: string; sizeBytes: number }; signature: { signed: boolean; coverage: string; docMdp: number; revisionIndex: number }; meta: { cacheDelta: null; affectedPages: unknown[] }; }>( await call( 'POST', `${layer}/signatures/${prepared.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(cms), expectedVersion: prepared.expectedVersion }), 'application/json', ), ); expect(completed.status).toBe('completed'); expect(completed.signature).toMatchObject({ signed: true, coverage: 'whole-revision', docMdp: 2, revisionIndex: 1, }); expect(completed.meta.cacheDelta).toBeNull(); expect(completed.meta.affectedPages.length).toBeGreaterThan(0); // The catalog and the head. const versions = await json<{ baseSha256: string; versions: Array<{ number: number; sha256: string; parentSha256: string | null; producer: string; signingId: string | null; }>; }>(await call('GET', `/v1/docs/${docId}/layers/alice/versions`, docId, 'alice')); // Alice's versions: the upload, then hers; her base is her new version. expect(versions.baseSha256).toBe(completed.version.sha256); expect(versions.versions).toEqual([ expect.objectContaining({ number: 1, sha256: seeded.sha, parentSha256: null, producer: 'upload', }), expect.objectContaining({ number: 2, sha256: completed.version.sha256, parentSha256: seeded.sha, producer: 'signature', signingId: prepared.signingId, }), ]); const head = await json<{ baseSha256: string; docVersion: number }>( await call('GET', `/v1/docs/${docId}/head`, docId, 'alice'), ); expect(head.baseSha256).toBe(seeded.sha); const layerHead = await json<{ baseSha256: string; sizeBytes: number }>( await call('GET', `${layer}/head`, docId, 'alice'), ); expect(layerHead).toMatchObject({ baseSha256: completed.version.sha256, sizeBytes: completed.version.sizeBytes, }); // Version reads: snapshot, contents, digest, download, revision prefix. The snapshot is // computed, so it is cached under the engine value its URL names. const vsigUrl = `/v1/docs/${docId}/layers/alice/versions/signatures/${completed.version.sha256}`; const vsig = await call('GET', `${vsigUrl}?engine=${ENGINE.signatures}`, docId, 'alice'); expect(vsig.headers.get('cache-control')).toContain('immutable'); expect(vsig.headers.get('embedpdf-engine')).toBeNull(); const vsnap = await json<{ revisions: Array<{ end: number }>; signatures: Array<{ fieldName: string; contentsSizeBytes: number }>; }>(vsig); expect(vsnap.revisions).toHaveLength(2); // Under no engine value, or under another, the answer is the same one, uncached, with the // current value beside it. for (const query of ['', '?engine=0ther']) { const other = await call('GET', `${vsigUrl}${query}`, docId, 'alice'); expect(await json(other), query).toEqual(vsnap); expect(other.headers.get('cache-control'), query).toContain('no-store'); expect(other.headers.get('cache-control'), query).not.toContain('immutable'); expect(other.headers.get('embedpdf-engine'), query).toBe(ENGINE.signatures); } const contents = await call( 'GET', `/v1/docs/${docId}/layers/alice/versions/signatures/${completed.version.sha256}/${encodeFieldKey('sig')}/contents`, docId, 'alice', ); expect(contents.status).toBe(200); expect(contents.headers.get('content-type')).toContain('application/pkcs7-signature'); expect(new Uint8Array(await contents.arrayBuffer())).toEqual(cms); const digest = await call( 'GET', `/v1/docs/${docId}/layers/alice/versions/signatures/${completed.version.sha256}/${encodeFieldKey('sig')}/digest/sha256`, docId, 'alice', ); expect(new Uint8Array(await digest.arrayBuffer())).toEqual(prepared.digest); const download = await call( 'GET', `/v1/docs/${docId}/layers/alice/versions/download/${completed.version.sha256}`, docId, 'alice', ); const published = new Uint8Array(await download.arrayBuffer()); expect(published.byteLength).toBe(completed.version.sizeBytes); expect(sha256(published)).toBe(completed.version.sha256); const rev0 = await call( 'GET', `/v1/docs/${docId}/layers/alice/versions/revisions/${completed.version.sha256}/0`, docId, 'alice', ); const rev0Bytes = new Uint8Array(await rev0.arrayBuffer()); expect(rev0Bytes.byteLength).toBe(seeded.size); expect(sha256(rev0Bytes)).toBe(seeded.sha); expect( ( await call( 'GET', `/v1/docs/${docId}/layers/alice/versions/revisions/${completed.version.sha256}/7`, docId, 'alice', ) ).status, ).toBe(404); expect( ( await call( 'GET', `/v1/docs/${docId}/layers/alice/versions/download/${'0'.repeat(64)}`, docId, 'alice', ) ).status, ).toBe(404); // The layer is clean over its new version; the fill survived in its bytes. const manifest = await json<{ baseSha256: string; baseSizeBytes: number; layerVersion: number; working: boolean; scopes: Record; }>(await call('GET', `${layer}/manifest`, docId, 'alice')); expect(manifest).toMatchObject({ baseSha256: completed.version.sha256, baseSizeBytes: completed.version.sizeBytes, layerVersion: 3, working: false, }); // Over a version that isn't the document's, every plane but actions is read at the layer. expect(manifest.scopes).toMatchObject({ content: 'layer', annotations: 'layer', forms: 'layer', layout: 'layer', actions: 'base', }); const form = await json<{ fields: Array<{ name: string; value: unknown }> }>( await call('GET', `${layer}/form`, docId, 'alice'), ); expect(JSON.stringify(form.fields.find((f) => f.name === 'group.total')?.value)).toContain( 'wire', ); // Replay with the same CMS: already-completed; a different CMS: refused; cancel: already-completed. const replay = await json<{ status: string; version: { sha256: string } }>( await call( 'POST', `${layer}/signatures/${prepared.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(cms), expectedVersion: prepared.expectedVersion }), 'application/json', ), ); expect(replay).toMatchObject({ status: 'already-completed', version: { sha256: completed.version.sha256 }, }); const other = await call( 'POST', `${layer}/signatures/${prepared.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(new Uint8Array([0x30, 3, 2, 1, 1])), expectedVersion: prepared.expectedVersion, }), 'application/json', ); expect(other.status).toBe(422); expect( await json<{ status: string }>( await call('DELETE', `${layer}/signatures/${prepared.signingId}`, docId, 'alice'), ), ).toEqual({ status: 'already-completed' }); // The audit trail carries the prepare and the completion (naming the // signing), so other sessions hear both. const audit = await fx.db .selectFrom('audit_log') .select(['kind', 'artifact_sha', 'payload_json']) .where('doc_id', '=', docId) .orderBy('id', 'desc') .limit(2) .execute(); expect(audit.map((row) => row.kind)).toEqual(['signature.complete', 'signature.prepare']); expect(audit[0]).toMatchObject({ artifact_sha: completed.version.sha256 }); expect(JSON.parse(audit[0]!.payload_json)).toMatchObject({ signingId: prepared.signingId }); }); test('analysis URLs name the engine value, a policy number is read past, and only settled verdicts are immutable', async () => { const docId = 'doc-sign-native-analysis'; await seed(docId); const layer = `/v1/docs/${docId}/layers/alice`; const signer = await createTestSigner({ commonName: 'Analysis Signer' }); const prepared = decodePrepared( SignaturePreparedWireSchema.parse( await json( await call( 'POST', `${layer}/signatures/prepare`, docId, 'alice', prepareForm({ field: { kind: 'fqn', name: 'sig' } }), ), ), ), ); const cms = await buildDetachedCms({ digest: prepared.digest, hash: prepared.algorithm, profile: profileFor(prepared.subFilter as SignatureSubFilter), signer, }); const completed = await json<{ version: { sha256: string } }>( await call( 'POST', `${layer}/signatures/${prepared.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(cms), expectedVersion: prepared.expectedVersion }), 'application/json', ), ); const sha = completed.version.sha256; const versionUrl = (q: string) => `/v1/docs/${docId}/layers/alice/versions/analysis/${sha}?${q}`; // With this server's engine value: a settled verdict, cached for a year. const ok = await call( 'GET', versionUrl(`since.signature=0&engine=${ENGINE.analysis}`), docId, 'alice', ); expect(ok.headers.get('cache-control')).toContain('immutable'); expect(ok.headers.get('embedpdf-engine')).toBeNull(); const analysis = await json<{ policyVersion: number; mode: string; verdict: string }>(ok); expect(analysis).toMatchObject({ policyVersion: SIGNATURE_POLICY_VERSION, mode: 'authoritative', verdict: 'unchanged', }); // Every other request gets the same verdict, uncached, with the current value beside it: // one that names no engine value, one that names another, and what a client of 3.0 to 3.2 // sends, a policy number, whichever number it is. for (const query of [ 'since.signature=0', 'since.signature=0&engine=0ther', `since.signature=0&policy=${SIGNATURE_POLICY_VERSION}`, `since.signature=0&policy=${SIGNATURE_POLICY_VERSION - 1}`, `since.signature=0&policy=${SIGNATURE_POLICY_VERSION + 1}`, ]) { const other = await call('GET', versionUrl(query), docId, 'alice'); expect(await json(other), query).toEqual(analysis); expect(other.headers.get('cache-control'), query).toContain('no-store'); expect(other.headers.get('cache-control'), query).not.toContain('immutable'); expect(other.headers.get('embedpdf-engine'), query).toBe(ENGINE.analysis); } // Exploratory: an answer to a what-if, not a verdict; never immutable. const exploratory = await call( 'GET', versionUrl(`since.signature=0&level=fill&engine=${ENGINE.analysis}`), docId, 'alice', ); expect((await json<{ mode: string }>(exploratory)).mode).toBe('exploratory'); expect(exploratory.headers.get('cache-control')).toContain('no-store'); // The layer twin: its token names the engine value, as every cached read's does, and no // policy. const manifest = await json<{ docVersion: number }>( await call('GET', `${layer}/manifest`, docId, 'alice'), ); const token = encodeAnalysisToken({ docVersion: manifest.docVersion, pin: pinOf('analysis'), since: { signatureIndex: 0 }, }); expect(token).not.toContain('policy'); const layerOk = await call('GET', `${layer}/signatures/analysis@${token}`, docId, 'alice'); expect(layerOk.headers.get('cache-control')).toContain('immutable'); const layerAnalysis = await json<{ policyVersion: number }>(layerOk); expect(layerAnalysis.policyVersion).toBe(SIGNATURE_POLICY_VERSION); // The token of a client of 3.0 to 3.2 also carries a policy number. It is read past: the // answer is the same one, cached under the engine value the token names. for (const policy of [ SIGNATURE_POLICY_VERSION - 1, SIGNATURE_POLICY_VERSION, SIGNATURE_POLICY_VERSION + 1, ]) { const older = await call( 'GET', `${layer}/signatures/analysis@${token.replace(',shape=', `,policy=${policy},shape=`)}`, docId, 'alice', ); expect(await json(older), `policy=${policy}`).toEqual(layerAnalysis); expect(older.headers.get('cache-control'), `policy=${policy}`).toContain('immutable'); } // A token that names another engine value is answered too, uncached. const layerOther = await call( 'GET', `${layer}/signatures/analysis@${token.replace(`engine=${ENGINE.analysis}`, 'engine=0ther')}`, docId, 'alice', ); expect(await json(layerOther)).toEqual(layerAnalysis); expect(layerOther.headers.get('cache-control')).not.toContain('immutable'); expect(layerOther.headers.get('embedpdf-engine')).toBe(ENGINE.analysis); }); test("cancel frees the layer; expiry is swept; another layer's signature moves only that layer", async () => { const docId = 'doc-sign-native-2'; const seeded = await seed(docId); const alice = `/v1/docs/${docId}/layers/alice`; const bob = `/v1/docs/${docId}/layers/bob`; // Bob edits first: his layer is over version 1. await json( await call( 'POST', `${bob}/form/fields/${encodeURIComponent('fqn:group.total')}/value`, docId, 'bob', JSON.stringify({ value: { value: 'bob' } }), 'application/json', ), ); const p1 = decodePrepared( SignaturePreparedWireSchema.parse( await json( await call( 'POST', `${alice}/signatures/prepare`, docId, 'alice', prepareForm({ field: { kind: 'fqn', name: 'sig' } }), ), ), ), ); expect( await json<{ status: string }>( await call('DELETE', `${alice}/signatures/${p1.signingId}`, docId, 'alice'), ), ).toEqual({ status: 'cancelled' }); expect( await json<{ status: string }>( await call('DELETE', `${alice}/signatures/${p1.signingId}`, docId, 'alice'), ), ).toEqual({ status: 'unknown' }); expect( ( await call( 'POST', `${alice}/signatures/${p1.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(new Uint8Array([0x30, 3, 2, 1, 1])), expectedVersion: p1.expectedVersion, }), 'application/json', ) ).status, ).toBe(404); // cancelled: NotFound (SigningExpired is only the time limit) // The tail is gone with the row. expect( await new FsObjectStore({ root: fx.storageRoot }).exists( StorageKeys.signingTail(TENANT, docId, p1.signingId), ), ).toBe(false); // Expiry: a prepared signing past its deadline is swept and the layer writable. const p2 = decodePrepared( SignaturePreparedWireSchema.parse( await json( await call( 'POST', `${alice}/signatures/prepare`, docId, 'alice', prepareForm({ field: { kind: 'fqn', name: 'sig' } }), ), ), ), ); await fx.db .updateTable('document_signings') .set({ expires_at: Date.now() - 1 }) .where('id', '=', p2.signingId) .execute(); expect(await fx.bundle.layerService!.expireSignings(Date.now())).toBe(1); expect( ( await fx.db .selectFrom('document_signings') .select('state') .where('id', '=', p2.signingId) .executeTakeFirst() )?.state, ).toBe('expired'); await json( await call( 'POST', `${alice}/form/fields/${encodeURIComponent('fqn:group.total')}/value`, docId, 'alice', JSON.stringify({ value: { value: 'after expiry' } }), 'application/json', ), ); // Sign for real on alice; bob stays over the upload. const signer = await createTestSigner(); const p3 = decodePrepared( SignaturePreparedWireSchema.parse( await json( await call( 'POST', `${alice}/signatures/prepare`, docId, 'alice', prepareForm({ field: { kind: 'fqn', name: 'sig' } }), ), ), ), ); const cms = await buildDetachedCms({ digest: p3.digest, hash: p3.algorithm, profile: profileFor(p3.subFilter as SignatureSubFilter), signer, }); const done = await json<{ status: string; version: { sha256: string } }>( await call( 'POST', `${alice}/signatures/${p3.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(cms), expectedVersion: p3.expectedVersion }), 'application/json', ), ); expect(done.status).toBe('completed'); // Alice's signature moved only her layer: Bob is still over the upload, // owning just the plane he wrote. const bobManifest = await json<{ baseSha256: string; scopes: Record }>( await call('GET', `${bob}/manifest`, docId, 'bob'), ); expect(bobManifest.baseSha256).toBe(seeded.sha); expect(bobManifest.scopes).toMatchObject({ content: 'base', forms: 'layer' }); // Bob signs too, over his own base, into a version of his own. const pBob = decodePrepared( SignaturePreparedWireSchema.parse( await json( await call( 'POST', `${bob}/signatures/prepare`, docId, 'bob', prepareForm({ field: { kind: 'fqn', name: 'sig' } }), ), ), ), ); expect(pBob.expectedVersion.baseSha256).toBe(seeded.sha); const bobCms = await buildDetachedCms({ digest: pBob.digest, hash: pBob.algorithm, profile: profileFor(pBob.subFilter as SignatureSubFilter), signer, }); const bobDone = await json<{ status: string; version: { sha256: string } }>( await call( 'POST', `${bob}/signatures/${pBob.signingId}/complete`, docId, 'bob', JSON.stringify({ cms: toBase64(bobCms), expectedVersion: pBob.expectedVersion }), 'application/json', ), ); expect(bobDone.status).toBe('completed'); expect(bobDone.version.sha256).not.toBe(done.version.sha256); const aliceManifest = await json<{ baseSha256: string }>( await call('GET', `${alice}/manifest`, docId, 'alice'), ); expect(aliceManifest.baseSha256).toBe(done.version.sha256); // Bob's reads work over his version: his own fill, never Alice's. const bobForm = await json<{ fields: Array<{ name: string; value: unknown }> }>( await call('GET', `${bob}/form`, docId, 'bob'), ); const bobTotal = JSON.stringify(bobForm.fields.find((f) => f.name === 'group.total')?.value); expect(bobTotal).toContain('bob'); expect(bobTotal).not.toContain('after expiry'); // A new layer starts on the upload: nobody's fill or signature. const carol = await json<{ baseSha256: string; scopes: Record; docVersion: number; }>(await call('GET', `/v1/docs/${docId}/layers/carol/manifest`, docId, 'carol')); expect(carol.baseSha256).toBe(seeded.sha); expect(new Set(Object.values(carol.scopes))).toEqual(new Set(['base'])); const carolForm = await json<{ fields: Array<{ name: string; value: unknown }> }>( await call('GET', `/v1/docs/${docId}/layers/carol/form`, docId, 'carol'), ); const carolTotal = JSON.stringify( carolForm.fields.find((f) => f.name === 'group.total')?.value, ); expect(carolTotal).not.toContain('bob'); expect(carolTotal).not.toContain('after expiry'); expect( ( await fx.db .selectFrom('documents') .select('base_sha') .where('id', '=', docId) .executeTakeFirst() )?.base_sha, ).toBe(seeded.sha); // Each layer downloads its own version: the signed bytes, nobody else's. const download = async (name: string, path: string) => sha256( new Uint8Array(await (await call('GET', `${path}/download`, docId, name)).arrayBuffer()), ); expect(await download('alice', alice)).toBe(done.version.sha256); expect(await download('bob', bob)).toBe(bobDone.version.sha256); // A layer reads only the upload and its own versions: Bob gets 404 for // Alice's version through his layer, and his token can't use hers. const aliceSha = done.version.sha256; expect((await call('GET', `${bob}/versions/download/${aliceSha}`, docId, 'bob')).status).toBe( 404, ); expect((await call('GET', `${bob}/versions/signatures/${aliceSha}`, docId, 'bob')).status).toBe( 404, ); expect((await call('GET', `${alice}/versions/download/${aliceSha}`, docId, 'bob')).status).toBe( 403, ); expect((await call('GET', `${bob}/versions/download/${seeded.sha}`, docId, 'bob')).status).toBe( 200, ); const bobVersions = await json<{ baseSha256: string; versions: Array<{ sha256: string }> }>( await call('GET', `${bob}/versions`, docId, 'bob'), ); expect(bobVersions.baseSha256).toBe(bobDone.version.sha256); expect(bobVersions.versions.map((v) => v.sha256)).toEqual([seeded.sha, bobDone.version.sha256]); // A tenant token reads any layer's versions, through that layer. const tenantToken = signDevToken(SECRET, { sub: 'admin', tenant_id: TENANT, scope: ['*'] }); const tenantRead = await fetch(`${fx.baseUrl}${alice}/versions/download/${aliceSha}`, { headers: { Authorization: `Bearer ${tenantToken}` }, }); expect(tenantRead.status).toBe(200); expect(sha256(new Uint8Array(await tenantRead.arrayBuffer()))).toBe(aliceSha); // Deleting Bob's layer deletes his version, row and file; the upload and // Alice's version stay. const bobKey = StorageKeys.layerVersionPdf(TENANT, docId, 'bob', bobDone.version.sha256); const aliceKey = StorageKeys.layerVersionPdf(TENANT, docId, 'alice', done.version.sha256); const store = new FsObjectStore({ root: fx.storageRoot }); expect(await store.exists(bobKey)).toBe(true); await fx.bundle.layerService!.deleteLayer(TENANT, { docId, layerName: 'bob' }); const left = await fx.db .selectFrom('base_versions') .select('sha256') .where('doc_id', '=', docId) .orderBy('number') .orderBy('sha256') .execute(); expect(left.map((v) => v.sha256).sort()).toEqual([seeded.sha, done.version.sha256].sort()); expect(await store.exists(bobKey)).toBe(false); expect(await store.exists(aliceKey)).toBe(true); expect(await store.exists(StorageKeys.basePdf(TENANT, docId))).toBe(true); }); test("a timestamp a CMS carries: one that provably isn't its own is refused, one that can't be checked completes", async () => { const signer = await createTestSigner({ commonName: 'Wire Signer' }); const authority = await createTimestampAuthorityIdentity('Wire Authority'); const sha256Bytes = async (bytes: Uint8Array) => new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); /** Prepare a signature on a fresh document, and complete it with what `carry` adds to the CMS. */ const completeWith = async ( docId: string, carry: (signatureValue: Uint8Array) => Promise, ): Promise => { await seed(docId); const layer = `/v1/docs/${docId}/layers/alice`; const prepared = decodePrepared( SignaturePreparedWireSchema.parse( await json( await call( 'POST', `${layer}/signatures/prepare`, docId, 'alice', prepareForm({ field: { kind: 'fqn', name: 'sig' }, contentsSizeBytes: 16384 }), ), ), ), ); const cms = await buildDetachedCms({ digest: prepared.digest, hash: prepared.algorithm, profile: profileFor(prepared.subFilter as SignatureSubFilter), signer, }); const token = await carry(signatureValueOf(parseCmsInternal(cms).signerInfo)); const carrying = addUnsignedAttribute(cms, timestampTokenAttribute(token)); return call( 'POST', `${layer}/signatures/${prepared.signingId}/complete`, docId, 'alice', JSON.stringify({ cms: toBase64(carrying), expectedVersion: prepared.expectedVersion }), 'application/json', ); }; // A token over other bytes than this signature's value: proof it belongs elsewhere. const refused = await completeWith('doc-sign-native-stamp-wrong', () => buildTestToken({ digest: new Uint8Array(32).fill(7), authority: authority.signer }), ); const refusal = await json<{ error: { code: string; message: string } }>(refused, 422); expect(refusal.error.code).toBe('SignatureRefused'); expect(refusal.error.message).toContain("the signature's timestamp does not belong to it"); // A token that stamps this signature but binds its certificate with a hash unknown here: a // signing service may bring one, and what can't be checked isn't proof of anything. const accepted = await completeWith('doc-sign-native-stamp-unknown', async (signatureValue) => buildTestToken({ digest: await sha256Bytes(signatureValue), authority: authority.signer, binding: { version: 2, hashOid: '2.16.840.1.101.3.4.2.8' }, }), ); expect(await json<{ status: string }>(accepted)).toMatchObject({ status: 'completed' }); }); }); /** Token-text (the attachment key encoding): base64 with `-` and `.`, unpadded. */ function encodeFieldKey(name: string): string { return Buffer.from(name, 'utf8') .toString('base64') .replace(/\+/g, '-') .replace(/\//g, '.') .replace(/=+$/, ''); }