Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(storage): add file copy support (#1518)

Corentin Thomasset78ec1762f056
diff --git a/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.models.ts b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.models.ts
index 3500a58d..fb708474 100644
--- a/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.models.ts
+++ b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.models.ts
@@ -3,7 +3,12 @@ export function isAzureBlobAlreadyExistsError({
}: {
error: Error & { code?: unknown; statusCode?: unknown };
}) {
- return error.code === 'BlobAlreadyExists' || error.statusCode === 409;
+ return (
+ error.code === 'BlobAlreadyExists' ||
+ error.code === 'ConditionNotMet' ||
+ error.statusCode === 409 ||
+ error.statusCode === 412
+ );
}
export function isAzureBlobNotFoundError({
diff --git a/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
index 63ceb38b..56577ccc 100644
--- a/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
@@ -1,5 +1,5 @@
import { AzuriteContainer } from '@testcontainers/azurite';
-import { describe } from 'vitest';
+import { describe, expect, test } from 'vitest';
import { TEST_CONTAINER_IMAGES } from '../../../../../test/containers/images';
import { runDriverTestSuites } from '../drivers.test-suite';
import { azBlobStorageDriverFactory } from './az-blob.storage-driver';
@@ -31,5 +31,50 @@ describe('az-blob storage-driver', () => {
};
},
});
+
+ test('copies blob metadata and content headers', { timeout: 30_000 }, async () => {
+ const container = await new AzuriteContainer(TEST_CONTAINER_IMAGES.AZURITE)
+ .withInMemoryPersistence()
+ .start();
+
+ try {
+ const driver = azBlobStorageDriverFactory({
+ connectionString: container.getConnectionString(),
+ containerName: 'test-container',
+ accountName: '',
+ accountKey: '',
+ });
+ const client = driver.getClient();
+ await client.createContainer('test-container');
+ const containerClient = client.getContainerClient('test-container');
+ const source = containerClient.getBlockBlobClient('source.txt');
+ const destination = containerClient.getBlockBlobClient('copy.txt');
+ const metadata = { originalname: 'original.txt' };
+ await source.upload('original content', 16, {
+ metadata,
+ blobHTTPHeaders: {
+ blobContentType: 'text/plain',
+ blobContentDisposition: 'attachment; filename="original.txt"',
+ blobCacheControl: 'private, max-age=3600',
+ },
+ });
+
+ await driver.copyFile({
+ sourceStorageKey: 'source.txt',
+ destinationStorageKey: 'copy.txt',
+ });
+
+ expect(await destination.getProperties()).toMatchObject({
+ metadata,
+ contentType: 'text/plain',
+ contentDisposition: 'attachment; filename="original.txt"',
+ cacheControl: 'private, max-age=3600',
+ copyStatus: 'success',
+ });
+ expect((await destination.downloadToBuffer()).toString()).toEqual('original content');
+ } finally {
+ await container.stop();
+ }
+ });
});
});
diff --git a/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts
index a56e0f9a..87cb9354 100644
--- a/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts
@@ -45,6 +45,29 @@ export const azBlobStorageDriverFactory = ({
: error;
}
},
+ copyFile: async ({ sourceStorageKey, destinationStorageKey }) => {
+ const source = getBlockBlobClient({ storageKey: sourceStorageKey });
+ const destination = getBlockBlobClient({ storageKey: destinationStorageKey });
+
+ const [, error] = await safely(async () => {
+ const poller = await destination.beginCopyFromURL(source.url, {
+ conditions: { ifNoneMatch: '*' },
+ });
+ await poller.pollUntilDone();
+ });
+
+ if (error && isAzureBlobNotFoundError({ error })) {
+ throw createFileNotFoundError();
+ }
+
+ if (error && isAzureBlobAlreadyExistsError({ error })) {
+ throw createFileAlreadyExistsInStorageError();
+ }
+
+ if (error) {
+ throw error;
+ }
+ },
getFileStream: async ({ storageKey }) => {
const [response, error] = await safely(getBlockBlobClient({ storageKey }).download());
diff --git a/apps/papra-server/src/modules/storage/drivers/drivers.models.ts b/apps/papra-server/src/modules/storage/drivers/drivers.models.ts
index 0380d783..dfadb9b5 100644
--- a/apps/papra-server/src/modules/storage/drivers/drivers.models.ts
+++ b/apps/papra-server/src/modules/storage/drivers/drivers.models.ts
@@ -14,6 +14,7 @@ export type StorageDriver = {
fileStream: Readable;
}>;
+ copyFile: (args: { sourceStorageKey: string; destinationStorageKey: string }) => Promise<void>;
deleteFile: (args: { storageKey: string }) => Promise<void>;
fileExists: (args: { storageKey: string }) => Promise<boolean>;
};
@@ -27,6 +28,7 @@ export type EncryptionContext = {
export type StorageService = {
saveFile: ExtendReturnPromise<StorageDriver['saveFile'], EncryptionContext>;
getFileStream: ExtendNamedArguments<StorageDriver['getFileStream'], EncryptionContext>;
+ copyFile: StorageDriver['copyFile'];
deleteFile: StorageDriver['deleteFile'];
fileExists: StorageDriver['fileExists'];
};
diff --git a/apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts b/apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts
index 22b39ab5..30e3c70b 100644
--- a/apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts
+++ b/apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts
@@ -24,11 +24,51 @@ export function runDriverTestSuites({
timeout?: number;
retry?: number;
}) {
+ const createDriver = async () => {
+ const { driver, [Symbol.asyncDispose]: dispose } = await createDriverBase();
+ const storageKeys = new Set<string>();
+
+ return {
+ driver: {
+ ...driver,
+ saveFile: async (args) => {
+ storageKeys.add(args.storageKey);
+ await driver.saveFile(args);
+ },
+ copyFile: async (args) => {
+ storageKeys.add(args.destinationStorageKey);
+ await driver.copyFile(args);
+ },
+ } satisfies StorageDriver,
+ [Symbol.asyncDispose]: async () => {
+ try {
+ // Clean up even after failed assertions, including on shared live R2/B2 backends.
+ const results = await Promise.allSettled(
+ [...storageKeys].map(async (storageKey) => {
+ if (await driver.fileExists({ storageKey })) {
+ await driver.deleteFile({ storageKey });
+ }
+ }),
+ );
+ const errors = results
+ .filter((result) => result.status === 'rejected')
+ .map((result) => result.reason);
+
+ if (errors.length > 0) {
+ throw new AggregateError(errors, 'Failed to clean up storage test files');
+ }
+ } finally {
+ await dispose();
+ }
+ },
+ };
+ };
+
[
{
name: 'without encryption',
createStorageService: async () => {
- const { driver, [Symbol.asyncDispose]: dispose } = await createDriverBase();
+ const { driver, [Symbol.asyncDispose]: dispose } = await createDriver();
return {
storageServices: {
@@ -45,7 +85,7 @@ export function runDriverTestSuites({
{
name: 'with encryption',
createStorageService: async () => {
- const { driver, [Symbol.asyncDispose]: dispose } = await createDriverBase();
+ const { driver, [Symbol.asyncDispose]: dispose } = await createDriver();
return {
storageServices: wrapWithEncryptionLayer({
@@ -69,6 +109,167 @@ export function runDriverTestSuites({
},
].forEach(({ createStorageService, name }) => {
describe.concurrent(name, () => {
+ test(
+ 'copies to a nested key and remains readable after deleting the source',
+ { timeout, retry },
+ async () => {
+ await using resource = await createStorageService();
+ const { storageServices } = resource;
+ const prefix = `files/${randomUUID()}`;
+ const sourceStorageKey = `${prefix}/source.bin`;
+ const destinationStorageKey = `${prefix}/nested/destination.bin`;
+ const content = randomBytes(2_048);
+ const encryptionContext = await storageServices.saveFile({
+ storageKey: sourceStorageKey,
+ fileName: 'source.bin',
+ mimeType: 'application/octet-stream',
+ fileStream: createReadableStream({ content }),
+ });
+
+ await storageServices.copyFile({ sourceStorageKey, destinationStorageKey });
+
+ const { fileStream: destinationStream } = await storageServices.getFileStream({
+ storageKey: destinationStorageKey,
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToBuffer({ stream: destinationStream })).toEqual(
+ content,
+ );
+
+ const { fileStream: sourceStream } = await storageServices.getFileStream({
+ storageKey: sourceStorageKey,
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToBuffer({ stream: sourceStream })).toEqual(content);
+
+ await storageServices.deleteFile({ storageKey: sourceStorageKey });
+ expect(await storageServices.fileExists({ storageKey: sourceStorageKey })).toEqual(false);
+
+ const { fileStream } = await storageServices.getFileStream({
+ storageKey: destinationStorageKey,
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToBuffer({ stream: fileStream })).toEqual(content);
+ },
+ );
+
+ test(
+ 'rejects a missing copy source without creating a destination',
+ { timeout, retry },
+ async () => {
+ await using resource = await createStorageService();
+ const { storageServices } = resource;
+ const prefix = `files/${randomUUID()}`;
+ const sourceStorageKey = `${prefix}/missing.txt`;
+ const destinationStorageKey = `${prefix}/nested/destination.txt`;
+
+ await expect(
+ storageServices.copyFile({ sourceStorageKey, destinationStorageKey }),
+ ).rejects.toThrow(createFileNotFoundError());
+
+ expect(await storageServices.fileExists({ storageKey: sourceStorageKey })).toEqual(false);
+ expect(await storageServices.fileExists({ storageKey: destinationStorageKey })).toEqual(
+ false,
+ );
+ },
+ );
+
+ test(
+ 'rejects an existing copy destination and preserves both files',
+ { timeout, retry },
+ async () => {
+ await using resource = await createStorageService();
+ const { storageServices } = resource;
+ const prefix = `files/${randomUUID()}`;
+ const sourceStorageKey = `${prefix}/source.txt`;
+ const destinationStorageKey = `${prefix}/destination.txt`;
+ const sourceContext = await storageServices.saveFile({
+ storageKey: sourceStorageKey,
+ fileName: 'source.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'source content' }),
+ });
+ const destinationContext = await storageServices.saveFile({
+ storageKey: destinationStorageKey,
+ fileName: 'destination.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'destination content' }),
+ });
+
+ await expect(
+ storageServices.copyFile({ sourceStorageKey, destinationStorageKey }),
+ ).rejects.toThrow(createFileAlreadyExistsInStorageError());
+
+ const { fileStream: sourceStream } = await storageServices.getFileStream({
+ storageKey: sourceStorageKey,
+ ...sourceContext,
+ });
+ expect(await collectReadableStreamToString({ stream: sourceStream })).toEqual(
+ 'source content',
+ );
+ const { fileStream: destinationStream } = await storageServices.getFileStream({
+ storageKey: destinationStorageKey,
+ ...destinationContext,
+ });
+ expect(await collectReadableStreamToString({ stream: destinationStream })).toEqual(
+ 'destination content',
+ );
+ },
+ );
+
+ test('rejects copying an existing key onto itself', { timeout, retry }, async () => {
+ await using resource = await createStorageService();
+ const { storageServices } = resource;
+ const storageKey = `files/${randomUUID()}.txt`;
+ const encryptionContext = await storageServices.saveFile({
+ storageKey,
+ fileName: 'source.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'original content' }),
+ });
+
+ await expect(
+ storageServices.copyFile({
+ sourceStorageKey: storageKey,
+ destinationStorageKey: storageKey,
+ }),
+ ).rejects.toThrow(createFileAlreadyExistsInStorageError());
+
+ const { fileStream } = await storageServices.getFileStream({
+ storageKey,
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual(
+ 'original content',
+ );
+ });
+
+ test(
+ 'copies keys containing spaces, Unicode, and URL-reserved characters',
+ { timeout, retry },
+ async () => {
+ await using resource = await createStorageService();
+ const { storageServices } = resource;
+ const prefix = `files/${randomUUID()}`;
+ const sourceStorageKey = `${prefix}/dossier été/文档 + #%.txt`;
+ const destinationStorageKey = `${prefix}/copie été/資料 + #%.txt`;
+ const encryptionContext = await storageServices.saveFile({
+ storageKey: sourceStorageKey,
+ fileName: 'source.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'été 文档' }),
+ });
+
+ await storageServices.copyFile({ sourceStorageKey, destinationStorageKey });
+
+ const { fileStream } = await storageServices.getFileStream({
+ storageKey: destinationStorageKey,
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual('été 文档');
+ },
+ );
+
test(
'the driver should support uploading, retrieving and deleting files',
{ timeout, retry },
diff --git a/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts
index 3166eb14..cf8d2e06 100644
--- a/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts
@@ -52,6 +52,30 @@ export const fsStorageDriverFactory = ({ root }: FilesystemStorageDriverOptions)
});
});
},
+ copyFile: async ({ sourceStorageKey, destinationStorageKey }) => {
+ const { storagePath: sourcePath } = getStoragePath({ storageKey: sourceStorageKey });
+ const { storagePath: destinationPath } = getStoragePath({
+ storageKey: destinationStorageKey,
+ });
+
+ await ensureDirectoryExists({ path: dirname(destinationPath) });
+
+ const [, error] = await safely(
+ fs.promises.copyFile(sourcePath, destinationPath, fs.constants.COPYFILE_EXCL),
+ );
+
+ if (error && isFileNotFoundError({ error })) {
+ throw createFileNotFoundError();
+ }
+
+ if (error && isFileAlreadyExistsError({ error })) {
+ throw createFileAlreadyExistsInStorageError();
+ }
+
+ if (error) {
+ throw error;
+ }
+ },
getFileStream: async ({ storageKey }) => {
const { storagePath } = getStoragePath({ storageKey });
diff --git a/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts
index 3d12e4a9..fdce39f8 100644
--- a/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts
@@ -21,6 +21,31 @@ describe('memory storage-driver', () => {
},
});
+ test('copies metadata into an independent entry and content buffer', async () => {
+ const driver = inMemoryStorageDriverFactory();
+ await driver.saveFile({
+ storageKey: 'source',
+ fileName: 'original.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'original content' }),
+ });
+
+ await driver.copyFile({ sourceStorageKey: 'source', destinationStorageKey: 'destination' });
+
+ const source = driver._getStorage().get('source');
+ const destination = driver._getStorage().get('destination');
+ expect.assert(source);
+ expect.assert(destination);
+ expect(destination).toEqual(source);
+
+ destination.content.fill(0);
+ destination.fileName = 'changed.txt';
+ destination.mimeType = 'application/octet-stream';
+ expect(source.content.toString()).toEqual('original content');
+ expect(source.fileName).toEqual('original.txt');
+ expect(source.mimeType).toEqual('text/plain');
+ });
+
test('saves, retrieves and delete a file', async () => {
const inMemoryStorageDriver = inMemoryStorageDriverFactory();
diff --git a/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts
index abedc1a3..b1aad563 100644
--- a/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts
@@ -1,5 +1,5 @@
-import type { Buffer } from 'node:buffer';
import type { StorageDriver } from '../drivers.models';
+import { Buffer } from 'node:buffer';
import {
collectReadableStreamToBuffer,
createReadableStream,
@@ -29,6 +29,20 @@ export const inMemoryStorageDriverFactory = () => {
storage.set(storageKey, { content, mimeType, fileName });
},
+ copyFile: async ({ sourceStorageKey, destinationStorageKey }) => {
+ const source = storage.get(sourceStorageKey);
+
+ if (!source) {
+ throw createFileNotFoundError();
+ }
+
+ if (fileExists({ storageKey: destinationStorageKey })) {
+ throw createFileAlreadyExistsInStorageError();
+ }
+
+ storage.set(destinationStorageKey, { ...source, content: Buffer.from(source.content) });
+ },
+
getFileStream: async ({ storageKey }) => {
const fileEntry = storage.get(storageKey);
diff --git a/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts
index 3ee1b7ee..c14315ea 100644
--- a/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts
@@ -1,8 +1,46 @@
+import { Buffer } from 'node:buffer';
+import { randomBytes } from 'node:crypto';
+import { gzipSync } from 'node:zlib';
import { LocalstackContainer } from '@testcontainers/localstack';
-import { describe } from 'vitest';
+import { S3mini } from 's3mini';
+import { request } from 'undici';
+import { describe, expect, test } from 'vitest';
import { TEST_CONTAINER_IMAGES } from '../../../../../test/containers/images';
+import { IN_BYTES } from '../../../shared/units';
import { runDriverTestSuites } from '../drivers.test-suite';
-import { s3StorageDriverFactory } from './s3.storage-driver';
+import {
+ buildS3StorageDriver,
+ MULTIPART_MIN_PART_SIZE_IN_BYTES,
+ s3StorageDriverFactory,
+} from './s3.storage-driver';
+
+async function createDriver() {
+ const localstackContainer = await new LocalstackContainer(
+ TEST_CONTAINER_IMAGES.LOCALSTACK,
+ ).start();
+
+ try {
+ const driver = s3StorageDriverFactory({
+ accessKeyId: 'test',
+ secretAccessKey: 'test',
+ bucketName: 'test-bucket',
+ region: 'eu-central-1',
+ endpoint: localstackContainer.getConnectionUri(),
+ forcePathStyle: true,
+ });
+ await driver.getClient().createBucket();
+
+ return {
+ driver,
+ [Symbol.asyncDispose]: async () => {
+ await localstackContainer.stop();
+ },
+ };
+ } catch (error) {
+ await localstackContainer.stop();
+ throw error;
+ }
+}
describe('s3 storage-driver', () => {
describe('s3StorageDriver', () => {
@@ -10,28 +48,93 @@ describe('s3 storage-driver', () => {
// In the ci it take more than 30 seconds to pull images
timeout: 40_000,
retry: 3,
- createDriver: async () => {
- const localstackContainer = await new LocalstackContainer(
- TEST_CONTAINER_IMAGES.LOCALSTACK,
- ).start();
- const driver = s3StorageDriverFactory({
- accessKeyId: 'test',
- secretAccessKey: 'test',
- bucketName: 'test-bucket',
- region: 'eu-central-1',
- endpoint: localstackContainer.getConnectionUri(),
- forcePathStyle: true,
- });
+ createDriver,
+ });
+
+ test('copies content headers and user metadata', { timeout: 40_000 }, async () => {
+ await using resource = await createDriver();
+ const { driver } = resource;
+ const client = driver.getClient();
+ const metadata = {
+ 'x-amz-meta-original-name': 'original.txt',
+ 'cache-control': 'private, max-age=3600',
+ 'content-disposition': 'attachment; filename="original.txt"',
+ 'content-language': 'fr',
+ };
+ await client.putObject('source.txt', 'original content', 'text/plain', undefined, metadata);
- await driver.getClient().createBucket();
+ await driver.copyFile({ sourceStorageKey: 'source.txt', destinationStorageKey: 'copy.txt' });
+
+ const response = await client.getObjectResponse('copy.txt');
+ expect.assert(response);
+ expect(await response.text()).toEqual('original content');
+ expect(Object.fromEntries(response.headers)).toMatchObject({
+ ...metadata,
+ 'content-type': 'text/plain',
+ });
+ });
- return {
- driver,
- [Symbol.asyncDispose]: async () => {
- await localstackContainer.stop();
- },
+ test(
+ 'copies objects above the single-copy limit through a raw multipart stream with metadata',
+ { timeout: 40_000 },
+ async () => {
+ await using resource = await createDriver();
+ const client = resource.driver.getClient();
+ const sourceStorageKey = 'dossier été/文档 + #%.bin';
+ const destinationStorageKey = 'copie été/資料 + #%.bin';
+ const content = gzipSync(randomBytes(9 * IN_BYTES.MEGABYTE));
+ const metadata = {
+ 'x-amz-meta-original-name': 'original.bin',
+ 'cache-control': 'private, max-age=3600',
+ 'content-disposition': 'attachment; filename="original.bin"',
+ 'content-encoding': 'gzip',
+ 'content-language': 'fr',
};
+ await client.putObject(
+ sourceStorageKey,
+ content,
+ 'application/octet-stream',
+ undefined,
+ metadata,
+ );
+
+ const copier = buildS3StorageDriver({
+ client: new S3mini({
+ accessKeyId: 'test',
+ secretAccessKey: 'test',
+ region: client.region,
+ endpoint: client.endpoint.toString(),
+ minPartSize: MULTIPART_MIN_PART_SIZE_IN_BYTES,
+ fetch: async (input, init) => {
+ if (init?.method === 'PUT' && new Headers(init.headers).has('x-amz-copy-source')) {
+ throw new Error('CopyObject cannot copy objects above 5 GiB');
+ }
+
+ const response = await fetch(input, init);
+
+ if (init?.method === 'HEAD' && response.ok) {
+ // Advertise a >5 GiB source without allocating or transferring that much data.
+ const headers = new Headers(response.headers);
+ headers.set('content-length', String(5 * IN_BYTES.GIGABYTE + 1));
+ return new Response(null, { status: response.status, headers });
+ }
+
+ return response;
+ },
+ }),
+ });
+
+ await copier.copyFile({ sourceStorageKey, destinationStorageKey });
+ await resource.driver.deleteFile({ storageKey: sourceStorageKey });
+
+ const response = await request(await client.getPresignedUrl('GET', destinationStorageKey));
+ expect(Buffer.from(await response.body.arrayBuffer()).equals(content)).toEqual(true);
+ expect(response.statusCode).toEqual(200);
+ expect(response.headers).toMatchObject({
+ ...metadata,
+ 'content-type': 'application/octet-stream',
+ });
},
- });
+ );
});
});
diff --git a/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts
index beff13f3..c88cadbc 100644
--- a/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts
@@ -2,6 +2,7 @@ import type { S3StorageDriverOptions } from '../../storage.types';
import type { StorageDriver } from '../drivers.models';
import { Readable } from 'node:stream';
import { S3mini } from 's3mini';
+import { request } from 'undici';
import {
createFileAlreadyExistsInStorageError,
createFileNotFoundError,
@@ -12,6 +13,18 @@ import { IN_BYTES } from '../../../shared/units';
export const S3_STORAGE_DRIVER_NAME = 's3' as const;
export const MULTIPART_MIN_PART_SIZE_IN_BYTES = 8 * IN_BYTES.MEGABYTE;
+const MAX_SINGLE_COPY_SIZE_IN_BYTES = 5 * IN_BYTES.GIGABYTE;
+
+const COPY_METADATA_HEADERS = new Set([
+ 'content-type',
+ 'cache-control',
+ 'content-disposition',
+ 'content-encoding',
+ 'content-language',
+ 'expires',
+ 'x-amz-website-redirect-location',
+ 'x-amz-storage-class',
+]);
export const s3StorageDriverFactory = ({
accessKeyId,
@@ -29,6 +42,10 @@ export const s3StorageDriverFactory = ({
minPartSize: MULTIPART_MIN_PART_SIZE_IN_BYTES,
});
+ return buildS3StorageDriver({ client });
+};
+
+export function buildS3StorageDriver({ client }: { client: S3mini }) {
const fileExists = async ({ storageKey }: { storageKey: string }) => {
return (await client.objectExists(storageKey)) === true;
};
@@ -55,6 +72,58 @@ export const s3StorageDriverFactory = ({
await client.putAnyObject(storageKey, Readable.toWeb(buffered.stream), mimeType);
}
},
+ copyFile: async ({ sourceStorageKey, destinationStorageKey }) => {
+ if (!(await fileExists({ storageKey: sourceStorageKey }))) {
+ throw createFileNotFoundError();
+ }
+
+ // Like saveFile, this collision check is not atomic across S3-compatible providers.
+ if (await fileExists({ storageKey: destinationStorageKey })) {
+ throw createFileAlreadyExistsInStorageError();
+ }
+
+ const size = await client.getContentLength(sourceStorageKey);
+
+ if (size <= MAX_SINGLE_COPY_SIZE_IN_BYTES) {
+ await client.copyObject(sourceStorageKey, destinationStorageKey, {
+ metadataDirective: 'COPY',
+ });
+ return;
+ }
+
+ // CopyObject is limited to 5 GiB. Stream the stored bytes through a multipart upload.
+ // undici.request does not transparently decompress Content-Encoding, unlike fetch.
+ const url = await client.getPresignedUrl('GET', sourceStorageKey);
+ const { body, headers, statusCode } = await request(url);
+
+ try {
+ if (statusCode === 404) {
+ throw createFileNotFoundError();
+ }
+
+ if (statusCode !== 200) {
+ throw new Error(`Unable to read S3 copy source: HTTP ${statusCode}`);
+ }
+
+ const metadataHeaders = Object.fromEntries(
+ Object.entries(headers).filter(
+ (entry): entry is [string, string] =>
+ typeof entry[1] === 'string' &&
+ (entry[0].startsWith('x-amz-meta-') || COPY_METADATA_HEADERS.has(entry[0])),
+ ),
+ );
+
+ await client.putAnyObject(
+ destinationStorageKey,
+ Readable.toWeb(body),
+ metadataHeaders['content-type'],
+ undefined,
+ metadataHeaders,
+ );
+ } finally {
+ body.destroy();
+ }
+ },
getFileStream: async ({ storageKey }) => {
const response = await client.getObjectResponse(storageKey);
@@ -73,4 +142,4 @@ export const s3StorageDriverFactory = ({
},
fileExists,
} satisfies StorageDriver & { getClient: () => S3mini };
-};
+}
diff --git a/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts
index 6de4c322..a9ca9ada 100644
--- a/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts
@@ -1,6 +1,7 @@
import { Buffer } from 'node:buffer';
import { describe, expect, test } from 'vitest';
import {
+ collectReadableStreamToBuffer,
collectReadableStreamToString,
createReadableStream,
} from '../../shared/streams/readable-stream';
@@ -12,6 +13,117 @@ const firstKek = { version: '1', key: Buffer.alloc(32, 1) };
const secondKek = { version: '2', key: Buffer.alloc(32, 2) };
describe('storage-encryption services', () => {
+ test('copies identical ciphertext and decrypts with the source context after key rotation', async () => {
+ const storageDriver = inMemoryStorageDriverFactory();
+ const writer = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: { isEncryptionEnabled: true, keyEncryptionKeys: [firstKek] },
+ });
+ const encryptionContext = await writer.saveFile({
+ storageKey: 'source.txt',
+ fileName: 'source.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'encrypted content' }),
+ });
+ const storageService = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: { isEncryptionEnabled: true, keyEncryptionKeys: [firstKek, secondKek] },
+ });
+
+ await storageService.copyFile({
+ sourceStorageKey: 'source.txt',
+ destinationStorageKey: 'copy.txt',
+ });
+
+ const { fileStream: sourceStream } = await storageDriver.getFileStream({
+ storageKey: 'source.txt',
+ });
+ const { fileStream: destinationStream } = await storageDriver.getFileStream({
+ storageKey: 'copy.txt',
+ });
+ const sourceCiphertext = await collectReadableStreamToBuffer({ stream: sourceStream });
+ const destinationCiphertext = await collectReadableStreamToBuffer({
+ stream: destinationStream,
+ });
+ expect(sourceCiphertext).not.toEqual(Buffer.from('encrypted content'));
+ expect(destinationCiphertext).toEqual(sourceCiphertext);
+ expect(encryptionContext.fileEncryptionKekVersion).toEqual(firstKek.version);
+
+ const { fileStream } = await storageService.getFileStream({
+ storageKey: 'copy.txt',
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual(
+ 'encrypted content',
+ );
+ });
+
+ test('copies encrypted bytes without encryption keys after encryption is disabled', async () => {
+ const storageDriver = inMemoryStorageDriverFactory();
+ const writer = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: { isEncryptionEnabled: true, keyEncryptionKeys: [firstKek] },
+ });
+ const encryptionContext = await writer.saveFile({
+ storageKey: 'source.txt',
+ fileName: 'source.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'encrypted content' }),
+ });
+ const copier = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: { isEncryptionEnabled: false, keyEncryptionKeys: [] },
+ });
+
+ await copier.copyFile({ sourceStorageKey: 'source.txt', destinationStorageKey: 'copy.txt' });
+
+ const { fileStream: sourceStream } = await storageDriver.getFileStream({
+ storageKey: 'source.txt',
+ });
+ const { fileStream: destinationStream } = await storageDriver.getFileStream({
+ storageKey: 'copy.txt',
+ });
+ expect(await collectReadableStreamToBuffer({ stream: destinationStream })).toEqual(
+ await collectReadableStreamToBuffer({ stream: sourceStream }),
+ );
+ const { fileStream } = await writer.getFileStream({
+ storageKey: 'copy.txt',
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual(
+ 'encrypted content',
+ );
+ });
+
+ test('copies unencrypted files without encrypting them after encryption is enabled', async () => {
+ const storageDriver = inMemoryStorageDriverFactory();
+ const writer = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: { isEncryptionEnabled: false, keyEncryptionKeys: [] },
+ });
+ const encryptionContext = await writer.saveFile({
+ storageKey: 'source.txt',
+ fileName: 'source.txt',
+ mimeType: 'text/plain',
+ fileStream: createReadableStream({ content: 'unencrypted content' }),
+ });
+ const copier = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: { isEncryptionEnabled: true, keyEncryptionKeys: [] },
+ });
+
+ await copier.copyFile({ sourceStorageKey: 'source.txt', destinationStorageKey: 'copy.txt' });
+
+ expect(encryptionContext).toEqual({});
+ const { fileStream } = await copier.getFileStream({
+ storageKey: 'copy.txt',
+ ...encryptionContext,
+ });
+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual(
+ 'unencrypted content',
+ );
+ });
+
test('decrypts a file with the KEK version stored in its encryption context', async () => {
const storageDriver = inMemoryStorageDriverFactory();
const writer = wrapWithEncryptionLayer({