|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 5 | + |
| 6 | +const { authorize, principal, provenance, safeKey, safeContributor, download, openPdf, destroyPdf, imageMetadata } = vi.hoisted(() => ({ |
| 7 | + authorize: vi.fn(), principal: vi.fn(), provenance: vi.fn(), safeKey: vi.fn(), |
| 8 | + safeContributor: vi.fn(), download: vi.fn(), openPdf: vi.fn(), destroyPdf: vi.fn(), imageMetadata: vi.fn(), |
| 9 | +})) |
| 10 | +vi.mock('@/lib/execution/payloads/materialization.server', () => ({ assertUserFileContentAccess: authorize })) |
| 11 | +vi.mock('@/lib/internal/principals/executor', () => ({ createExecutorPrincipalFromExecutionContext: principal })) |
| 12 | +vi.mock('@sim/auth/principal', () => ({ resolvePrincipalSubject: () => ({ kind: 'sim_user', userId: 'actor-1' }) })) |
| 13 | +vi.mock('@/lib/execution/model-input-provenance', () => ({ validateOpaqueModelInputProvenance: provenance })) |
| 14 | +vi.mock('@/lib/uploads/contexts/workspace/workspace-file-secret-provenance', () => ({ |
| 15 | + isModelSafeWorkspaceFileKey: safeKey, |
| 16 | + isOpaqueWorkspaceFileEgressSafe: safeContributor, |
| 17 | + MODEL_UNSAFE_WORKSPACE_FILE_ERROR_MESSAGE: 'Unsafe workspace file', |
| 18 | +})) |
| 19 | +vi.mock('@/lib/uploads/utils/file-utils.server', () => ({ downloadServableFileFromStorage: download })) |
| 20 | +vi.mock('@/lib/file-parsers/pdfjs-server', () => ({ openPdfDocument: openPdf })) |
| 21 | +vi.mock('sharp', () => ({ default: () => ({ metadata: imageMetadata }) })) |
| 22 | +vi.mock('@/lib/workspace-files/application/authorization', () => ({ WORKSPACE_FILES_DELEGATION_AUDIENCE: 'workspace-files' })) |
| 23 | + |
| 24 | +import { prepareDocumentSource, validateDocumentBytes } from '@/lib/internal/oci-document-understanding/document-input' |
| 25 | +import { type AnalysisInput, documentInputSchema } from '@/lib/internal/oci-document-understanding/schema' |
| 26 | +import type { InternalToolOperationCall } from '@/lib/internal/tool-operations/types' |
| 27 | + |
| 28 | +const file = { |
| 29 | + id: 'file-1', name: 'invoice.pdf', key: 'workspace/workspace-1/file-1', |
| 30 | + url: 'https://untrusted.example/ignored', size: 12, type: 'application/pdf', |
| 31 | +} |
| 32 | +const call: InternalToolOperationCall = { |
| 33 | + toolId: 'oci_document_understanding_analyze_document', requestId: 'request-1', headers: new Headers(), |
| 34 | + context: { workspaceId: 'workspace-1', workflowId: 'workflow-1', executionId: 'execution-1', userId: 'owner-not-actor' }, |
| 35 | +} |
| 36 | +function input(values: Record<string, unknown> = {}): AnalysisInput { |
| 37 | + const parsed = documentInputSchema.parse({ |
| 38 | + operation: 'analyze_document', credentialId: 'authorized', source: 'file', file, |
| 39 | + features: [{ featureType: 'TEXT_EXTRACTION' }], ...values, |
| 40 | + }) |
| 41 | + if (parsed.operation !== 'analyze_document' && parsed.operation !== 'create_processor_job') throw new Error('Expected analysis') |
| 42 | + return parsed |
| 43 | +} |
| 44 | + |
| 45 | +describe('authorized document inputs', () => { |
| 46 | + beforeEach(() => { |
| 47 | + vi.clearAllMocks() |
| 48 | + principal.mockResolvedValue({ kind: 'session', userId: 'actor-1', sessionId: 'session-1' }) |
| 49 | + provenance.mockReturnValue({ success: true }) |
| 50 | + authorize.mockResolvedValue(undefined) |
| 51 | + safeKey.mockResolvedValue(true) |
| 52 | + safeContributor.mockResolvedValue(true) |
| 53 | + download.mockResolvedValue({ buffer: Buffer.from('%PDF-synthetic') }) |
| 54 | + openPdf.mockResolvedValue({ numPages: 1, destroy: destroyPdf }) |
| 55 | + imageMetadata.mockResolvedValue({ format: 'png', width: 100, height: 100 }) |
| 56 | + }) |
| 57 | + |
| 58 | + it('authorizes the stored file with the acting principal and bounds the shared download', async () => { |
| 59 | + const result = await prepareDocumentSource(input(), call) |
| 60 | + expect(authorize).toHaveBeenCalledWith(file, expect.objectContaining({ userId: 'actor-1', workspaceId: 'workspace-1' })) |
| 61 | + expect(safeKey).toHaveBeenCalledWith(file.key, { workspaceId: 'workspace-1', actorUserId: 'actor-1' }) |
| 62 | + expect(download).toHaveBeenCalledWith(file, 'request-1', expect.anything(), expect.objectContaining({ maxBytes: 8_000_000, filePrincipal: expect.objectContaining({ userId: 'actor-1' }) })) |
| 63 | + expect(result).toEqual({ source: 'INLINE', data: Buffer.from('%PDF-synthetic').toString('base64') }) |
| 64 | + expect(destroyPdf).toHaveBeenCalledOnce() |
| 65 | + }) |
| 66 | + |
| 67 | + it('rejects opaque secret provenance before touching a file or Oracle object', async () => { |
| 68 | + provenance.mockReturnValue({ success: false, status: 400, error: 'Unsafe model input' }) |
| 69 | + await expect(prepareDocumentSource(input(), call)).rejects.toThrow('Unsafe model input') |
| 70 | + expect(authorize).not.toHaveBeenCalled() |
| 71 | + expect(download).not.toHaveBeenCalled() |
| 72 | + }) |
| 73 | + |
| 74 | + it.each(['authorization', 'provenance'])('denies %s failures before reading bytes', async (kind) => { |
| 75 | + if (kind === 'authorization') authorize.mockRejectedValue(new Error('private detail')) |
| 76 | + else safeKey.mockResolvedValue(false) |
| 77 | + await expect(prepareDocumentSource(input(), call)).rejects.toThrow(kind === 'authorization' ? 'File is not available' : 'Unsafe workspace file') |
| 78 | + expect(download).not.toHaveBeenCalled() |
| 79 | + }) |
| 80 | + |
| 81 | + it('rejects unsafe contributing files after authorized materialization', async () => { |
| 82 | + const contributor = { kind: 'workspace_file', fileId: 'contributor-1' } |
| 83 | + download.mockResolvedValue({ buffer: Buffer.from('%PDF-synthetic'), contributingFiles: [contributor] }) |
| 84 | + safeContributor.mockResolvedValue(false) |
| 85 | + await expect(prepareDocumentSource(input(), call)).rejects.toThrow('Unsafe workspace file') |
| 86 | + expect(safeContributor).toHaveBeenCalledWith('workspace-1', contributor) |
| 87 | + expect(openPdf).not.toHaveBeenCalled() |
| 88 | + }) |
| 89 | + |
| 90 | + it('uses Oracle namespace/bucket/object locations without treating them as Sim files', async () => { |
| 91 | + const objects = [{ namespaceName: 'namespace', bucketName: 'bucket', objectName: 'exact/a b.pdf', pageRange: ['1-3'] }] |
| 92 | + const sync = await prepareDocumentSource(input({ source: 'objectStorage', file: undefined, objects }), call) |
| 93 | + expect(sync).toEqual({ source: 'OBJECT_STORAGE', ...objects[0] }) |
| 94 | + const batch = await prepareDocumentSource(input({ |
| 95 | + operation: 'create_processor_job', source: 'objectStorage', file: undefined, objects, |
| 96 | + compartmentId: 'compartment-1', outputLocation: { namespaceName: 'namespace', bucketName: 'results', prefix: 'docs' }, |
| 97 | + }), call) |
| 98 | + expect(batch).toEqual({ sourceType: 'OBJECT_STORAGE_LOCATIONS', objectLocations: objects }) |
| 99 | + expect(provenance).toHaveBeenCalledTimes(2) |
| 100 | + expect(download).not.toHaveBeenCalled() |
| 101 | + expect(authorize).not.toHaveBeenCalled() |
| 102 | + }) |
| 103 | + |
| 104 | + it('rejects URL-only and inline-base64 inputs at the boundary', () => { |
| 105 | + expect(() => input({ file: { url: 'https://example.com/private.pdf' } })).toThrow() |
| 106 | + expect(() => input({ file: { ...file, base64: 'raw-document' } })).toThrow() |
| 107 | + expect(() => input({ file: { ...file, providerFileId: 'file-external' } })).toThrow() |
| 108 | + }) |
| 109 | + |
| 110 | + it('enforces actual byte and page limits rather than trusting file metadata', async () => { |
| 111 | + await expect(validateDocumentBytes(Buffer.alloc(8_000_001))).rejects.toThrow('8,000,000') |
| 112 | + openPdf.mockResolvedValue({ numPages: 6, destroy: destroyPdf }) |
| 113 | + await expect(validateDocumentBytes(Buffer.from('%PDF-synthetic'))).rejects.toThrow('five pages') |
| 114 | + expect(destroyPdf).toHaveBeenCalledOnce() |
| 115 | + imageMetadata.mockResolvedValue({ format: 'tiff', pages: 6, width: 100, height: 100 }) |
| 116 | + await expect(validateDocumentBytes(Buffer.from('synthetic TIFF'))).rejects.toThrow('five pages') |
| 117 | + imageMetadata.mockResolvedValue({ format: 'png', width: 10001, height: 100 }) |
| 118 | + await expect(validateDocumentBytes(Buffer.from('synthetic PNG'))).rejects.toThrow('pixels') |
| 119 | + imageMetadata.mockResolvedValue({ format: 'webp', width: 100, height: 100 }) |
| 120 | + await expect(validateDocumentBytes(Buffer.from('synthetic WebP'))).rejects.toThrow('Only JPEG') |
| 121 | + }) |
| 122 | +}) |
0 commit comments