Skip to content

An AI-powered search engine with a generative UI

Address signed file URL review feedback

Yoshiki Miura8414755574b7
diff --git a/lib/storage/__tests__/r2-client.test.ts b/lib/storage/__tests__/r2-client.test.ts
index 3eb83f23..396d0071 100644
--- a/lib/storage/__tests__/r2-client.test.ts
+++ b/lib/storage/__tests__/r2-client.test.ts
@@ -164,4 +164,76 @@ describe('R2 client', () => {
Key: 'user-id/file.png'
})
})
+
+ it('preserves existing file URLs when no object key is available', async () => {
+ const { signFilePartUrls } = await importR2Client()
+
+ await expect(
+ signFilePartUrls([
+ {
+ type: 'file',
+ mediaType: 'image/png',
+ filename: 'external.png',
+ url: 'https://external.example.com/external.png'
+ }
+ ])
+ ).resolves.toEqual([
+ {
+ type: 'file',
+ mediaType: 'image/png',
+ filename: 'external.png',
+ url: 'https://external.example.com/external.png'
+ }
+ ])
+ })
+
+ it('rejects object keys outside the allowed prefix', async () => {
+ const { signFilePartUrls } = await importR2Client()
+
+ await expect(
+ signFilePartUrls(
+ [
+ {
+ type: 'file',
+ key: 'other-user/chats/chat-123/file.png',
+ mediaType: 'image/png',
+ filename: 'file.png',
+ url: ''
+ }
+ ],
+ { allowedKeyPrefix: 'user-123/chats/chat-123/' }
+ )
+ ).rejects.toThrow('File object key is not allowed for this chat')
+
+ expect(s3Mocks.getSignedUrl).not.toHaveBeenCalled()
+ })
+
+ it('signs object keys inside the allowed prefix', async () => {
+ s3Mocks.getSignedUrl.mockResolvedValue('https://signed.example.com/file')
+
+ const { signFilePartUrls } = await importR2Client()
+
+ await expect(
+ signFilePartUrls(
+ [
+ {
+ type: 'file',
+ key: 'user-123/chats/chat-123/file.png',
+ mediaType: 'image/png',
+ filename: 'file.png',
+ url: ''
+ }
+ ],
+ { allowedKeyPrefix: 'user-123/chats/chat-123/' }
+ )
+ ).resolves.toEqual([
+ {
+ type: 'file',
+ key: 'user-123/chats/chat-123/file.png',
+ mediaType: 'image/png',
+ filename: 'file.png',
+ url: 'https://signed.example.com/file'
+ }
+ ])
+ })
})
diff --git a/lib/storage/r2-client.ts b/lib/storage/r2-client.ts
index 136fd0e6..39d243c1 100644
--- a/lib/storage/r2-client.ts
+++ b/lib/storage/r2-client.ts
@@ -20,6 +20,10 @@ export const R2_SIGNED_URL_EXPIRES_SECONDS =
let _r2Client: S3Client | null = null
+type SignFilePartUrlsOptions = {
+ allowedKeyPrefix?: string
+}
+
export function getR2Client(): S3Client {
if (_r2Client) {
return _r2Client
@@ -68,6 +72,17 @@ function normalizeObjectKey(key: string) {
return key.replace(/^\/+/, '')
}
+export function getChatFileObjectKeyPrefix(userId: string, chatId: string) {
+ return `${normalizeObjectKey(userId)}/chats/${normalizeObjectKey(chatId)}/`
+}
+
+function isObjectKeyWithinPrefix(key: string, prefix: string) {
+ const normalizedKey = normalizeObjectKey(key)
+ const normalizedPrefix = normalizeObjectKey(prefix).replace(/\/+$/, '')
+
+ return normalizedPrefix.length > 0 && normalizedKey.startsWith(`${normalizedPrefix}/`)
+}
+
export async function getSignedFileUrl(
key: string,
expiresIn = R2_SIGNED_URL_EXPIRES_SECONDS
@@ -87,7 +102,10 @@ export async function getSignedFileUrl(
)
}
-export async function signFilePartUrls(parts: any[] = []) {
+export async function signFilePartUrls(
+ parts: any[] = [],
+ options: SignFilePartUrlsOptions = {}
+) {
return Promise.all(
parts.map(async part => {
if (part?.type !== 'file') {
@@ -95,7 +113,14 @@ export async function signFilePartUrls(parts: any[] = []) {
}
if (!part.key) {
- return { ...part, url: '' }
+ return part
+ }
+
+ if (
+ options.allowedKeyPrefix &&
+ !isObjectKeyWithinPrefix(part.key, options.allowedKeyPrefix)
+ ) {
+ throw new Error('File object key is not allowed for this chat')
}
try {
diff --git a/lib/streaming/helpers/__tests__/prepare-messages.test.ts b/lib/streaming/helpers/__tests__/prepare-messages.test.ts
index 9159b03f..2e32b09f 100644
--- a/lib/streaming/helpers/__tests__/prepare-messages.test.ts
+++ b/lib/streaming/helpers/__tests__/prepare-messages.test.ts
@@ -7,6 +7,7 @@ import {
upsertMessage
} from '@/lib/actions/chat'
import type { Chat } from '@/lib/db/schema'
+import { signFilePartUrls } from '@/lib/storage/r2-client'
import type { UIMessage } from '@/lib/types/ai'
import { prepareMessages } from '../prepare-messages'
@@ -21,6 +22,12 @@ vi.mock('@/lib/db/schema', async () => {
generateId: vi.fn(() => 'generated-id-123')
}
})
+vi.mock('@/lib/storage/r2-client', () => ({
+ getChatFileObjectKeyPrefix: vi.fn(
+ (userId: string, chatId: string) => `${userId}/chats/${chatId}/`
+ ),
+ signFilePartUrls: vi.fn(async (parts: any[]) => parts)
+}))
describe('prepareMessages', () => {
const userId = 'user-123'
@@ -374,6 +381,9 @@ describe('prepareMessages', () => {
...newMessage,
id: 'msg-1'
})
+ expect(signFilePartUrls).toHaveBeenCalledWith(newMessage.parts, {
+ allowedKeyPrefix: 'user-123/chats/chat-123/'
+ })
})
it('should append message to existing chat', async () => {
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index b4039f26..d71bc0bd 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -8,7 +8,10 @@ import {
upsertMessage
} from '@/lib/actions/chat'
import { generateId } from '@/lib/db/schema'
-import { signFilePartUrls } from '@/lib/storage/r2-client'
+import {
+ getChatFileObjectKeyPrefix,
+ signFilePartUrls
+} from '@/lib/storage/r2-client'
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
import type { StreamContext } from './types'
@@ -87,7 +90,9 @@ export async function prepareMessages(
const messageWithId = {
...message,
id: message.id || generateId(),
- parts: await signFilePartUrls(message.parts)
+ parts: await signFilePartUrls(message.parts, {
+ allowedKeyPrefix: getChatFileObjectKeyPrefix(userId, chatId)
+ })
}
// Optimize for new chats: create chat and save message together