-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(file): workspace-scoped inline images + public-share cascade #5203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
e14499f
feat(file): workspace-scoped inline images + public-share cascade
TheodoreSpeaks 45e51f1
feat(file): add Image command to the markdown editor slash menu
TheodoreSpeaks a007410
fix(file): export rewrites all embed forms; cap embedded refs combined
TheodoreSpeaks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
116 changes: 116 additions & 0 deletions
116
apps/sim/app/api/files/public/[token]/inline/route.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockResolveShare, mockRateLimit, mockValidateAuth, mockDownloadFile, mockResolveImage } = | ||
| vi.hoisted(() => ({ | ||
| mockResolveShare: vi.fn(), | ||
| mockRateLimit: vi.fn(), | ||
| mockValidateAuth: vi.fn(), | ||
| mockDownloadFile: vi.fn(), | ||
| mockResolveImage: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/public-shares/share-manager', () => ({ | ||
| resolveActiveShareByToken: mockResolveShare, | ||
| })) | ||
| vi.mock('@/lib/public-shares/rate-limit', () => ({ enforcePublicFileRateLimit: mockRateLimit })) | ||
| vi.mock('@/lib/core/security/deployment-auth', () => ({ validateDeploymentAuth: mockValidateAuth })) | ||
| vi.mock('@/lib/uploads/core/storage-service', () => ({ downloadFile: mockDownloadFile })) | ||
| vi.mock('@/lib/uploads/server/inline-image', () => ({ | ||
| resolveWorkspaceInlineImage: mockResolveImage, | ||
| })) | ||
|
|
||
| import { GET } from '@/app/api/files/public/[token]/inline/route' | ||
|
|
||
| const TOKEN = 'tok_share_123456' | ||
| const DOC_KEY = 'workspace/ws-1/doc.md' | ||
| const IMG_KEY = 'workspace/ws-1/photo.png' | ||
| const FILE_ID = 'wf_YwDXi8eWOkTxn0sbgChlB' | ||
| const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]) | ||
|
|
||
| const params = { params: Promise.resolve({ token: TOKEN }) } | ||
| const req = (q: string) => new NextRequest(`http://localhost/api/files/public/${TOKEN}/inline?${q}`) | ||
|
|
||
| const share = { | ||
| share: { id: 'sh_1', token: TOKEN, authType: 'public' }, | ||
| file: { id: 'wf_doc', key: DOC_KEY, workspaceId: 'ws-1', originalName: 'doc.md' }, | ||
| workspaceName: 'Acme', | ||
| ownerName: 'Jane', | ||
| } | ||
|
|
||
| /** doc bytes embed the image via the view form; image bytes are a real PNG */ | ||
| function downloadByKey(docContent = ``) { | ||
| return ({ key }: { key: string }) => | ||
| Promise.resolve(key === DOC_KEY ? Buffer.from(docContent, 'utf-8') : PNG) | ||
| } | ||
|
|
||
| describe('GET /api/files/public/[token]/inline', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockRateLimit.mockResolvedValue(null) | ||
| mockResolveShare.mockResolvedValue(share) | ||
| mockValidateAuth.mockResolvedValue({ authorized: true }) | ||
| mockResolveImage.mockResolvedValue({ | ||
| key: IMG_KEY, | ||
| contentType: 'image/png', | ||
| filename: 'photo.png', | ||
| }) | ||
| mockDownloadFile.mockImplementation(downloadByKey()) | ||
| }) | ||
|
|
||
| it('serves a same-workspace image referenced by the doc, typed from its bytes', async () => { | ||
| const res = await GET(req(`fileId=${FILE_ID}`), params) | ||
| expect(res.status).toBe(200) | ||
| expect(res.headers.get('content-type')).toBe('image/png') | ||
| }) | ||
|
|
||
| it('serves a key-referenced image', async () => { | ||
| mockDownloadFile.mockImplementation( | ||
| downloadByKey(`}?context=workspace)`) | ||
| ) | ||
| const res = await GET(req(`key=${encodeURIComponent(IMG_KEY)}`), params) | ||
| expect(res.status).toBe(200) | ||
| }) | ||
|
|
||
| it('404s when the reference is not embedded in the shared document', async () => { | ||
| mockDownloadFile.mockImplementation(downloadByKey('no images here')) | ||
| const res = await GET(req(`fileId=${FILE_ID}`), params) | ||
| expect(res.status).toBe(404) | ||
| expect(mockResolveImage).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('404s when the referenced file is not in the document workspace', async () => { | ||
| mockResolveImage.mockResolvedValue(null) | ||
| const res = await GET(req(`fileId=${FILE_ID}`), params) | ||
| expect(res.status).toBe(404) | ||
| }) | ||
|
|
||
| it('404s when the bytes are not a renderable image', async () => { | ||
| mockDownloadFile.mockImplementation(({ key }: { key: string }) => | ||
| Promise.resolve( | ||
| key === DOC_KEY | ||
| ? Buffer.from(``, 'utf-8') | ||
| : Buffer.from('<svg/>', 'utf-8') | ||
| ) | ||
| ) | ||
| const res = await GET(req(`fileId=${FILE_ID}`), params) | ||
| expect(res.status).toBe(404) | ||
| }) | ||
|
|
||
| it('401s and never reads storage when the share is unauthorized', async () => { | ||
| mockValidateAuth.mockResolvedValue({ authorized: false, error: 'auth_required_password' }) | ||
| const res = await GET(req(`fileId=${FILE_ID}`), params) | ||
| expect(res.status).toBe(401) | ||
| expect(mockDownloadFile).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('404s for an unknown or inactive token', async () => { | ||
| mockResolveShare.mockResolvedValue(null) | ||
| const res = await GET(req(`fileId=${FILE_ID}`), params) | ||
| expect(res.status).toBe(404) | ||
| expect(mockDownloadFile).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import type { NextRequest } from 'next/server' | ||
| import { NextResponse } from 'next/server' | ||
| import { getPublicInlineFileContract } from '@/lib/api/contracts/public-shares' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { | ||
| extractEmbeddedImageIds, | ||
| extractEmbeddedImageKeys, | ||
| } from '@/lib/copilot/tools/server/files/embedded-image-refs' | ||
| import { validateDeploymentAuth } from '@/lib/core/security/deployment-auth' | ||
| import { generateRequestId } from '@/lib/core/utils/request' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { enforcePublicFileRateLimit } from '@/lib/public-shares/rate-limit' | ||
| import { resolveActiveShareByToken } from '@/lib/public-shares/share-manager' | ||
| import { downloadFile } from '@/lib/uploads/core/storage-service' | ||
| import { resolveWorkspaceInlineImage } from '@/lib/uploads/server/inline-image' | ||
| import { serveInlineImage } from '@/app/api/files/serve-inline-image' | ||
| import { createErrorResponse, FileNotFoundError } from '@/app/api/files/utils' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| const logger = createLogger('PublicInlineFileAPI') | ||
|
|
||
| /** | ||
| * GET /api/files/public/[token]/inline?key=<cloudKey>|fileId=<id> | ||
| * | ||
| * Cascades a markdown document's public share to the images it embeds, so a logged-out viewer sees them | ||
| * instead of broken icons. The share grants the document bytes; this route extends that grant to the | ||
| * document's referenced images only, behind three gates that together hold the security boundary: | ||
| * | ||
| * 1. Referenced-by-doc — the requested key/id must appear in the shared document's current bytes. The | ||
| * token is a capability for the document and its embeds, never an arbitrary workspace file. | ||
| * 2. Same-workspace — the referenced file must be a `workspace` file in the document's own workspace | ||
| * ({@link resolveWorkspaceInlineImage}). This blocks any cross-workspace reference (which an author | ||
| * can write but must never resolve) from loading. | ||
| * 3. Content-truth — the served content type is sniffed from the bytes, not the client-declared type, | ||
| * and only genuine raster images are served. A file spoofing `image/png` while holding HTML/SVG is | ||
| * refused rather than rendered inline. | ||
| */ | ||
| export const GET = withRouteHandler( | ||
| async (request: NextRequest, context: { params: Promise<{ token: string }> }) => { | ||
| const requestId = generateRequestId() | ||
|
|
||
| try { | ||
| const limited = await enforcePublicFileRateLimit(request, 'content') | ||
| if (limited) return limited | ||
|
|
||
| const parsed = await parseRequest(getPublicInlineFileContract, request, context) | ||
| if (!parsed.success) return parsed.response | ||
| const { token } = parsed.data.params | ||
| const ref = parsed.data.query | ||
|
|
||
| const resolved = await resolveActiveShareByToken(token) | ||
| if (!resolved) { | ||
| throw new FileNotFoundError('Not found') | ||
| } | ||
|
|
||
| const auth = await validateDeploymentAuth( | ||
| requestId, | ||
| resolved.share, | ||
| request, | ||
| undefined, | ||
| 'file' | ||
| ) | ||
| if (!auth.authorized) { | ||
| return NextResponse.json({ error: auth.error ?? 'auth_required_password' }, { status: 401 }) | ||
| } | ||
|
|
||
| const { file: doc } = resolved | ||
| if (!doc.workspaceId) { | ||
| throw new FileNotFoundError('Not found') | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // Referenced-by-doc gate: the share grants exactly the images the document embeds. | ||
| const docText = (await downloadFile({ key: doc.key, context: 'workspace' })).toString('utf-8') | ||
| const referenced = ref.fileId | ||
| ? extractEmbeddedImageIds(docText).includes(ref.fileId) | ||
| : extractEmbeddedImageKeys(docText).includes(ref.key as string) | ||
| if (!referenced) { | ||
| throw new FileNotFoundError('Not found') | ||
| } | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
|
|
||
| // Same-workspace gate: resolve scoped to the document's own workspace. | ||
| const image = await resolveWorkspaceInlineImage(doc.workspaceId, ref) | ||
| if (!image) { | ||
| throw new FileNotFoundError('Not found') | ||
| } | ||
|
|
||
| // Content-truth gate (`sniff`): render only genuine raster image bytes. | ||
| return await serveInlineImage(image, { sniff: true }) | ||
| } catch (error) { | ||
| if (error instanceof FileNotFoundError) { | ||
| return createErrorResponse(error) | ||
| } | ||
| logger.error('Error serving public inline image:', error) | ||
| return createErrorResponse(error instanceof Error ? error : new Error('Failed to serve file')) | ||
| } | ||
| } | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import type { NextResponse } from 'next/server' | ||
| import { downloadFile } from '@/lib/uploads/core/storage-service' | ||
| import type { ResolvedInlineImage } from '@/lib/uploads/server/inline-image' | ||
| import { sniffImageContentType } from '@/lib/uploads/utils/validation' | ||
| import { createFileResponse, FileNotFoundError } from '@/app/api/files/utils' | ||
|
|
||
| const logger = createLogger('InlineImageServe') | ||
|
|
||
| /** | ||
| * A shared/edited/deleted file must never serve stale bytes from its fixed inline URL, so every inline | ||
| * image revalidates on each request. | ||
| */ | ||
| const INLINE_CACHE_CONTROL = 'private, no-cache, must-revalidate' | ||
|
|
||
| /** | ||
| * Download and respond with an already-workspace-scoped inline image — the single serving tail for both | ||
| * the in-app and public inline routes. When `sniff` is set (public shares, a less-trusted audience), the | ||
| * served content type is derived from the bytes and non-raster content is refused with 404; otherwise the | ||
| * stored content type is served, matching the in-app serve route. | ||
| */ | ||
| export async function serveInlineImage( | ||
| image: ResolvedInlineImage, | ||
| { sniff }: { sniff: boolean } | ||
| ): Promise<NextResponse> { | ||
| const buffer = await downloadFile({ key: image.key, context: 'workspace' }) | ||
|
|
||
| let contentType = image.contentType | ||
| if (sniff) { | ||
| const sniffed = sniffImageContentType(buffer) | ||
| if (!sniffed) { | ||
| logger.warn('Embedded reference is not a renderable image', { key: image.key }) | ||
| throw new FileNotFoundError('Not found') | ||
| } | ||
| contentType = sniffed | ||
| } | ||
|
|
||
| return createFileResponse({ | ||
| buffer, | ||
| contentType, | ||
| filename: image.filename, | ||
| cacheControl: INLINE_CACHE_CONTROL, | ||
| }) | ||
| } |
77 changes: 77 additions & 0 deletions
77
apps/sim/app/api/workspaces/[id]/files/inline/route.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockGetSession, mockGetPerms, mockResolveImage, mockDownloadFile } = vi.hoisted(() => ({ | ||
| mockGetSession: vi.fn(), | ||
| mockGetPerms: vi.fn(), | ||
| mockResolveImage: vi.fn(), | ||
| mockDownloadFile: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/auth', () => ({ | ||
| auth: { api: { getSession: vi.fn() } }, | ||
| getSession: mockGetSession, | ||
| })) | ||
| vi.mock('@/lib/workspaces/permissions/utils', () => ({ getUserEntityPermissions: mockGetPerms })) | ||
| vi.mock('@/lib/uploads/server/inline-image', () => ({ | ||
| resolveWorkspaceInlineImage: mockResolveImage, | ||
| })) | ||
| vi.mock('@/lib/uploads/core/storage-service', () => ({ downloadFile: mockDownloadFile })) | ||
|
|
||
| import { GET } from '@/app/api/workspaces/[id]/files/inline/route' | ||
|
|
||
| const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]) | ||
| const params = { params: Promise.resolve({ id: 'ws-1' }) } | ||
| const req = (q: string) => new NextRequest(`http://localhost/api/workspaces/ws-1/files/inline?${q}`) | ||
|
|
||
| describe('GET /api/workspaces/[id]/files/inline', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockGetSession.mockResolvedValue({ user: { id: 'u1' } }) | ||
| mockGetPerms.mockResolvedValue('read') | ||
| mockResolveImage.mockResolvedValue({ | ||
| key: 'workspace/ws-1/x-photo.png', | ||
| contentType: 'image/png', | ||
| filename: 'photo.png', | ||
| }) | ||
| mockDownloadFile.mockResolvedValue(PNG) | ||
| }) | ||
|
|
||
| it('serves a workspace-scoped image by fileId', async () => { | ||
| const res = await GET(req('fileId=wf_abc'), params) | ||
| expect(res.status).toBe(200) | ||
| expect(mockResolveImage).toHaveBeenCalledWith('ws-1', { fileId: 'wf_abc' }) | ||
| }) | ||
|
|
||
| it('serves a workspace-scoped image by key', async () => { | ||
| const res = await GET(req(`key=${encodeURIComponent('workspace/ws-1/x-photo.png')}`), params) | ||
| expect(res.status).toBe(200) | ||
| }) | ||
|
|
||
| it('404s when the reference does not resolve in the workspace (cross-workspace)', async () => { | ||
| mockResolveImage.mockResolvedValue(null) | ||
| const res = await GET(req('fileId=wf_other'), params) | ||
| expect(res.status).toBe(404) | ||
| }) | ||
|
|
||
| it('404s without workspace membership, before resolving the file', async () => { | ||
| mockGetPerms.mockResolvedValue(null) | ||
| const res = await GET(req('fileId=wf_abc'), params) | ||
| expect(res.status).toBe(404) | ||
| expect(mockResolveImage).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('401s without a session', async () => { | ||
| mockGetSession.mockResolvedValue(null) | ||
| const res = await GET(req('fileId=wf_abc'), params) | ||
| expect(res.status).toBe(401) | ||
| }) | ||
|
|
||
| it('400s when neither key nor fileId is provided', async () => { | ||
| const res = await GET(req(''), params) | ||
| expect(res.status).toBe(400) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.