Skip to content

The open alternative to Salesforce, designed for AI.

fix: quarantine direct uploads until completion has validated them (#25342)

Félix Malfaite4b7f7b6cbcc
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
index 4d370b603ee..015080eb193 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
@@ -2,6 +2,7 @@ import {
mkdtemp,
mkdir,
readFile,
+ readdir,
rm,
stat,
symlink,
@@ -176,6 +177,42 @@ describe('LocalDriver', () => {
await expect(
stat(path.join(storagePath, 'workspace/app/partial.txt')),
).rejects.toMatchObject({ code: 'ENOENT' });
+
+ await expect(
+ readdir(path.join(storagePath, 'workspace/app')),
+ ).resolves.toEqual([]);
+ });
+
+ it('should publish each write as a new object rather than rewriting in place', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const driver = new LocalDriver({ storagePath });
+ const filePath = 'workspace/app/file.txt';
+
+ await driver.writeFileStream({
+ filePath,
+ stream: Readable.from(Buffer.from('first')),
+ mimeType: undefined,
+ });
+
+ const first = await stat(path.join(storagePath, filePath));
+
+ await driver.writeFileStream({
+ filePath,
+ stream: Readable.from(Buffer.from('secnd')),
+ mimeType: undefined,
+ });
+
+ const second = await stat(path.join(storagePath, filePath));
+
+ // Same length, so only the identity distinguishes them: a rewrite in
+ // place would keep the inode and leave a promotion unable to tell the
+ // two versions apart.
+ expect(second.size).toBe(first.size);
+ expect(second.ino).not.toBe(first.ino);
+
+ await expect(
+ readdir(path.join(storagePath, 'workspace/app')),
+ ).resolves.toEqual(['file.txt']);
});
});
@@ -229,6 +266,196 @@ describe('LocalDriver', () => {
});
});
+ describe('move', () => {
+ it('should refuse to move an object that changed since it was inspected', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const folderPath = path.join(storagePath, 'workspace', 'app');
+
+ await mkdir(folderPath, { recursive: true });
+ await writeFile(path.join(folderPath, 'file.txt'), 'original');
+
+ const driver = new LocalDriver({ storagePath });
+ const before = await driver.getFileMetadata({
+ filePath: 'workspace/app/file.txt',
+ });
+
+ await writeFile(path.join(folderPath, 'file.txt'), 'replaced');
+
+ await expect(
+ driver.move({
+ from: { folderPath: 'workspace/app', filename: 'file.txt' },
+ to: { folderPath: 'workspace/app', filename: 'moved.txt' },
+ ifMatchChecksum: before?.checksum,
+ }),
+ ).rejects.toMatchObject({
+ code: FileStorageExceptionCode.PRECONDITION_FAILED,
+ });
+ });
+
+ it('should move an object that still matches the inspected identity', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const folderPath = path.join(storagePath, 'workspace', 'app');
+
+ await mkdir(folderPath, { recursive: true });
+ await writeFile(path.join(folderPath, 'file.txt'), 'original');
+
+ const driver = new LocalDriver({ storagePath });
+ const before = await driver.getFileMetadata({
+ filePath: 'workspace/app/file.txt',
+ });
+
+ await driver.move({
+ from: { folderPath: 'workspace/app', filename: 'file.txt' },
+ to: { folderPath: 'workspace/app', filename: 'moved.txt' },
+ ifMatchChecksum: before?.checksum,
+ });
+
+ await expect(
+ driver.checkFileExists({ filePath: 'workspace/app/moved.txt' }),
+ ).resolves.toBe(true);
+ });
+
+ it('should report a missing source under a precondition as FILE_NOT_FOUND', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+
+ await mkdir(path.join(storagePath, 'workspace', 'app'), {
+ recursive: true,
+ });
+
+ const driver = new LocalDriver({ storagePath });
+
+ await expect(
+ driver.move({
+ from: { folderPath: 'workspace/app', filename: 'missing.txt' },
+ to: { folderPath: 'workspace/app', filename: 'moved.txt' },
+ ifMatchChecksum: 'any-checksum',
+ }),
+ ).rejects.toMatchObject({
+ code: FileStorageExceptionCode.FILE_NOT_FOUND,
+ });
+ });
+
+ it('should leave the source in place when the precondition fails', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const folderPath = path.join(storagePath, 'workspace', 'app');
+
+ await mkdir(folderPath, { recursive: true });
+ await writeFile(path.join(folderPath, 'file.txt'), 'original');
+
+ const driver = new LocalDriver({ storagePath });
+ const before = await driver.getFileMetadata({
+ filePath: 'workspace/app/file.txt',
+ });
+
+ await writeFile(path.join(folderPath, 'file.txt'), 'replaced');
+
+ await expect(
+ driver.move({
+ from: { folderPath: 'workspace/app', filename: 'file.txt' },
+ to: { folderPath: 'workspace/final', filename: 'moved.txt' },
+ ifMatchChecksum: before?.checksum,
+ }),
+ ).rejects.toMatchObject({
+ code: FileStorageExceptionCode.PRECONDITION_FAILED,
+ });
+
+ // A failed promotion must not strand the object under the private name
+ // it was claimed with, where nothing would ever look for it again.
+ await expect(readdir(folderPath)).resolves.toEqual(['file.txt']);
+ await expect(
+ readFile(path.join(folderPath, 'file.txt'), 'utf-8'),
+ ).resolves.toBe('replaced');
+ });
+
+ it('should leave the source in place when the destination rename fails', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const folderPath = path.join(storagePath, 'workspace', 'app');
+
+ await mkdir(folderPath, { recursive: true });
+ await writeFile(path.join(folderPath, 'file.txt'), 'original');
+
+ // A non-empty directory in the destination's place makes the final
+ // rename fail after the source has already been claimed.
+ const blockedDestination = path.join(
+ storagePath,
+ 'workspace',
+ 'final',
+ 'moved.txt',
+ );
+
+ await mkdir(blockedDestination, { recursive: true });
+ await writeFile(path.join(blockedDestination, 'occupant.txt'), 'x');
+
+ const driver = new LocalDriver({ storagePath });
+ const before = await driver.getFileMetadata({
+ filePath: 'workspace/app/file.txt',
+ });
+
+ await expect(
+ driver.move({
+ from: { folderPath: 'workspace/app', filename: 'file.txt' },
+ to: { folderPath: 'workspace/final', filename: 'moved.txt' },
+ ifMatchChecksum: before?.checksum,
+ }),
+ ).rejects.toBeDefined();
+
+ await expect(readdir(folderPath)).resolves.toEqual(['file.txt']);
+ await expect(
+ readFile(path.join(folderPath, 'file.txt'), 'utf-8'),
+ ).resolves.toBe('original');
+ });
+
+ it('should not report a storage failure as a missing source', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+
+ await mkdir(path.join(storagePath, 'workspace'), { recursive: true });
+ // A regular file where a directory is expected makes stat fail with
+ // ENOTDIR, which root cannot bypass the way it bypasses mode bits.
+ await writeFile(path.join(storagePath, 'workspace', 'blocker'), 'x');
+
+ const driver = new LocalDriver({ storagePath });
+
+ await expect(
+ driver.move({
+ from: { folderPath: 'workspace/blocker', filename: 'file.txt' },
+ to: { folderPath: 'workspace/app', filename: 'moved.txt' },
+ ifMatchChecksum: 'any-checksum',
+ }),
+ ).rejects.toMatchObject({ code: 'ENOTDIR' });
+ });
+
+ it('should write and promote a filename at the validation limit', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const driver = new LocalDriver({ storagePath });
+ // MAX_SEGMENT_LENGTH is the filesystem's own limit, so any suffix the
+ // driver adds to the filename for its temporary names would not fit.
+ const filename = `${'a'.repeat(251)}.txt`;
+
+ await driver.writeFileStream({
+ filePath: `workspace/app/${filename}`,
+ stream: Readable.from(Buffer.from('content')),
+ mimeType: undefined,
+ });
+
+ const before = await driver.getFileMetadata({
+ filePath: `workspace/app/${filename}`,
+ });
+
+ await driver.move({
+ from: { folderPath: 'workspace/app', filename },
+ to: { folderPath: 'workspace/final', filename },
+ ifMatchChecksum: before?.checksum,
+ });
+
+ await expect(
+ readFile(path.join(storagePath, 'workspace/final', filename), 'utf-8'),
+ ).resolves.toBe('content');
+ await expect(
+ readdir(path.join(storagePath, 'workspace/app')),
+ ).resolves.toEqual([]);
+ });
+ });
+
describe('getFileMetadata', () => {
it('should return the file size', async () => {
const storagePath = await createTempDirectory('local-driver-storage-');
@@ -241,7 +468,7 @@ describe('LocalDriver', () => {
await expect(
driver.getFileMetadata({ filePath: 'workspace/app/file.txt' }),
- ).resolves.toEqual({ size: 5 });
+ ).resolves.toMatchObject({ size: 5 });
});
it('should return null when the file does not exist', async () => {
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface.ts
index 060258ac4cf..becc26acad2 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface.ts
@@ -1,6 +1,7 @@
import { type Readable } from 'stream';
import { type ByteRange } from 'src/engine/core-modules/file-storage/types/byte-range.type';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
export interface StorageDriver {
readFile(params: {
@@ -25,7 +26,7 @@ export interface StorageDriver {
getFileMetadata(params: {
filePath: string;
- }): Promise<{ size: number } | null>;
+ }): Promise<FileStorageMetadata | null>;
downloadFolder(params: {
onStoragePath: string;
@@ -45,6 +46,7 @@ export interface StorageDriver {
move(params: {
from: { folderPath: string; filename?: string };
to: { folderPath: string; filename?: string };
+ ifMatchChecksum?: string;
}): Promise<void>;
copy(params: {
from: { folderPath: string; filename?: string };
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
index 6f4d78f485c..9d3ca459982 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
@@ -3,15 +3,20 @@ import {
createWriteStream,
existsSync,
realpathSync,
+ type Stats,
} from 'fs';
import * as fs from 'fs/promises';
import path, { dirname, join } from 'path';
import { type Readable } from 'stream';
import { pipeline } from 'stream/promises';
+import { Logger } from '@nestjs/common';
+
import { isDefined } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
import { type StorageDriver } from 'src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import {
FileStorageException,
FileStorageExceptionCode,
@@ -22,7 +27,14 @@ export interface LocalDriverOptions {
storagePath: string;
}
+// Local storage has no ETag, so identity comes from the stat fields that a
+// rewrite changes. Enough to catch a swap between an inspection and a move,
+// which is all callers use it for.
+const buildStatChecksum = (stats: Stats): string =>
+ `${stats.ino}-${stats.size}-${stats.mtimeMs}`;
+
export class LocalDriver implements StorageDriver {
+ private readonly logger = new Logger(LocalDriver.name);
private options: LocalDriverOptions;
constructor(options: LocalDriverOptions) {
@@ -176,19 +188,58 @@ export class LocalDriver implements StorageDriver {
params.filePath,
);
+ // Writing through to the destination would mutate the object other callers
+ // are already reading, in place and under a stable inode. Promotion
+ // identifies the version it validated by inode, so publishing each write as
+ // a new one is what keeps that identity meaningful. The temporary name
+ // does not carry the original filename: path validation allows filenames
+ // up to the filesystem's own limit, so appending to one could not fit.
+ const partialFilePath = join(dirname(realFilePath), `.${v4()}.part`);
+
try {
- await pipeline(params.stream, createWriteStream(realFilePath));
+ await pipeline(params.stream, createWriteStream(partialFilePath));
+ await fs.rename(partialFilePath, realFilePath);
} catch (error) {
// Remove the partial file so a failed upload can be retried cleanly
- await fs.rm(realFilePath, { force: true });
+ await fs.rm(partialFilePath, { force: true });
throw error;
}
}
+ private async assertChecksumMatchesOrThrow({
+ filePath,
+ expectedChecksum,
+ }: {
+ filePath: string;
+ expectedChecksum: string;
+ }): Promise<void> {
+ let stats: Stats;
+
+ try {
+ stats = await fs.stat(filePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ throw new FileStorageException(
+ 'File not found',
+ FileStorageExceptionCode.FILE_NOT_FOUND,
+ );
+ }
+
+ throw error;
+ }
+
+ if (buildStatChecksum(stats) !== expectedChecksum) {
+ throw new FileStorageException(
+ `Object at ${path.basename(filePath)} changed since it was inspected`,
+ FileStorageExceptionCode.PRECONDITION_FAILED,
+ );
+ }
+ }
+
async getFileMetadata(params: {
filePath: string;
- }): Promise<{ size: number } | null> {
+ }): Promise<FileStorageMetadata | null> {
const joinedPath = join(this.options.storagePath, params.filePath);
let filePath: string;
@@ -203,7 +254,7 @@ export class LocalDriver implements StorageDriver {
try {
const stats = await fs.stat(filePath);
- return { size: stats.size };
+ return { size: stats.size, checksum: buildStatChecksum(stats) };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null;
@@ -345,6 +396,7 @@ export class LocalDriver implements StorageDriver {
async move(params: {
from: { folderPath: string; filename?: string };
to: { folderPath: string; filename?: string };
+ ifMatchChecksum?: string;
}): Promise<void> {
const fromPath = path.resolve(
this.options.storagePath,
@@ -360,10 +412,30 @@ export class LocalDriver implements StorageDriver {
await this.createFolder(dirname(toPath));
+ if (isDefined(params.ifMatchChecksum)) {
+ await this.movePreconditionedOnChecksum({
+ fromPath,
+ toPath,
+ expectedChecksum: params.ifMatchChecksum,
+ });
+
+ return;
+ }
+
+ await this.renameOrThrow({ fromPath, toPath });
+ }
+
+ private async renameOrThrow({
+ fromPath,
+ toPath,
+ }: {
+ fromPath: string;
+ toPath: string;
+ }): Promise<void> {
try {
await fs.rename(fromPath, toPath);
} catch (error) {
- if (error.code === 'ENOENT') {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
throw new FileStorageException(
'File not found',
FileStorageExceptionCode.FILE_NOT_FOUND,
@@ -374,6 +446,48 @@ export class LocalDriver implements StorageDriver {
}
}
+ // Checking the source and then renaming it leaves a window in which a client
+ // still holding an upload target can publish over the path, so the rename
+ // would promote bytes that were never inspected. Claiming the source under a
+ // private name first makes the checked object and the moved object the same
+ // one: whatever a concurrent upload publishes afterwards lands on the
+ // original path and is no longer reachable from here.
+ private async movePreconditionedOnChecksum({
+ fromPath,
+ toPath,
+ expectedChecksum,
+ }: {
+ fromPath: string;
+ toPath: string;
+ expectedChecksum: string;
+ }): Promise<void> {
+ const claimedPath = join(dirname(fromPath), `.${v4()}.promoting`);
+
+ await this.renameOrThrow({ fromPath, toPath: claimedPath });
+
+ try {
+ await this.assertChecksumMatchesOrThrow({
+ filePath: claimedPath,
+ expectedChecksum,
+ });
+
+ await this.renameOrThrow({ fromPath: claimedPath, toPath });
+ } catch (error) {
+ // Put it back so the caller's retry and the cleanup sweep still find it
+ // at the path they know: the claim name is private to this call and
+ // nothing would look for it again. A concurrent upload may have
+ // published there in the meantime, but that path is bound for deletion
+ // either way.
+ await fs.rename(claimedPath, fromPath).catch(() => {
+ this.logger.error(
+ `Could not restore "${path.basename(fromPath)}" after a failed promotion`,
+ );
+ });
+
+ throw error;
+ }
+ }
+
async copy(params: {
from: { folderPath: string; filename?: string };
to: { folderPath: string; filename?: string };
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts
index 0f8c11ddd06..c5821251bbb 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/s3.driver.ts
@@ -35,6 +35,7 @@ import {
FILE_STORAGE_S3_SLOW_REQUEST_THRESHOLD_MS,
} from 'src/engine/core-modules/file-storage/constants/s3-client-timeouts.constant';
import { type StorageDriver } from 'src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import {
FileStorageException,
FileStorageExceptionCode,
@@ -225,7 +226,7 @@ export class S3Driver implements StorageDriver {
async getFileMetadata(params: {
filePath: string;
- }): Promise<{ size: number } | null> {
+ }): Promise<FileStorageMetadata | null> {
return this.measureRequest(
{ operation: 'HeadObject', key: params.filePath },
async () => {
@@ -237,7 +238,7 @@ export class S3Driver implements StorageDriver {
}),
);
- return { size: head.ContentLength ?? 0 };
+ return { size: head.ContentLength ?? 0, checksum: head.ETag };
} catch (error) {
if (error instanceof NotFound) {
return null;
@@ -388,6 +389,7 @@ export class S3Driver implements StorageDriver {
async move(params: {
from: { folderPath: string; filename?: string };
to: { folderPath: string; filename?: string };
+ ifMatchChecksum?: string;
}): Promise<void> {
if (!params.from.filename || !params.to.filename) {
await this.moveS3Folder(params);
@@ -409,6 +411,7 @@ export class S3Driver implements StorageDriver {
await this.s3Client.send(
new CopyObjectCommand({
CopySource: `${this.bucketName}/${fromKey}`,
+ CopySourceIfMatch: params.ifMatchChecksum,
Bucket: this.bucketName,
Key: toKey,
}),
@@ -427,6 +430,14 @@ export class S3Driver implements StorageDriver {
FileStorageExceptionCode.FILE_NOT_FOUND,
);
}
+
+ if (error.name === 'PreconditionFailed') {
+ throw new FileStorageException(
+ `Object at ${fromKey} changed since it was inspected`,
+ FileStorageExceptionCode.PRECONDITION_FAILED,
+ );
+ }
+
throw error;
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/validated-storage.driver.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/validated-storage.driver.ts
index 0b6576ba112..bfb721d7f53 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/validated-storage.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/validated-storage.driver.ts
@@ -1,6 +1,7 @@
import { type Readable } from 'stream';
import { type StorageDriver } from 'src/engine/core-modules/file-storage/drivers/interfaces/storage-driver.interface';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import { assertStoragePathIsSafe } from 'src/engine/core-modules/file-storage/utils/assert-storage-path-is-safe.util';
import { type ByteRange } from 'src/engine/core-modules/file-storage/types/byte-range.type';
@@ -48,7 +49,7 @@ export class ValidatedStorageDriver implements StorageDriver {
async getFileMetadata(params: {
filePath: string;
- }): Promise<{ size: number } | null> {
+ }): Promise<FileStorageMetadata | null> {
assertStoragePathIsSafe(params.filePath);
return this.delegate.getFileMetadata(params);
@@ -97,6 +98,7 @@ export class ValidatedStorageDriver implements StorageDriver {
async move(params: {
from: { folderPath: string; filename?: string };
to: { folderPath: string; filename?: string };
+ ifMatchChecksum?: string;
}): Promise<void> {
assertStoragePathIsSafe(params.from.folderPath);
assertStoragePathIsSafe(params.to.folderPath);
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/file-storage-exception-filter.ts b/packages/twenty-server/src/engine/core-modules/file-storage/file-storage-exception-filter.ts
index 31095cd5518..f992935dee9 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/file-storage-exception-filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/file-storage-exception-filter.ts
@@ -7,6 +7,7 @@ import {
FileStorageExceptionCode,
} from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
import {
+ ConflictError,
ForbiddenError,
NotFoundError,
UserInputError,
@@ -22,6 +23,8 @@ export class FileStorageExceptionFilter implements ExceptionFilter {
throw new ForbiddenError(exception);
case FileStorageExceptionCode.FILE_NOT_FOUND:
throw new NotFoundError(exception);
+ case FileStorageExceptionCode.PRECONDITION_FAILED:
+ throw new ConflictError(exception);
default:
assertUnreachable(exception.code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/interfaces/file-storage-exception.ts b/packages/twenty-server/src/engine/core-modules/file-storage/interfaces/file-storage-exception.ts
index 874cfbb7095..655cd404d58 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/interfaces/file-storage-exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/interfaces/file-storage-exception.ts
@@ -8,6 +8,7 @@ export enum FileStorageExceptionCode {
FILE_NOT_FOUND = 'FILE_NOT_FOUND',
ACCESS_DENIED = 'ACCESS_DENIED',
INVALID_EXTENSION = 'INVALID_EXTENSION',
+ PRECONDITION_FAILED = 'PRECONDITION_FAILED',
}
const getFileStorageExceptionUserFriendlyMessage = (
@@ -20,6 +21,8 @@ const getFileStorageExceptionUserFriendlyMessage = (
return msg`File not found.`;
case FileStorageExceptionCode.ACCESS_DENIED:
return msg`Access denied.`;
+ case FileStorageExceptionCode.PRECONDITION_FAILED:
+ return msg`The file changed while it was being processed.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
index ff0c3bd13d7..fc09b96e2d2 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
@@ -10,6 +10,7 @@ import { Like, type QueryRunner } from 'typeorm';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { findActiveFlatApplicationById } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-id.util';
import { findActiveFlatApplicationByUniversalIdentifier } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-universal-identifier.util';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import { FileStorageDriverFactory } from 'src/engine/core-modules/file-storage/file-storage-driver.factory';
import { type ByteRange } from 'src/engine/core-modules/file-storage/types/byte-range.type';
import {
@@ -330,7 +331,7 @@ export class FileStorageService {
async getFileMetadata(
params: ResourceIdentifier,
- ): Promise<{ size: number } | null> {
+ ): Promise<FileStorageMetadata | null> {
const driver = this.fileStorageDriverFactory.getCurrentDriver();
const { onStorageFilePath } =
this.validateAndBuildFileStoragePathOrThrow(params);
@@ -474,6 +475,20 @@ export class FileStorageService {
});
}
+ // Removes only the stored object. deleteFile also drops any row sitting at
+ // that path, which is wrong once the row is gone or belongs to a later
+ // upload that reused the same resource path.
+ async deleteFileObject(params: ResourceIdentifier): Promise<void> {
+ const driver = this.fileStorageDriverFactory.getCurrentDriver();
+ const { onStorageFilePath } =
+ this.validateAndBuildFileStoragePathOrThrow(params);
+
+ await driver.delete({
+ folderPath: dirname(onStorageFilePath),
+ filename: basename(onStorageFilePath),
+ });
+ }
+
async deleteFolder(
params: Omit<ResourceIdentifier, 'resourcePath'> & { folderPath: string },
): Promise<void> {
@@ -588,6 +603,29 @@ export class FileStorageService {
});
}
+ async move({
+ from,
+ to,
+ ifMatchChecksum,
+ }: {
+ from: ResourceIdentifier;
+ to: ResourceIdentifier;
+ ifMatchChecksum?: string;
+ }): Promise<void> {
+ const driver = this.fileStorageDriverFactory.getCurrentDriver();
+
+ const { onStorageFilePath: fromPath } =
+ this.validateAndBuildFileStoragePathOrThrow(from);
+ const { onStorageFilePath: toPath } =
+ this.validateAndBuildFileStoragePathOrThrow(to);
+
+ return driver.move({
+ from: { folderPath: dirname(fromPath), filename: basename(fromPath) },
+ to: { folderPath: dirname(toPath), filename: basename(toPath) },
+ ifMatchChecksum,
+ });
+ }
+
checkFileExists(params: ResourceIdentifier): Promise<boolean> {
const driver = this.fileStorageDriverFactory.getCurrentDriver();
const { onStorageFilePath } =
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts b/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts
new file mode 100644
index 00000000000..7d291795cf3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/types/file-storage-metadata.type.ts
@@ -0,0 +1,3 @@
+// checksum is whatever the backend can offer as a version identity (an S3
+// ETag); backends that have none omit it and callers lose the precondition.
+export type FileStorageMetadata = { size: number; checksum?: string };
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts
new file mode 100644
index 00000000000..5abb67ceab0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant.ts
@@ -0,0 +1,5 @@
+// Direct uploads land under this prefix and are only moved to their final
+// path once completeFileUpload has validated them. A presigned PUT URL stays
+// usable until it expires, so a client allowed to write straight to the final
+// path could swap the bytes after they were checked.
+export const PENDING_UPLOAD_PATH_PREFIX = '.pending';
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/file-upload.exception.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/file-upload.exception.ts
index 0ccc4cf7523..b4da10793dc 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/file-upload.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/file-upload.exception.ts
@@ -9,6 +9,7 @@ export enum FileUploadExceptionCode {
FILE_SIZE_MISMATCH = 'FILE_SIZE_MISMATCH',
FILE_TOO_LARGE = 'FILE_TOO_LARGE',
STORAGE_TIMEOUT = 'STORAGE_TIMEOUT',
+ STORAGE_INCONSISTENT = 'STORAGE_INCONSISTENT',
}
export class FileUploadException extends CustomException<FileUploadExceptionCode> {
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/filters/file-upload-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/filters/file-upload-api-exception.filter.ts
index a98819e7cb5..db37b77cacb 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/filters/file-upload-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/filters/file-upload-api-exception.filter.ts
@@ -41,6 +41,12 @@ export class FileUploadApiExceptionFilter implements ExceptionFilter {
response,
504,
);
+ case FileUploadExceptionCode.STORAGE_INCONSISTENT:
+ return this.httpExceptionHandlerService.handleError(
+ exception,
+ response,
+ 502,
+ );
case FileUploadExceptionCode.BAD_REQUEST:
case FileUploadExceptionCode.FILE_NOT_UPLOADED:
case FileUploadExceptionCode.FILE_SIZE_MISMATCH:
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
index 0e8e25e3f6d..1c22575a85d 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/__tests__/file-upload-completion.service.spec.ts
@@ -7,6 +7,7 @@ import { type FileEntity } from 'src/engine/core-modules/file/entities/file.enti
import { MAX_SANITIZABLE_SVG_BYTES } from 'src/engine/core-modules/file/file-upload/constants/max-sanitizable-svg-size.constant';
import { FileUploadExceptionCode } from 'src/engine/core-modules/file/file-upload/file-upload.exception';
import { FileUploadCompletionService } from 'src/engine/core-modules/file/file-upload/services/file-upload-completion.service';
+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
import { type WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
@@ -52,10 +53,12 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
.fn()
.mockImplementation(async () => Readable.from(Buffer.from(svgContent))),
writeFileStream: jest.fn().mockResolvedValue(undefined),
+ move: jest.fn().mockResolvedValue(undefined),
+ deleteFileObject: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<FileStorageService>;
fileRepository = {
- update: jest.fn().mockResolvedValue(undefined),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
} as unknown as jest.Mocked<WorkspaceScopedRepository<FileEntity>>;
});
@@ -66,7 +69,10 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
it('should refuse an SVG larger than the sanitizable limit without reading it', async () => {
const size = MAX_SANITIZABLE_SVG_BYTES + 1;
- fileStorageService.getFileMetadata.mockResolvedValue({ size });
+ fileStorageService.getFileMetadata.mockResolvedValue({
+ size,
+ checksum: '"etag-a"',
+ });
await expect(
buildService().completeUploadedFile({
@@ -87,6 +93,7 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
fileStorageService.getFileMetadata.mockResolvedValue({
size: declaredSize,
+ checksum: '"etag-a"',
});
fileStorageService.readFile.mockResolvedValue(
Readable.from(Buffer.alloc(MAX_SANITIZABLE_SVG_BYTES + 1)),
@@ -105,10 +112,71 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
expect(fileRepository.update).not.toHaveBeenCalled();
});
+ it('should refuse to promote a sanitized SVG whose new identity is unreadable', async () => {
+ const size = Buffer.byteLength(svgContent);
+
+ fileStorageService.getFileMetadata
+ .mockResolvedValueOnce({ size, checksum: '"etag-a"' })
+ .mockResolvedValueOnce(null);
+
+ await expect(
+ buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('svg', size),
+ storageLocation: buildStorageLocation('svg'),
+ }),
+ ).rejects.toMatchObject({
+ code: FileUploadExceptionCode.STORAGE_INCONSISTENT,
+ });
+
+ expect(fileStorageService.move).not.toHaveBeenCalled();
+ });
+
+ it('should refuse to promote a sanitized SVG that lost its version identity', async () => {
+ const size = Buffer.byteLength(svgContent);
+
+ fileStorageService.getFileMetadata
+ .mockResolvedValueOnce({ size, checksum: '"etag-a"' })
+ .mockResolvedValueOnce({ size: 10 });
+
+ await expect(
+ buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('svg', size),
+ storageLocation: buildStorageLocation('svg'),
+ }),
+ ).rejects.toMatchObject({
+ code: FileUploadExceptionCode.STORAGE_INCONSISTENT,
+ });
+
+ expect(fileStorageService.move).not.toHaveBeenCalled();
+ });
+
+ it('should promote a sanitized SVG under the identity it has after the rewrite', async () => {
+ const size = Buffer.byteLength(svgContent);
+
+ fileStorageService.getFileMetadata
+ .mockResolvedValueOnce({ size, checksum: '"etag-before"' })
+ .mockResolvedValueOnce({ size: 10, checksum: '"etag-after"' });
+
+ await buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('svg', size),
+ storageLocation: buildStorageLocation('svg'),
+ });
+
+ expect(fileStorageService.move).toHaveBeenCalledWith(
+ expect.objectContaining({ ifMatchChecksum: '"etag-after"' }),
+ );
+ });
+
it('should sanitize an SVG within the limit and store its new size', async () => {
const size = Buffer.byteLength(svgContent);
- fileStorageService.getFileMetadata.mockResolvedValue({ size });
+ fileStorageService.getFileMetadata.mockResolvedValue({
+ size,
+ checksum: '"etag-a"',
+ });
const completedFile = await buildService().completeUploadedFile({
workspaceId,
@@ -133,7 +201,10 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
it('should not read a file that does not need sanitizing', async () => {
const size = pngContent.length;
- fileStorageService.getFileMetadata.mockResolvedValue({ size });
+ fileStorageService.getFileMetadata.mockResolvedValue({
+ size,
+ checksum: '"etag-a"',
+ });
fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
const completedFile = await buildService().completeUploadedFile({
@@ -147,4 +218,108 @@ describe('FileUploadCompletionService.completeUploadedFile', () => {
expect(fileStorageService.readFile).not.toHaveBeenCalled();
expect(fileStorageService.writeFileStream).not.toHaveBeenCalled();
});
+
+ it('should validate the quarantined object and move it to its final path', async () => {
+ const size = pngContent.length;
+ const storageLocation = buildStorageLocation('png');
+ const pendingResourcePath = buildPendingUploadResourcePath({
+ fileId,
+ resourcePath: storageLocation.resourcePath,
+ });
+
+ fileStorageService.getFileMetadata.mockResolvedValue({
+ size,
+ checksum: '"etag-a"',
+ });
+ fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
+
+ await buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('png', size),
+ storageLocation,
+ });
+
+ expect(fileStorageService.getFileMetadata).toHaveBeenCalledWith(
+ expect.objectContaining({ resourcePath: pendingResourcePath }),
+ );
+ expect(fileStorageService.readFilePrefix).toHaveBeenCalledWith(
+ expect.objectContaining({ resourcePath: pendingResourcePath }),
+ );
+ expect(fileStorageService.move).toHaveBeenCalledWith({
+ from: expect.objectContaining({ resourcePath: pendingResourcePath }),
+ to: storageLocation,
+ ifMatchChecksum: '"etag-a"',
+ });
+ });
+
+ it('should not complete an upload from an object left at the final path', async () => {
+ const size = pngContent.length;
+ const storageLocation = buildStorageLocation('png');
+
+ fileStorageService.getFileMetadata.mockImplementation(async (location) =>
+ location.resourcePath === storageLocation.resourcePath
+ ? { size, checksum: '"etag-of-a-previous-upload"' }
+ : null,
+ );
+
+ await expect(
+ buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('png', size),
+ storageLocation,
+ }),
+ ).rejects.toMatchObject({
+ code: FileUploadExceptionCode.FILE_NOT_UPLOADED,
+ });
+
+ expect(fileStorageService.move).not.toHaveBeenCalled();
+ expect(fileRepository.update).not.toHaveBeenCalled();
+ });
+
+ it('should fail without touching storage when the row was reaped mid-completion', async () => {
+ const size = pngContent.length;
+
+ fileStorageService.getFileMetadata.mockResolvedValue({
+ size,
+ checksum: '"etag-a"',
+ });
+ fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
+ fileRepository.update.mockResolvedValue({
+ affected: 0,
+ raw: [],
+ generatedMaps: [],
+ });
+
+ await expect(
+ buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('png', size),
+ storageLocation: buildStorageLocation('png'),
+ }),
+ ).rejects.toMatchObject({
+ code: FileUploadExceptionCode.FILE_NOT_FOUND,
+ });
+
+ // Deliberately orphaned: this path cannot prove the object is still the
+ // one it promoted, and a later upload may own it by now.
+ expect(fileStorageService.deleteFileObject).not.toHaveBeenCalled();
+ });
+
+ it('should leave the promoted object alone on a successful completion', async () => {
+ const size = pngContent.length;
+
+ fileStorageService.getFileMetadata.mockResolvedValue({
+ size,
+ checksum: '"etag-a"',
+ });
+ fileStorageService.readFilePrefix.mockResolvedValue(pngContent);
+
+ await buildService().completeUploadedFile({
+ workspaceId,
+ file: buildFile('png', size),
+ storageLocation: buildStorageLocation('png'),
+ });
+
+ expect(fileStorageService.deleteFileObject).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
index 0bd884fc170..78daf9b20ea 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-completion.service.ts
@@ -1,10 +1,11 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { Readable } from 'stream';
import { FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { type FileStorageMetadata } from 'src/engine/core-modules/file-storage/types/file-storage-metadata.type';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
import { FileDTO } from 'src/engine/core-modules/file/dtos/file.dto';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
@@ -15,6 +16,7 @@ import {
FileUploadExceptionCode,
} from 'src/engine/core-modules/file/file-upload/file-upload.exception';
import { type BatchFileResult } from 'src/engine/core-modules/file/file-upload/types/batch-file-result.type';
+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
import { buildSvgTooLargeException } from 'src/engine/core-modules/file/file-upload/utils/build-svg-too-large-exception.util';
import { toBatchErrorMessage } from 'src/engine/core-modules/file/file-upload/utils/to-batch-error-message.util';
import {
@@ -47,6 +49,8 @@ type CompletedUploadedFile = FileDTO & Pick<FileEntity, 'mimeType'>;
@Injectable()
export class FileUploadCompletionService {
+ private readonly logger = new Logger(FileUploadCompletionService.name);
+
constructor(
private readonly fileStorageService: FileStorageService,
@InjectWorkspaceScopedRepository(FileEntity)
@@ -82,8 +86,20 @@ export class FileUploadCompletionService {
file: FileEntity;
storageLocation: FileUploadStorageLocation;
}): Promise<CompletedUploadedFile> {
+ const pendingLocation: FileUploadStorageLocation = {
+ ...storageLocation,
+ resourcePath: buildPendingUploadResourcePath({
+ fileId: file.id,
+ resourcePath: storageLocation.resourcePath,
+ }),
+ };
+
+ // Only the quarantined object is ever evidence of this upload. Falling
+ // back to the final path would let an object left there by a previous
+ // upload of the same resource path complete an upload that never
+ // delivered any bytes.
const metadata =
- await this.fileStorageService.getFileMetadata(storageLocation);
+ await this.fileStorageService.getFileMetadata(pendingLocation);
if (!isDefined(metadata)) {
throw new FileUploadException(
@@ -108,24 +124,54 @@ export class FileUploadCompletionService {
}
const mimeType = await this.detectUploadedMimeTypeOrThrow({
- ...storageLocation,
+ ...pendingLocation,
filename: file.path,
});
- this.assertMimeTypeAllowedForFolder(storageLocation.fileFolder, mimeType);
+ this.assertMimeTypeAllowedForFolder(pendingLocation.fileFolder, mimeType);
- const size = await this.sanitizeUploadedFileIfNeeded({
- storageLocation,
+ const { size, checksum } = await this.sanitizeUploadedFileIfNeeded({
+ storageLocation: pendingLocation,
mimeType,
- size: metadata.size,
+ metadata,
});
- await this.fileRepository.update(
+ // The presigned PUT stays usable until it expires, so the quarantined
+ // object can still be overwritten between the sniff above and this move.
+ // Promoting only the version that was inspected is what makes the
+ // recorded mimeType describe the bytes that end up at the final path.
+ await this.fileStorageService.move({
+ from: pendingLocation,
+ to: storageLocation,
+ ifMatchChecksum: checksum,
+ });
+
+ const { affected } = await this.fileRepository.update(
workspaceId,
{ id: file.id },
{ status: FILE_STATUS.UPLOADED, mimeType, size },
);
+ // The cleanup cron claims a stale PENDING row by deleting it, then deletes
+ // its objects, so losing the row here means it won. The promoting copy may
+ // have landed after its sweep and be orphaned; it is deliberately left
+ // there rather than rolled back, because this path cannot prove the object
+ // is still the one it wrote, and deleting a later upload's bytes is far
+ // worse than leaking one object.
+ if (affected === 0) {
+ this.logger.warn(
+ `File ${file.id} was reaped while completing; the object promoted to "${file.path}" may be orphaned`,
+ );
+
+ throw new FileUploadException(
+ `File ${file.id} was reaped while its upload was being completed`,
+ FileUploadExceptionCode.FILE_NOT_FOUND,
+ {
+ userFriendlyMessage: msg`This upload expired before it was confirmed. Please upload the file again.`,
+ },
+ );
+ }
+
return {
id: file.id,
path: file.path,
@@ -198,14 +244,16 @@ export class FileUploadCompletionService {
private async sanitizeUploadedFileIfNeeded({
storageLocation,
mimeType,
- size,
+ metadata,
}: {
storageLocation: FileUploadStorageLocation;
mimeType: string;
- size: number;
- }): Promise<number> {
+ metadata: FileStorageMetadata;
+ }): Promise<FileStorageMetadata> {
+ const { size } = metadata;
+
if (mimeType !== 'image/svg+xml') {
- return size;
+ return metadata;
}
if (size > MAX_SANITIZABLE_SVG_BYTES) {
@@ -248,6 +296,30 @@ export class FileUploadCompletionService {
mimeType,
});
- return sanitizedBuffer.length;
+ // Rewriting the object gives it a new version identity, so the checksum
+ // read before sanitizing would no longer match on the promoting copy.
+ const sanitizedMetadata =
+ await this.fileStorageService.getFileMetadata(storageLocation);
+
+ // Returning no identity here would silently downgrade that copy to an
+ // unconditional one, so a backend that reported one before the rewrite
+ // has to report one after it.
+ if (
+ !isDefined(sanitizedMetadata) ||
+ (isDefined(metadata.checksum) && !isDefined(sanitizedMetadata.checksum))
+ ) {
+ throw new FileUploadException(
+ `Could not read back the sanitized SVG at "${storageLocation.resourcePath}"`,
+ FileUploadExceptionCode.STORAGE_INCONSISTENT,
+ {
+ userFriendlyMessage: msg`File storage did not confirm the processed file. Please retry.`,
+ },
+ );
+ }
+
+ return {
+ size: sanitizedBuffer.length,
+ checksum: sanitizedMetadata.checksum,
+ };
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts
index c098bbca815..0a2336e68ea 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload-target.service.ts
@@ -1,12 +1,20 @@
import { Injectable } from '@nestjs/common';
+import { msg } from '@lingui/core/macro';
+
import { ApiPath, FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { v4 } from 'uuid';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import { validateFilePath } from 'src/engine/core-modules/file-storage/utils/validate-file-path.util';
import { FileUploadTargetDTO } from 'src/engine/core-modules/file/file-upload/dtos/file-upload-target.dto';
+import {
+ FileUploadException,
+ FileUploadExceptionCode,
+} from 'src/engine/core-modules/file/file-upload/file-upload.exception';
import { type BatchFileResult } from 'src/engine/core-modules/file/file-upload/types/batch-file-result.type';
+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
import { toBatchErrorMessage } from 'src/engine/core-modules/file/file-upload/utils/to-batch-error-message.util';
import { FileSettings } from 'src/engine/core-modules/file/types/file-settings.types';
import { FileUploadTokenJwtPayload } from 'src/engine/core-modules/auth/types/file-upload-token-jwt-payload.type';
@@ -51,6 +59,28 @@ export class FileUploadTargetService {
contentType: string;
size: number;
}): Promise<FileUploadTargetDTO> {
+ const pendingResourcePath = buildPendingUploadResourcePath({
+ fileId,
+ resourcePath,
+ });
+
+ // The prefix is added after the final path has passed validation, so a
+ // path close to the limit would only fail once the client tried to write.
+ const pendingPathValidation = validateFilePath({
+ resourcePath: pendingResourcePath,
+ fileFolder,
+ });
+
+ if (!pendingPathValidation.isValid) {
+ throw new FileUploadException(
+ `Resource path "${resourcePath}" leaves no room for the pending upload prefix: ${pendingPathValidation.error}`,
+ FileUploadExceptionCode.BAD_REQUEST,
+ {
+ userFriendlyMessage: msg`This file path is too long to upload.`,
+ },
+ );
+ }
+
const expiresInSeconds = this.twentyConfigService.get(
'STORAGE_S3_PRESIGNED_URL_EXPIRES_IN',
);
@@ -61,7 +91,7 @@ export class FileUploadTargetService {
fileFolder,
applicationUniversalIdentifier,
workspaceId,
- resourcePath,
+ resourcePath: pendingResourcePath,
contentType,
contentLength: size,
expiresInSeconds,
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts
index 27006f18554..3e1196d41f8 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/file-upload.service.ts
@@ -31,6 +31,7 @@ import { buildSvgTooLargeException } from 'src/engine/core-modules/file/file-upl
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
import { buildFileInfo } from 'src/engine/core-modules/file/utils/build-file-info.utils';
+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
import { removeFileFolderFromFileEntityPath } from 'src/engine/core-modules/file/utils/remove-file-folder-from-file-entity-path.utils';
import { FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -210,7 +211,10 @@ export class FileUploadService {
fileFolder,
applicationUniversalIdentifier: application.universalIdentifier,
workspaceId,
- resourcePath,
+ resourcePath: buildPendingUploadResourcePath({
+ fileId,
+ resourcePath,
+ }),
stream: sizeLimiter,
mimeType: file.mimeType,
}),
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
index 3f86b4031a9..75eb3e873ce 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
@@ -12,6 +12,7 @@ import {
PENDING_FILE_CLEANUP_BATCH_SIZE,
PENDING_FILE_MAX_AGE_MS,
} from 'src/engine/core-modules/file/file-upload/crons/constants/pending-file-cleanup.constants';
+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.types';
import { removeFileFolderFromFileEntityPath } from 'src/engine/core-modules/file/utils/remove-file-folder-from-file-entity-path.utils';
@@ -93,11 +94,40 @@ export class PendingFileCleanupService {
return;
}
- await this.fileStorageService.deleteFile({
+ const resourcePath = removeFileFolderFromFileEntityPath(file.path);
+
+ const location = {
workspaceId: file.workspaceId,
applicationUniversalIdentifier: application.universalIdentifier,
fileFolder: fileFolder as FileFolder,
- resourcePath: removeFileFolderFromFileEntityPath(file.path),
- });
+ };
+
+ // Normally the object is still in quarantine, but a crash between the move
+ // and the row update leaves it at its final path with the row PENDING.
+ //
+ // Quarantine goes first and the two are not concurrent: while a
+ // quarantined object still exists, a completion racing this cleanup can
+ // move it into the final path after that path has been deleted, orphaning
+ // an object no later run will look for. Both still run regardless of the
+ // other's outcome, since the row is already gone.
+ const failures: unknown[] = [];
+
+ for (const pathToDelete of [
+ buildPendingUploadResourcePath({ fileId: file.id, resourcePath }),
+ resourcePath,
+ ]) {
+ try {
+ await this.fileStorageService.deleteFileObject({
+ ...location,
+ resourcePath: pathToDelete,
+ });
+ } catch (error) {
+ failures.push(error);
+ }
+ }
+
+ if (failures.length > 0) {
+ throw failures[0];
+ }
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts
new file mode 100644
index 00000000000..3c78a3e59f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/__tests__/build-pending-upload-resource-path.util.spec.ts
@@ -0,0 +1,46 @@
+import { FileFolder } from 'twenty-shared/types';
+
+import { validateFilePath } from 'src/engine/core-modules/file-storage/utils/validate-file-path.util';
+import { buildPendingUploadResourcePath } from 'src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util';
+
+describe('buildPendingUploadResourcePath', () => {
+ const fileId = '20202020-0000-4000-8000-000000000001';
+
+ it('should keep the final resource path under the prefix', () => {
+ expect(
+ buildPendingUploadResourcePath({
+ fileId,
+ resourcePath: 'field-universal-identifier/document.pdf',
+ }),
+ ).toBe(`.pending/${fileId}/field-universal-identifier/document.pdf`);
+ });
+
+ // The presigned PUT targets the quarantine path, so it has to survive the
+ // same storage validation as the final path for every folder shape.
+ it.each([
+ { fileFolder: FileFolder.FilesField, resourcePath: 'field-uid/file.png' },
+ { fileFolder: FileFolder.Workflow, resourcePath: 'attachment.pdf' },
+ { fileFolder: FileFolder.EmailImage, resourcePath: 'inline-image.png' },
+ { fileFolder: FileFolder.EmailAttachment, resourcePath: 'attachment.eml' },
+ { fileFolder: FileFolder.AgentChat, resourcePath: 'chat-upload.png' },
+ { fileFolder: FileFolder.Source, resourcePath: 'src/index.ts' },
+ { fileFolder: FileFolder.Dependencies, resourcePath: 'yarn.lock' },
+ ])(
+ 'should build a path that validates for $fileFolder',
+ ({ fileFolder, resourcePath }) => {
+ expect(validateFilePath({ resourcePath, fileFolder })).toEqual({
+ isValid: true,
+ });
+
+ expect(
+ validateFilePath({
+ resourcePath: buildPendingUploadResourcePath({
+ fileId,
+ resourcePath,
+ }),
+ fileFolder,
+ }),
+ ).toEqual({ isValid: true });
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts
new file mode 100644
index 00000000000..247b33c7b1a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/utils/build-pending-upload-resource-path.util.ts
@@ -0,0 +1,11 @@
+import { PENDING_UPLOAD_PATH_PREFIX } from 'src/engine/core-modules/file/file-upload/constants/pending-upload-path-prefix.constant';
+
+// The final resource path is kept verbatim under the prefix so that path and
+// extension validation behave identically for both locations.
+export const buildPendingUploadResourcePath = ({
+ fileId,
+ resourcePath,
+}: {
+ fileId: string;
+ resourcePath: string;
+}): string => `${PENDING_UPLOAD_PATH_PREFIX}/${fileId}/${resourcePath}`;