From 42b668d35c7dd64d7f7570cfc6f5e54c708e28a2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 21:13:35 -0800 Subject: [PATCH] fix(public-shares): retry a public read when the shared file is saved mid-read --- .../api/files/public/[token]/content/route.ts | 43 +++++----- .../api/files/public/[token]/inline/route.ts | 9 +- .../content-sharing.integration.ts | 84 +++++++++++++++++++ .../lib/public-shares/application/index.ts | 1 + .../sim/lib/public-shares/application/read.ts | 30 ++++++- 5 files changed, 141 insertions(+), 26 deletions(-) diff --git a/apps/sim/app/api/files/public/[token]/content/route.ts b/apps/sim/app/api/files/public/[token]/content/route.ts index e665b3a474c..134c01a843c 100644 --- a/apps/sim/app/api/files/public/[token]/content/route.ts +++ b/apps/sim/app/api/files/public/[token]/content/route.ts @@ -14,6 +14,7 @@ import { authorizePublicFileShare, checkPublicFileShareContent, readPublicFileShareContent, + retryOnSharedFileRevisionChange, } from '@/lib/public-shares/application' import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit' import { FILE_CACHE_CONTROL } from '@/lib/uploads/server/delivery' @@ -39,7 +40,7 @@ export const GET = withRouteHandler( }) if (!auth.authorized) return publicFileAuthDenied(auth) if (request.method === 'HEAD') { - await checkPublicFileShareContent(auth.grant) + await retryOnSharedFileRevisionChange(() => checkPublicFileShareContent(auth.grant)) return new NextResponse(null, { headers: { 'Cache-Control': FILE_CACHE_CONTROL.revalidate, @@ -47,26 +48,28 @@ export const GET = withRouteHandler( }, }) } - const result = await readPublicFileShareContent({ - grant: auth.grant, - preview: parsed.data.query.preview === '1', - request, - }) - if (result.kind === 'stream') { - return await createStoredFileStreamResponse( - { ...result, cacheControl: FILE_CACHE_CONTROL.revalidate }, - request.headers + return await retryOnSharedFileRevisionChange(async () => { + const result = await readPublicFileShareContent({ + grant: auth.grant, + preview: parsed.data.query.preview === '1', + request, + }) + if (result.kind === 'stream') { + return await createStoredFileStreamResponse( + { ...result, cacheControl: FILE_CACHE_CONTROL.revalidate }, + request.headers + ) + } + return createConditionalFileResponse( + { + buffer: result.buffer, + contentType: result.contentType, + filename: result.file.originalName, + cacheControl: FILE_CACHE_CONTROL.revalidate, + }, + request.headers.get('if-none-match') ) - } - return createConditionalFileResponse( - { - buffer: result.buffer, - contentType: result.contentType, - filename: result.file.originalName, - cacheControl: FILE_CACHE_CONTROL.revalidate, - }, - request.headers.get('if-none-match') - ) + }) } catch (error) { logPublicFileError(logger, 'Error serving public shared file:', error) return publicFileBinaryErrorResponse(error, 'Failed to serve file') diff --git a/apps/sim/app/api/files/public/[token]/inline/route.ts b/apps/sim/app/api/files/public/[token]/inline/route.ts index 346fbeb88a5..88120e21d77 100644 --- a/apps/sim/app/api/files/public/[token]/inline/route.ts +++ b/apps/sim/app/api/files/public/[token]/inline/route.ts @@ -13,6 +13,7 @@ import { import { authorizePublicFileShare, readPublicFileShareInline, + retryOnSharedFileRevisionChange, } from '@/lib/public-shares/application' import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit' import { FILE_CACHE_CONTROL } from '@/lib/uploads/server/delivery' @@ -34,11 +35,9 @@ export const GET = withRouteHandler( credential: await publicFileShareCredential(request.cookies.getAll(), getClientIp(request)), }) if (!auth.authorized) return publicFileAuthDenied(auth) - const result = await readPublicFileShareInline({ - grant: auth.grant, - ...parsed.data.query, - request, - }) + const result = await retryOnSharedFileRevisionChange(() => + readPublicFileShareInline({ grant: auth.grant, ...parsed.data.query, request }) + ) return createConditionalFileResponse( { buffer: result.buffer, diff --git a/apps/sim/lib/projects/files/__integration__/content-sharing.integration.ts b/apps/sim/lib/projects/files/__integration__/content-sharing.integration.ts index f406e9f0573..576dc15ad46 100644 --- a/apps/sim/lib/projects/files/__integration__/content-sharing.integration.ts +++ b/apps/sim/lib/projects/files/__integration__/content-sharing.integration.ts @@ -884,6 +884,90 @@ describe('Public file shares against PostgreSQL and private storage', () => { } ) + check( + 'public share content saved during an object read is delivered from a fresh snapshot, never mixed', + async () => { + const { updateProjectFileShare } = await import('@/lib/projects/files/application/shares') + const { + authorizePublicFileShare, + readPublicFileShareContent, + retryOnSharedFileRevisionChange, + } = await import('@/lib/public-shares/application') + // A Markdown file streams from storage; a page is rendered whole. Both see the save. + const saved = 'Saved while read' + const shared = { + streamed: { input: createInput, source: '' }, + rendered: { + input: (projectId: string) => ({ + ...createInput(projectId, '---\ntitle: Architecture\n---\n\nShared page'), + name: 'Architecture', + contentType: 'text/x-sim-page', + }), + source: '---\ntitle: Architecture\n---\n\n', + }, + } + for (const { input, source } of Object.values(shared)) + for (const saves of ['once', 'every read'] as const) { + const f = await fixture() + const { file } = await createProjectFile.execute({ + principal: f.principal, + input: input(f.projectId), + }) + const { share } = await updateProjectFileShare.execute({ + principal: f.principal, + input: { projectId: f.projectId, fileId: file.id, isActive: true }, + }) + const access = await authorizePublicFileShare({ + token: share.token, + credential: { method: 'GET' }, + }) + if (!access.authorized) throw new Error('Public fixture rejected') + // A collaborative save commits while the object is being read, buffered or streamed alike. + let written = 0 + let saving = false + const save = async () => { + if (saving || (saves === 'once' && written > 0)) return + saving = true + written++ + try { + await updateProjectFileContent.execute({ + principal: f.principal, + input: { + projectId: f.projectId, + fileId: file.id, + content: `${source}${saved} ${written}`, + encoding: 'utf-8', + }, + }) + } finally { + saving = false + } + } + const download = storage.downloadFile + const downloadStream = storage.downloadFileStream + const spies = [ + vi.spyOn(storage, 'downloadFile').mockImplementation(async (options) => { + const result = await download(options) + await save() + return result + }), + vi.spyOn(storage, 'downloadFileStream').mockImplementation(async (options) => { + const result = await downloadStream(options) + await save() + return result + }), + ] + const delivered = retryOnSharedFileRevisionChange(() => + sharedBytes(readPublicFileShareContent({ grant: access.grant })) + ) + if (saves === 'once') expect((await delivered).toString()).toContain(`${saved} 1`) + else await expect(delivered).rejects.toMatchObject({ code: 'conflict' }) + expect(written).toBe(saves === 'once' ? 1 : 3) + for (const spy of spies) spy.mockRestore() + } + } + ) + check( 'public share grants cannot be cloned or reused after Project archive and preserve workspace links', async () => { diff --git a/apps/sim/lib/public-shares/application/index.ts b/apps/sim/lib/public-shares/application/index.ts index b722ee4c0d5..3154986e07c 100644 --- a/apps/sim/lib/public-shares/application/index.ts +++ b/apps/sim/lib/public-shares/application/index.ts @@ -10,4 +10,5 @@ export { readPublicFileShare, readPublicFileShareContent, readPublicFileShareInline, + retryOnSharedFileRevisionChange, } from './read' diff --git a/apps/sim/lib/public-shares/application/read.ts b/apps/sim/lib/public-shares/application/read.ts index cd35d316e83..cb3cc456e5a 100644 --- a/apps/sim/lib/public-shares/application/read.ts +++ b/apps/sim/lib/public-shares/application/read.ts @@ -84,13 +84,41 @@ function renderSharedPage(source: string, snapshot: PublicFileShareSnapshot) { throw error } } +/** A content write (a collaborative save, an upload) committed between a read's snapshot and its delivery. */ +class SharedFileRevisionChangedError extends OrchestrationError { + constructor() { + super('conflict', 'Shared file changed during the read') + } +} +const MAX_SHARED_FILE_READ_ATTEMPTS = 3 function requireRevision(current: WorkspaceFileRow, expected: WorkspaceFileRow) { if ( current.id !== expected.id || current.key !== expected.key || current.contentUpdatedAt.getTime() !== expected.contentUpdatedAt.getTime() ) - throw new OrchestrationError('conflict', 'Shared file changed during the read') + throw new SharedFileRevisionChangedError() +} +/** + * Runs one public delivery again from a fresh snapshot when the shared file, or an input it embeds, + * is rewritten mid-read, as a collaborative save of a file being edited does. Every attempt is a + * complete read that still refuses mixed revisions, so this only spares the viewer a benign race; a + * file rewritten on every attempt still refuses. `deliver` must cover the whole delivery, including + * opening a stream, because a stream rechecks the revision on open. Nothing is reported or audited + * for a refused attempt. + */ +export async function retryOnSharedFileRevisionChange(deliver: () => Promise): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await deliver() + } catch (error) { + if ( + attempt >= MAX_SHARED_FILE_READ_ATTEMPTS || + !(asOrchestrationError(error) instanceof SharedFileRevisionChangedError) + ) + throw error + } + } } function requirePublicBytes(provenance: WorkspaceFileSecretProvenance) { if (