Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(sandbox-drive): download from the drive through the storage export (#22730)

Rdmclin25732c2528c14
diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts
index 8f0611b5c20..67497dd57c8 100644
--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts
@@ -41,6 +41,7 @@ const plane = vi.hoisted(() => ({
createDirectory: vi.fn(),
deleteFile: vi.fn(),
deleteInstance: vi.fn(),
+ exportFile: vi.fn(),
getStorage: vi.fn(),
listFiles: vi.fn(),
readOccupancy: vi.fn(),
@@ -150,6 +151,11 @@ beforeEach(async () => {
plane.createDirectory.mockReset().mockImplementation(async ({ path }) => ({ path }));
plane.deleteFile.mockReset().mockImplementation(async ({ path }) => ({ path }));
plane.deleteInstance.mockReset().mockResolvedValue(undefined);
+ // A storage service that cannot export, so a download packs in a sandbox
+ // unless a case says otherwise.
+ plane.exportFile
+ .mockReset()
+ .mockRejectedValue(new SandboxStorageFilesError('no', 501, 'EXPORT_UNAVAILABLE'));
plane.listFiles.mockReset().mockRejectedValue(notFound());
plane.readOccupancy.mockReset().mockResolvedValue({ held: [], unavailable: false });
plane.renameFile.mockReset().mockImplementation(async ({ newPath }) => ({ path: newPath }));
@@ -634,6 +640,47 @@ describe('downloading from the drive', () => {
expect(packed()).toMatchObject({ hidden: ['projects/secret'], path: 'projects' });
});
+ it('exports a public folder through the storage service, without a sandbox', async () => {
+ await legacyPrivateFolder(ownerId, 'projects/secret');
+ plane.exportFile.mockResolvedValue({
+ contentType: 'application/zip',
+ kind: 'directory',
+ size: 7,
+ });
+
+ const result = await drive(memberId).prepareDownload({ drive: 'public', path: 'projects' });
+
+ expect(result).toMatchObject({ fileName: 'projects.zip', kind: 'directory', size: 7 });
+ expect(plane.exportFile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ hidden: ['projects/secret'],
+ path: 'projects',
+ uploadUrl: expect.stringContaining('sandbox-drive-downloads/'),
+ }),
+ { signal: expect.any(AbortSignal) },
+ );
+ expect(reached.at(-1)).toBe(STORAGE_KEY);
+ expect(downloads.callTool).not.toHaveBeenCalled();
+ });
+
+ it('says what an export refused in codes the client translates', async () => {
+ plane.exportFile.mockRejectedValue(
+ new SandboxStorageFilesError('gone', 404, 'EXPORT_NOT_FOUND'),
+ );
+ await expect(
+ drive(memberId).prepareDownload({ drive: 'public', path: 'gone' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'PATH_NOT_FOUND' });
+
+ plane.exportFile.mockRejectedValue(
+ new SandboxStorageFilesError('upload', 500, 'EXPORT_UPLOAD_FAILED'),
+ );
+ // A 500, never a 502: the edge replaces a 502's body and the code is lost.
+ await expect(
+ drive(memberId).prepareDownload({ drive: 'public', path: 'projects' }),
+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR', message: 'DOWNLOAD_FAILED' });
+ expect(downloads.callTool).not.toHaveBeenCalled();
+ });
+
it("downloads from the caller's own personal drive", async () => {
answer({ contentType: 'text/plain', kind: 'file', ok: true, size: 3 });
diff --git a/apps/server/src/routers/lambda/sandboxStorage/download.ts b/apps/server/src/routers/lambda/sandboxStorage/download.ts
index f357edb92c9..2f71261dd58 100644
--- a/apps/server/src/routers/lambda/sandboxStorage/download.ts
+++ b/apps/server/src/routers/lambda/sandboxStorage/download.ts
@@ -14,8 +14,13 @@ import { assertReadable, resolveDriveScope } from './driveScope';
import { instanceProcedure } from './procedures';
import { driveSchema, relativePathSchema } from './schemas';
+/**
+ * `DOWNLOAD_FAILED` is a 500, not the 502 a failed upstream would suggest:
+ * the edge in front of the app replaces a 502's body with its own error page,
+ * so the client could no longer read the code and said "unreadable response".
+ */
const ERROR_CODES: Record<DriveDownloadError['code'], TRPCError['code']> = {
- DOWNLOAD_FAILED: 'BAD_GATEWAY',
+ DOWNLOAD_FAILED: 'INTERNAL_SERVER_ERROR',
DOWNLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE',
DOWNLOAD_UNAVAILABLE: 'NOT_IMPLEMENTED',
PATH_NOT_FOUND: 'NOT_FOUND',
@@ -32,13 +37,14 @@ const ERROR_CODES: Record<DriveDownloadError['code'], TRPCError['code']> = {
export const driveDownloadTopicId = (storageKey: string) => `sandbox-drive-download:${storageKey}`;
/**
- * Copies one path of the drive to object storage from a sandbox session and
- * answers with a link to it. Read the way a listing is β€” a member reaches
- * whatever they can browse β€” and a hidden environment directory is refused
+ * Copies one path of the drive to object storage β€” through the storage
+ * service, or a sandbox session where it cannot β€” and answers with a link to
+ * it. Read the way a listing is β€” a member reaches whatever they can
+ * browse β€” and a hidden environment directory is refused
* when named and left out of any folder that holds it.
*
- * A mutation, not a query: it starts a sandbox session and writes an object
- * to storage, and a refetch-on-focus must never repeat that.
+ * A mutation, not a query: it writes an object to storage β€” and may start a
+ * sandbox session to do it β€” so a refetch-on-focus must never repeat that.
*/
const copyProcedure = (purpose: DriveCopyPurpose) =>
instanceProcedure
@@ -61,6 +67,7 @@ const copyProcedure = (purpose: DriveCopyPurpose) =>
path: input.path,
purpose,
sandbox,
+ storage: scope.client,
});
} catch (error) {
if (error instanceof DriveDownloadError) {
diff --git a/apps/server/src/services/sandbox/__tests__/driveDownload.test.ts b/apps/server/src/services/sandbox/__tests__/driveDownload.test.ts
index 54d5f771cad..8c0ce683ff5 100644
--- a/apps/server/src/services/sandbox/__tests__/driveDownload.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/driveDownload.test.ts
@@ -17,6 +17,7 @@ import {
parseDriveDownloadOutput,
prepareDriveDownload,
} from '../driveDownload';
+import { SandboxStorageFilesError } from '../storageFiles';
const hasPython = spawnSync('python3', ['--version']).status === 0;
@@ -425,4 +426,143 @@ describe('prepareDriveDownload', () => {
).rejects.toMatchObject({ code: 'DOWNLOAD_UNAVAILABLE' });
expect(sandbox.callTool).not.toHaveBeenCalled();
});
+
+ describe('through the storage service', () => {
+ const storageAnswering = (answer: () => Promise<any>) => ({ exportFile: vi.fn(answer) });
+
+ it('exports without a sandbox and links the copy', async () => {
+ const storage = storageAnswering(async () => ({
+ contentType: 'application/zip',
+ kind: 'directory',
+ size: 9,
+ }));
+ const sandbox = sandboxAnswering(undefined);
+
+ const result = await prepareDriveDownload({
+ fileService,
+ hidden: ['project/private'],
+ path: 'project',
+ sandbox,
+ storage,
+ });
+
+ const [key] = fileService.createPreSignedUpload.mock.calls[0] as unknown as [string];
+ expect(storage.exportFile).toHaveBeenCalledWith(
+ {
+ fileOnly: undefined,
+ hidden: ['project/private'],
+ maxBytes: DRIVE_DOWNLOAD_MAX_BYTES,
+ maxFiles: expect.any(Number),
+ path: 'project',
+ uploadHeaders: { 'x-amz-acl': 'public-read' },
+ uploadUrl: `https://upload/${key}`,
+ },
+ { signal: expect.any(AbortSignal) },
+ );
+ expect(result).toMatchObject({ fileName: 'project.zip', kind: 'directory', size: 9 });
+ expect(sandbox.callTool).not.toHaveBeenCalled();
+ });
+
+ it('bounds the export, and fails it without a sandbox when it runs out of time', async () => {
+ const storage = storageAnswering(async () => {
+ throw new DOMException('The operation timed out.', 'TimeoutError');
+ });
+ const sandbox = sandboxAnswering(undefined);
+
+ await expect(
+ prepareDriveDownload({ fileService, hidden: [], path: 'big', sandbox, storage }),
+ ).rejects.toMatchObject({
+ code: 'DOWNLOAD_FAILED',
+ message: 'DOWNLOAD_FAILED: EXPORT_TIMEOUT',
+ });
+
+ const [, options] = storage.exportFile.mock.calls[0] as unknown as [unknown, any];
+ expect(options.signal).toBeInstanceOf(AbortSignal);
+ expect(sandbox.callTool).not.toHaveBeenCalled();
+ expect(fileService.deleteFile).toHaveBeenCalled();
+ });
+
+ it('works on a deployment whose sandbox has no shell', async () => {
+ const storage = storageAnswering(async () => ({
+ contentType: 'text/plain',
+ kind: 'file',
+ size: 1,
+ }));
+
+ await expect(
+ prepareDriveDownload({
+ fileService,
+ hidden: [],
+ path: 'a.txt',
+ purpose: 'preview',
+ sandbox: sandboxAnswering('', false),
+ storage,
+ }),
+ ).resolves.toMatchObject({ fileName: 'a.txt' });
+ expect(storage.exportFile).toHaveBeenCalledWith(
+ expect.objectContaining({ fileOnly: true }),
+ expect.anything(),
+ );
+ });
+
+ it('packs in a sandbox when the storage service cannot export', async () => {
+ for (const error of [
+ new SandboxStorageFilesError('no function', 501, 'EXPORT_UNAVAILABLE'),
+ // A storage service from before the route: Not Found, with no code of ours.
+ new SandboxStorageFilesError('Not Found', 404),
+ new SandboxStorageFilesError('Method Not Allowed', 405),
+ ]) {
+ const sandbox = sandboxAnswering(
+ 'LOBE_DRIVE_DOWNLOAD_RESULT {"ok":true,"kind":"file","size":1,"contentType":"text/plain"}',
+ );
+
+ await expect(
+ prepareDriveDownload({
+ fileService,
+ hidden: [],
+ path: 'a.txt',
+ sandbox,
+ storage: storageAnswering(async () => {
+ throw error;
+ }),
+ }),
+ ).resolves.toMatchObject({ fileName: 'a.txt' });
+ expect(sandbox.callTool).toHaveBeenCalledOnce();
+ }
+ });
+
+ it('answers a refusal in the codes the client translates, and deletes the copy', async () => {
+ const cases = [
+ ['EXPORT_NOT_FOUND', 404, 'PATH_NOT_FOUND'],
+ ['EXPORT_TOO_LARGE', 413, 'DOWNLOAD_TOO_LARGE'],
+ ['EXPORT_NOT_A_FILE', 400, 'PREVIEW_NOT_A_FILE'],
+ ['EXPORT_UPLOAD_FAILED', 500, 'DOWNLOAD_FAILED'],
+ ['EXPORT_READ_FAILED', 500, 'DOWNLOAD_FAILED'],
+ ['EXPORT_INTERNAL', 500, 'DOWNLOAD_FAILED'],
+ // A request the storage service rejected is ours to fix, not a reason
+ // to retry the same copy in a sandbox.
+ ['EXPORT_INVALID_PARAMS', 400, 'DOWNLOAD_FAILED'],
+ [undefined, 502, 'DOWNLOAD_FAILED'],
+ ] as const;
+
+ for (const [code, status, expected] of cases) {
+ fileService.deleteFile.mockClear();
+ const sandbox = sandboxAnswering(undefined);
+
+ await expect(
+ prepareDriveDownload({
+ fileService,
+ hidden: [],
+ path: 'a',
+ sandbox,
+ storage: storageAnswering(async () => {
+ throw new SandboxStorageFilesError('refused', status, code);
+ }),
+ }),
+ ).rejects.toMatchObject({ code: expected });
+ expect(sandbox.callTool).not.toHaveBeenCalled();
+ expect(fileService.deleteFile).toHaveBeenCalledOnce();
+ }
+ });
+ });
});
diff --git a/apps/server/src/services/sandbox/driveDownload.ts b/apps/server/src/services/sandbox/driveDownload.ts
index 1ebc53baf49..a00f57c0287 100644
--- a/apps/server/src/services/sandbox/driveDownload.ts
+++ b/apps/server/src/services/sandbox/driveDownload.ts
@@ -4,6 +4,7 @@ import debug from 'debug';
import type { PreSignedUpload } from '@/server/modules/S3';
+import { type SandboxStorageExportResult, SandboxStorageFilesError } from './storageFiles';
import type { SandboxService } from './types';
const log = debug('lobe-server:sandbox:drive-download');
@@ -23,6 +24,13 @@ export const DRIVE_DOWNLOAD_MAX_FILES = 50_000;
/** How long the sandbox may spend packing and uploading. */
export const DRIVE_DOWNLOAD_TIMEOUT_MS = 180_000;
+/**
+ * How long the storage service may spend exporting. It answers well inside
+ * this or not at all; past it the request is abandoned rather than holding
+ * this one open, and not retried in a sandbox, which would stall the same way.
+ */
+export const DRIVE_EXPORT_TIMEOUT_MS = 90_000;
+
/** How long the link the browser follows stays valid. */
export const DRIVE_DOWNLOAD_URL_EXPIRES_IN = 15 * 60;
@@ -374,9 +382,119 @@ export interface PrepareDriveDownloadParams {
path: string;
/** Defaults to `download`. */
purpose?: DriveCopyPurpose;
+ /** Packs the copy in a session, where the storage service cannot export it. */
sandbox: Pick<SandboxService, 'callTool' | 'capabilities'>;
+ /**
+ * The drive's storage service, which copies off the volume without a
+ * sandbox session β€” tried first. Absent where there is none.
+ */
+ storage?: {
+ exportFile: (
+ params: {
+ fileOnly?: boolean;
+ hidden?: string[];
+ maxBytes?: number;
+ maxFiles?: number;
+ path: string;
+ uploadHeaders?: Record<string, string>;
+ uploadUrl: string;
+ },
+ options?: { signal?: AbortSignal },
+ ) => Promise<SandboxStorageExportResult>;
+ };
}
+type CopyOutcome = Extract<DriveDownloadOutcome, { ok: true }>;
+
+/** The export refusals that mean something to the person, as the codes the client translates. */
+const EXPORT_REFUSALS: Record<string, DriveDownloadError['code']> = {
+ EXPORT_NOT_A_FILE: 'PREVIEW_NOT_A_FILE',
+ EXPORT_NOT_FOUND: 'PATH_NOT_FOUND',
+ EXPORT_TOO_LARGE: 'DOWNLOAD_TOO_LARGE',
+};
+
+/**
+ * Copies through the storage service, or answers `undefined` when this
+ * deployment's cannot: one without the file function says so (501), and one
+ * that predates the route does not know it (a 404 with no code of ours).
+ */
+const exportFromStorage = async (
+ storage: NonNullable<PrepareDriveDownloadParams['storage']>,
+ params: { fileOnly: boolean; hidden: string[]; path: string; upload: PreSignedUpload },
+): Promise<CopyOutcome | undefined> => {
+ try {
+ const result = await storage.exportFile(
+ {
+ fileOnly: params.fileOnly || undefined,
+ hidden: params.hidden,
+ maxBytes: DRIVE_DOWNLOAD_MAX_BYTES,
+ maxFiles: DRIVE_DOWNLOAD_MAX_FILES,
+ path: params.path,
+ uploadHeaders: params.upload.headers,
+ uploadUrl: params.upload.url,
+ },
+ { signal: AbortSignal.timeout(DRIVE_EXPORT_TIMEOUT_MS) },
+ );
+ return { ...result, ok: true };
+ } catch (error) {
+ if ((error as { name?: unknown } | null)?.name === 'TimeoutError') {
+ log('drive export timed out after %dms', DRIVE_EXPORT_TIMEOUT_MS);
+ throw new DriveDownloadError('DOWNLOAD_FAILED', 'EXPORT_TIMEOUT');
+ }
+ if (error instanceof SandboxStorageFilesError) {
+ const unsupported =
+ error.code === 'EXPORT_UNAVAILABLE' ||
+ ((error.status === 404 || error.status === 405) && !error.code?.startsWith('EXPORT_'));
+ if (unsupported) {
+ log('storage cannot export (%d %s), packing in a sandbox', error.status, error.code);
+ return;
+ }
+ const refusal = error.code && EXPORT_REFUSALS[error.code];
+ if (refusal) throw new DriveDownloadError(refusal);
+ log('drive export failed: %O', error);
+ throw new DriveDownloadError('DOWNLOAD_FAILED', error.code || error.message);
+ }
+ throw error;
+ }
+};
+
+/** Packs the copy inside a sandbox session the drive is mounted in. */
+const copyInSandbox = async (
+ sandbox: PrepareDriveDownloadParams['sandbox'],
+ params: { fileOnly: boolean; hidden: string[]; path: string; upload: PreSignedUpload },
+): Promise<CopyOutcome> => {
+ const result = await sandbox.callTool('runCommand', {
+ command: buildDriveDownloadCommand({
+ fileOnly: params.fileOnly,
+ hidden: params.hidden,
+ maxBytes: DRIVE_DOWNLOAD_MAX_BYTES,
+ maxFiles: DRIVE_DOWNLOAD_MAX_FILES,
+ path: params.path,
+ uploadHeaders: params.upload.headers,
+ uploadUrl: params.upload.url,
+ }),
+ timeout: DRIVE_DOWNLOAD_TIMEOUT_MS,
+ });
+
+ const stdout = (result.result as { stdout?: unknown } | null | undefined)?.stdout;
+ const outcome = typeof stdout === 'string' ? parseDriveDownloadOutput(stdout) : undefined;
+
+ if (!outcome) {
+ log('drive download produced no result: %O', result.error ?? result.result);
+ throw new DriveDownloadError('DOWNLOAD_FAILED', result.error?.message);
+ }
+
+ if (!outcome.ok) {
+ log('drive download refused: %O', outcome);
+ if (outcome.code === 'NOT_FOUND') throw new DriveDownloadError('PATH_NOT_FOUND');
+ if (outcome.code === 'TOO_LARGE') throw new DriveDownloadError('DOWNLOAD_TOO_LARGE');
+ if (outcome.code === 'NOT_A_FILE') throw new DriveDownloadError('PREVIEW_NOT_A_FILE');
+ throw new DriveDownloadError('DOWNLOAD_FAILED', outcome.code);
+ }
+
+ return outcome;
+};
+
const dayOf = (date: Date) => date.toISOString().slice(0, 10);
/**
@@ -423,9 +541,11 @@ const sweepExpiredDownloads = async (
* Puts one file or folder of the drive where the browser can fetch it, and
* answers with the link.
*
- * The drive is only mounted inside a sandbox, so the bytes are read there and
- * uploaded from there straight to object storage; nothing passes through this
- * server. The object is a transient copy, not a library file: no file record
+ * The bytes never pass through this server: the drive's storage service
+ * reads them off the volume and uploads them straight to object storage. Only
+ * where it cannot (a deployment without that service) are they packed inside
+ * a sandbox session the drive is mounted in β€” which a shared storage, a
+ * workspace's public drive, refuses at its root. The object is a transient copy, not a library file: no file record
* is made, so a download never shows up among the user's resources. A copy
* that never gets a link is deleted at once; the rest are swept once expired.
*/
@@ -436,8 +556,11 @@ export const prepareDriveDownload = async ({
path,
purpose = 'download',
sandbox,
+ storage,
}: PrepareDriveDownloadParams) => {
- if (!sandbox.capabilities.shell) throw new DriveDownloadError('DOWNLOAD_UNAVAILABLE');
+ if (!storage && !sandbox.capabilities.shell) {
+ throw new DriveDownloadError('DOWNLOAD_UNAVAILABLE');
+ }
const key = `${DRIVE_DOWNLOAD_PREFIX}${dayOf(now)}/${randomUUID()}`;
// Private whatever the bucket's default ACL: a copy of someone's drive is
@@ -447,33 +570,11 @@ export const prepareDriveDownload = async ({
const sweep = sweepExpiredDownloads(fileService, now);
try {
- const result = await sandbox.callTool('runCommand', {
- command: buildDriveDownloadCommand({
- fileOnly: purpose === 'preview',
- hidden,
- maxBytes: DRIVE_DOWNLOAD_MAX_BYTES,
- maxFiles: DRIVE_DOWNLOAD_MAX_FILES,
- path,
- uploadHeaders: upload.headers,
- uploadUrl: upload.url,
- }),
- timeout: DRIVE_DOWNLOAD_TIMEOUT_MS,
- });
-
- const stdout = (result.result as { stdout?: unknown } | null | undefined)?.stdout;
- const outcome = typeof stdout === 'string' ? parseDriveDownloadOutput(stdout) : undefined;
-
+ const copy = { fileOnly: purpose === 'preview', hidden, path, upload };
+ let outcome = storage ? await exportFromStorage(storage, copy) : undefined;
if (!outcome) {
- log('drive download produced no result: %O', result.error ?? result.result);
- throw new DriveDownloadError('DOWNLOAD_FAILED', result.error?.message);
- }
-
- if (!outcome.ok) {
- log('drive download refused: %O', outcome);
- if (outcome.code === 'NOT_FOUND') throw new DriveDownloadError('PATH_NOT_FOUND');
- if (outcome.code === 'TOO_LARGE') throw new DriveDownloadError('DOWNLOAD_TOO_LARGE');
- if (outcome.code === 'NOT_A_FILE') throw new DriveDownloadError('PREVIEW_NOT_A_FILE');
- throw new DriveDownloadError('DOWNLOAD_FAILED', outcome.code);
+ if (!sandbox.capabilities.shell) throw new DriveDownloadError('DOWNLOAD_UNAVAILABLE');
+ outcome = await copyInSandbox(sandbox, copy);
}
const fileName = driveDownloadFileName(path, outcome.kind);
diff --git a/apps/server/src/services/sandbox/storageFiles.ts b/apps/server/src/services/sandbox/storageFiles.ts
index 5eb3d712a49..252dd211401 100644
--- a/apps/server/src/services/sandbox/storageFiles.ts
+++ b/apps/server/src/services/sandbox/storageFiles.ts
@@ -26,6 +26,12 @@ export interface SandboxStorageFileEntry {
size?: number;
}
+export interface SandboxStorageExportResult {
+ contentType: string;
+ kind: 'directory' | 'file';
+ size: number;
+}
+
export interface SandboxStorageFileList {
entries: SandboxStorageFileEntry[];
path: string;
@@ -232,6 +238,32 @@ export const createSandboxStorageClient = ({ baseURL, headers }: SandboxStorageC
};
return {
+ /**
+ * Copy one file as it is, or one folder as a zip, to a presigned upload
+ * URL β€” read off the volume by the storage service itself, without a
+ * sandbox session. A refusal carries an `EXPORT_*` code; a deployment
+ * that cannot export answers 501 `EXPORT_UNAVAILABLE`, and one that
+ * predates the route answers 404 with no code.
+ */
+ exportFile: async (
+ params: {
+ fileOnly?: boolean;
+ hidden?: string[];
+ maxBytes?: number;
+ maxFiles?: number;
+ path: string;
+ uploadHeaders?: Record<string, string>;
+ uploadUrl: string;
+ },
+ options: { signal?: AbortSignal } = {},
+ ): Promise<SandboxStorageExportResult> =>
+ request(`${CURRENT_STORAGE}/export`, {
+ body: JSON.stringify(params),
+ signal: options.signal,
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ }),
+
/**
* Create a directory, parents included. Idempotent β€” an existing directory
* is a success, so a picker can offer "new folder" without first proving