Skip to content

Commit 42b668d

Browse files
committed
fix(public-shares): retry a public read when the shared file is saved mid-read
1 parent 188d06f commit 42b668d

5 files changed

Lines changed: 141 additions & 26 deletions

File tree

‎apps/sim/app/api/files/public/[token]/content/route.ts‎

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
authorizePublicFileShare,
1515
checkPublicFileShareContent,
1616
readPublicFileShareContent,
17+
retryOnSharedFileRevisionChange,
1718
} from '@/lib/public-shares/application'
1819
import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit'
1920
import { FILE_CACHE_CONTROL } from '@/lib/uploads/server/delivery'
@@ -39,34 +40,36 @@ export const GET = withRouteHandler(
3940
})
4041
if (!auth.authorized) return publicFileAuthDenied(auth)
4142
if (request.method === 'HEAD') {
42-
await checkPublicFileShareContent(auth.grant)
43+
await retryOnSharedFileRevisionChange(() => checkPublicFileShareContent(auth.grant))
4344
return new NextResponse(null, {
4445
headers: {
4546
'Cache-Control': FILE_CACHE_CONTROL.revalidate,
4647
'X-Content-Type-Options': 'nosniff',
4748
},
4849
})
4950
}
50-
const result = await readPublicFileShareContent({
51-
grant: auth.grant,
52-
preview: parsed.data.query.preview === '1',
53-
request,
54-
})
55-
if (result.kind === 'stream') {
56-
return await createStoredFileStreamResponse(
57-
{ ...result, cacheControl: FILE_CACHE_CONTROL.revalidate },
58-
request.headers
51+
return await retryOnSharedFileRevisionChange(async () => {
52+
const result = await readPublicFileShareContent({
53+
grant: auth.grant,
54+
preview: parsed.data.query.preview === '1',
55+
request,
56+
})
57+
if (result.kind === 'stream') {
58+
return await createStoredFileStreamResponse(
59+
{ ...result, cacheControl: FILE_CACHE_CONTROL.revalidate },
60+
request.headers
61+
)
62+
}
63+
return createConditionalFileResponse(
64+
{
65+
buffer: result.buffer,
66+
contentType: result.contentType,
67+
filename: result.file.originalName,
68+
cacheControl: FILE_CACHE_CONTROL.revalidate,
69+
},
70+
request.headers.get('if-none-match')
5971
)
60-
}
61-
return createConditionalFileResponse(
62-
{
63-
buffer: result.buffer,
64-
contentType: result.contentType,
65-
filename: result.file.originalName,
66-
cacheControl: FILE_CACHE_CONTROL.revalidate,
67-
},
68-
request.headers.get('if-none-match')
69-
)
72+
})
7073
} catch (error) {
7174
logPublicFileError(logger, 'Error serving public shared file:', error)
7275
return publicFileBinaryErrorResponse(error, 'Failed to serve file')

‎apps/sim/app/api/files/public/[token]/inline/route.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
import {
1414
authorizePublicFileShare,
1515
readPublicFileShareInline,
16+
retryOnSharedFileRevisionChange,
1617
} from '@/lib/public-shares/application'
1718
import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit'
1819
import { FILE_CACHE_CONTROL } from '@/lib/uploads/server/delivery'
@@ -34,11 +35,9 @@ export const GET = withRouteHandler(
3435
credential: await publicFileShareCredential(request.cookies.getAll(), getClientIp(request)),
3536
})
3637
if (!auth.authorized) return publicFileAuthDenied(auth)
37-
const result = await readPublicFileShareInline({
38-
grant: auth.grant,
39-
...parsed.data.query,
40-
request,
41-
})
38+
const result = await retryOnSharedFileRevisionChange(() =>
39+
readPublicFileShareInline({ grant: auth.grant, ...parsed.data.query, request })
40+
)
4241
return createConditionalFileResponse(
4342
{
4443
buffer: result.buffer,

‎apps/sim/lib/projects/files/__integration__/content-sharing.integration.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,6 +884,90 @@ describe('Public file shares against PostgreSQL and private storage', () => {
884884
}
885885
)
886886

887+
check(
888+
'public share content saved during an object read is delivered from a fresh snapshot, never mixed',
889+
async () => {
890+
const { updateProjectFileShare } = await import('@/lib/projects/files/application/shares')
891+
const {
892+
authorizePublicFileShare,
893+
readPublicFileShareContent,
894+
retryOnSharedFileRevisionChange,
895+
} = await import('@/lib/public-shares/application')
896+
// A Markdown file streams from storage; a page is rendered whole. Both see the save.
897+
const saved = 'Saved while read'
898+
const shared = {
899+
streamed: { input: createInput, source: '' },
900+
rendered: {
901+
input: (projectId: string) => ({
902+
...createInput(projectId, '---\ntitle: Architecture\n---\n\nShared page'),
903+
name: 'Architecture',
904+
contentType: 'text/x-sim-page',
905+
}),
906+
source: '---\ntitle: Architecture\n---\n\n',
907+
},
908+
}
909+
for (const { input, source } of Object.values(shared))
910+
for (const saves of ['once', 'every read'] as const) {
911+
const f = await fixture()
912+
const { file } = await createProjectFile.execute({
913+
principal: f.principal,
914+
input: input(f.projectId),
915+
})
916+
const { share } = await updateProjectFileShare.execute({
917+
principal: f.principal,
918+
input: { projectId: f.projectId, fileId: file.id, isActive: true },
919+
})
920+
const access = await authorizePublicFileShare({
921+
token: share.token,
922+
credential: { method: 'GET' },
923+
})
924+
if (!access.authorized) throw new Error('Public fixture rejected')
925+
// A collaborative save commits while the object is being read, buffered or streamed alike.
926+
let written = 0
927+
let saving = false
928+
const save = async () => {
929+
if (saving || (saves === 'once' && written > 0)) return
930+
saving = true
931+
written++
932+
try {
933+
await updateProjectFileContent.execute({
934+
principal: f.principal,
935+
input: {
936+
projectId: f.projectId,
937+
fileId: file.id,
938+
content: `${source}${saved} ${written}`,
939+
encoding: 'utf-8',
940+
},
941+
})
942+
} finally {
943+
saving = false
944+
}
945+
}
946+
const download = storage.downloadFile
947+
const downloadStream = storage.downloadFileStream
948+
const spies = [
949+
vi.spyOn(storage, 'downloadFile').mockImplementation(async (options) => {
950+
const result = await download(options)
951+
await save()
952+
return result
953+
}),
954+
vi.spyOn(storage, 'downloadFileStream').mockImplementation(async (options) => {
955+
const result = await downloadStream(options)
956+
await save()
957+
return result
958+
}),
959+
]
960+
const delivered = retryOnSharedFileRevisionChange(() =>
961+
sharedBytes(readPublicFileShareContent({ grant: access.grant }))
962+
)
963+
if (saves === 'once') expect((await delivered).toString()).toContain(`${saved} 1`)
964+
else await expect(delivered).rejects.toMatchObject({ code: 'conflict' })
965+
expect(written).toBe(saves === 'once' ? 1 : 3)
966+
for (const spy of spies) spy.mockRestore()
967+
}
968+
}
969+
)
970+
887971
check(
888972
'public share grants cannot be cloned or reused after Project archive and preserve workspace links',
889973
async () => {

‎apps/sim/lib/public-shares/application/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ export {
1010
readPublicFileShare,
1111
readPublicFileShareContent,
1212
readPublicFileShareInline,
13+
retryOnSharedFileRevisionChange,
1314
} from './read'

‎apps/sim/lib/public-shares/application/read.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,13 +84,41 @@ function renderSharedPage(source: string, snapshot: PublicFileShareSnapshot) {
8484
throw error
8585
}
8686
}
87+
/** A content write (a collaborative save, an upload) committed between a read's snapshot and its delivery. */
88+
class SharedFileRevisionChangedError extends OrchestrationError {
89+
constructor() {
90+
super('conflict', 'Shared file changed during the read')
91+
}
92+
}
93+
const MAX_SHARED_FILE_READ_ATTEMPTS = 3
8794
function requireRevision(current: WorkspaceFileRow, expected: WorkspaceFileRow) {
8895
if (
8996
current.id !== expected.id ||
9097
current.key !== expected.key ||
9198
current.contentUpdatedAt.getTime() !== expected.contentUpdatedAt.getTime()
9299
)
93-
throw new OrchestrationError('conflict', 'Shared file changed during the read')
100+
throw new SharedFileRevisionChangedError()
101+
}
102+
/**
103+
* Runs one public delivery again from a fresh snapshot when the shared file, or an input it embeds,
104+
* is rewritten mid-read, as a collaborative save of a file being edited does. Every attempt is a
105+
* complete read that still refuses mixed revisions, so this only spares the viewer a benign race; a
106+
* file rewritten on every attempt still refuses. `deliver` must cover the whole delivery, including
107+
* opening a stream, because a stream rechecks the revision on open. Nothing is reported or audited
108+
* for a refused attempt.
109+
*/
110+
export async function retryOnSharedFileRevisionChange<T>(deliver: () => Promise<T>): Promise<T> {
111+
for (let attempt = 1; ; attempt++) {
112+
try {
113+
return await deliver()
114+
} catch (error) {
115+
if (
116+
attempt >= MAX_SHARED_FILE_READ_ATTEMPTS ||
117+
!(asOrchestrationError(error) instanceof SharedFileRevisionChangedError)
118+
)
119+
throw error
120+
}
121+
}
94122
}
95123
function requirePublicBytes(provenance: WorkspaceFileSecretProvenance) {
96124
if (

0 commit comments

Comments
 (0)