Files
0pt/tests/document-workbench/doc0-upload-client.test.ts
T
admin 4d56a1dd62
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 5s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 6s
CI (SIAX Cloud) / security (push) Successful in 19s
Security Scan (SIAX Cloud) / security (push) Successful in 19s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 22s
CI (SIAX Cloud) / security (pull_request) Successful in 25s
CI (SIAX Cloud) / quality (push) Successful in 51s
CI (SIAX Cloud) / integration (pull_request) Successful in 51s
CI (SIAX Cloud) / quality (pull_request) Successful in 59s
fix: reconcile uncertain document uploads
2026-11-02 02:17:55 +01:00

107 lines
4.8 KiB
TypeScript

import { createHash } from 'node:crypto';
import { describe, expect, it, vi } from 'vitest';
import { Doc0UploadClient, Doc0UploadOutcomeUnknownError } from '../../src/document-workbench/doc0-upload-client';
const bytes = new TextEncoder().encode('source bytes');
const input = {
tenantId: 'tenant-a',
projectId: 'project-a',
actorId: 'user-a',
requestId: 'req-a',
idempotencyKey: 'idem-a',
filename: 'test.txt',
mimeType: 'text/plain',
classification: 'confidential' as const,
bytes,
};
const receipt = {
document: { documentId: 'doc-a', tenantId: 'tenant-a', projectId: 'project-a', currentVersionId: 'v1' },
currentVersion: {
versionId: 'v1',
tenantId: 'tenant-a',
documentId: 'doc-a',
checksumSha256: createHash('sha256').update(bytes).digest('hex'),
sizeBytes: bytes.length,
pipelineStage: 'parsed',
},
};
describe('DOC0 upload client', () => {
it('sends real bytes and validates a tenant-scoped checksum-bound receipt', async () => {
const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
expect(new Headers(init?.headers).get('x-tenant-id')).toBe('tenant-a');
expect(new Headers(init?.headers).get('x-idempotency-key')).toBe('idem-a');
expect(init?.redirect).toBe('error');
const form = init?.body as FormData;
expect(await (form.get('file') as Blob).text()).toBe('source bytes');
return new Response(JSON.stringify(receipt), { status: 201 });
});
const client = new Doc0UploadClient({
baseUrl: 'https://doc0.test',
serviceToken: 'test',
maxBytes: 100,
fetchImpl: fetchImpl as typeof fetch,
});
expect(await client.upload(input)).toMatchObject({
documentId: 'doc-a',
versionId: 'v1',
pipelineStage: 'parsed',
});
});
it.each([
{ document: { ...receipt.document, tenantId: 'tenant-b' } },
{ document: { ...receipt.document, projectId: 'other' } },
{ currentVersion: { ...receipt.currentVersion, checksumSha256: 'bad' } },
{ currentVersion: { ...receipt.currentVersion, documentId: 'other' } },
])('rejects an incorrect receipt', async (change) => {
const client = new Doc0UploadClient({
baseUrl: 'https://doc0.test',
serviceToken: 'test',
maxBytes: 100,
fetchImpl: async () => new Response(JSON.stringify({ ...receipt, ...change }), { status: 201 }),
});
await expect(client.upload(input)).rejects.toThrow(/receipt/);
});
it('rejects empty or oversized inputs before calling DOC0', async () => {
const fetchImpl = vi.fn();
const client = new Doc0UploadClient({
baseUrl: 'https://doc0.test',
serviceToken: 'test',
maxBytes: 2,
fetchImpl,
});
await expect(client.upload(input)).rejects.toThrow(/Invalid/);
await expect(client.upload({ ...input, bytes: new Uint8Array() })).rejects.toThrow(/Invalid/);
expect(fetchImpl).not.toHaveBeenCalled();
});
it('rejects insecure endpoints, embedded credentials and invalid timeouts', () => {
const base = { serviceToken: 'test', maxBytes: 100 };
for (const baseUrl of ['http://doc0.test', 'https://doc0.test?token=x', 'file:///tmp/doc0', 'not a URL']) {
expect(() => new Doc0UploadClient({ ...base, baseUrl })).toThrow(/HTTPS/);
}
const credentialUrl = new URL('https://doc0.test');
credentialUrl.username = 'fixture';
credentialUrl.password = 'fixture';
expect(() => new Doc0UploadClient({ ...base, baseUrl: credentialUrl.toString() })).toThrow(/HTTPS/);
expect(() => new Doc0UploadClient({ ...base, baseUrl: 'https://doc0.test', timeoutMs: 0 })).toThrow(/limits/);
});
it('treats transport failure and non-success responses as unknown outcomes without retrying', async () => {
for (const response of [new Error('connection reset'), new Response('unavailable', { status: 503 })]) {
const fetchImpl = vi.fn(async () => { if (response instanceof Error) throw response; return response; });
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl });
await expect(client.upload(input)).rejects.toBeInstanceOf(Doc0UploadOutcomeUnknownError);
expect(fetchImpl).toHaveBeenCalledOnce();
}
});
it('rejects broken, malformed and oversized receipts as unknown outcomes', async () => {
const broken = new ReadableStream<Uint8Array>({ start(controller) { controller.error(new Error('broken')); } });
const locked = new Response('{}');
const lock = locked.body!.getReader();
for (const response of [new Response(broken), new Response('{'), new Response('x'.repeat(128 * 1024 + 1)), locked]) {
const client = new Doc0UploadClient({ baseUrl: 'https://doc0.test', serviceToken: 'test', maxBytes: 100, fetchImpl: async () => response });
await expect(client.upload(input)).rejects.toBeInstanceOf(Doc0UploadOutcomeUnknownError);
}
lock.releaseLock();
});
});