OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(api): the assistant only serves a conversation to its owner
Carl-Gerhard Lindesvärd6918630c9bef
diff --git a/packages/core/src/modules/assistant/assistant.routes.test.ts b/packages/core/src/modules/assistant/assistant.routes.test.tsindex 30fdd97b0..10f9069fb 100644--- a/packages/core/src/modules/assistant/assistant.routes.test.ts+++ b/packages/core/src/modules/assistant/assistant.routes.test.ts@@ -33,8 +33,21 @@ mock.module('./assistant.service', () => ({const { assistantRoutes } = await import('./assistant.routes');+const OWN_CONVERSATION_ID = 'conv_own';+const OTHER_USER_CONVERSATION_ID = 'conv_other';+const conversationsById: Record<string, { userId: string }> = {+ [OWN_CONVERSATION_ID]: { userId: 'user_1' },+ [OTHER_USER_CONVERSATION_ID]: { userId: 'user_2' },+};+const findConversation = mock(({ where }: { where: { id: string } }) =>+ Promise.resolve(conversationsById[where.id] ?? null)+);+function buildApp() {const { deps } = stubAppDeps();+ deps.db = {+ conversation: { findUnique: findConversation },+ } as unknown as typeof deps.db;return new Elysia().use(requestLogging(deps)).use(assistantRoutes(deps));}@@ -44,8 +57,17 @@ beforeEach(() => {app = buildApp();session = { userId: 'user_1' };seenBodies.length = 0;+ findConversation.mockClear();});+function get(path: string) {+ return app.handle(+ new Request(`http://localhost${path}`, {+ headers: { cookie: 'session=s' },+ })+ );+}+function post(path: string, body: unknown) {return app.handle(new Request(`http://localhost${path}`, {@@ -76,3 +98,45 @@ test('no session -> 401', async () => {const response = await post('/ai/agents/__titler/run', { input: 'hi' });expect(response.status).toBe(401);});++test("the titler cannot load another user's conversation", async () => {+ const response = await get(+ `/ai/agents/__titler/conversations/${OTHER_USER_CONVERSATION_ID}`+ );+ expect(response.status).toBe(404);+ expect(seenBodies).toEqual([]);+});++test('the titler serves nothing but a stateless run', async () => {+ const resume = await get(+ `/ai/agents/__titler/conversations/${OWN_CONVERSATION_ID}/resume`+ );+ const abort = await post('/ai/agents/__titler/runs/run_1/abort', {});+ const withConversation = await post('/ai/agents/__titler/run', {+ input: 'hi',+ conversationId: OWN_CONVERSATION_ID,+ });+ expect([resume.status, abort.status, withConversation.status]).toEqual([+ 404, 404, 404,+ ]);+ expect(seenBodies).toEqual([]);+});++test("loading another user's conversation is a 404", async () => {+ const response = await get(+ `/ai/agents/gpt/conversations/${OTHER_USER_CONVERSATION_ID}`+ );+ expect(response.status).toBe(404);+ expect(findConversation).toHaveBeenCalledTimes(1);+});++test("a run cannot continue another user's conversation", async () => {+ const response = await post('/ai/agents/gpt/run', {+ input: 'hi',+ conversationId: OTHER_USER_CONVERSATION_ID,+ context: { projectId: 'p', organizationId: 'o' },+ });+ expect(response.status).toBe(404);+ expect(findConversation).toHaveBeenCalledTimes(1);+ expect(seenBodies).toEqual([]);+});diff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.tsindex 9fb9f57a7..4179e95b5 100644--- a/packages/core/src/modules/assistant/assistant.routes.ts+++ b/packages/core/src/modules/assistant/assistant.routes.ts@@ -11,10 +11,20 @@ import {getSettingsForProject,} from '../organization/organization.service';+const TITLER_AGENT_NAME = '__titler';+interface RunBody {+ conversationId?: string;context?: { projectId?: string; organizationId?: string };}+function readRunBody(request: Request): Promise<RunBody | null> {+ return request+ .clone()+ .json()+ .catch(() => null) as Promise<RunBody | null>;+}+export const assistantRoutes = defineRoutes((app) =>app.all('/ai/agents/*',@@ -37,19 +47,32 @@ export const assistantRoutes = defineRoutes((app) =>const route = segments[1] ?? '';const routeId = segments[2] ?? '';- // The internal `__titler` agent has no project context — skip the- // access check; session auth is enough.- if (agentName === '__titler') {+ // The store loads conversations by id alone, whatever the agent name.+ const isOwnConversation = async (conversationId: string) => {+ const conv =+ await ctx.services.conversation.getConversationById(conversationId);+ return !conv || conv.userId === userId;+ };++ // The titler has no project context, so it may only run statelessly:+ // any other route or a `conversationId` would load a conversation+ // without the ownership check below.+ if (agentName === TITLER_AGENT_NAME) {+ const isStatelessRun =+ request.method === 'POST' &&+ route === 'run' &&+ segments.length === 2 &&+ !(await readRunBody(request))?.conversationId;+ if (!isStatelessRun) {+ return status(404, { message: 'Not found' });+ }return chatApp.handler(request);}- // Conversation hydration: verify ownership if the row already exists.// A brand-new chat (no row yet) falls through to the agent handler,// whose `ConversationStore.load()` returns null.if (route === 'conversations' && routeId) {- const conv =- await ctx.services.conversation.getConversationById(routeId);- if (conv && conv.userId !== userId) {+ if (!(await isOwnConversation(routeId))) {return status(404, { message: 'Conversation not found' });}return chatApp.handler(request);@@ -57,10 +80,13 @@ export const assistantRoutes = defineRoutes((app) =>// Everything else (primarily `POST /:name/run`) is an active run and// must carry `context.projectId` + `context.organizationId`.- const body = (await request- .clone()- .json()- .catch(() => null)) as RunBody | null;+ const body = await readRunBody(request);+ if (+ body?.conversationId &&+ !(await isOwnConversation(body.conversationId))+ ) {+ return status(404, { message: 'Conversation not found' });+ }const projectId = body?.context?.projectId;const organizationIdFromBody = body?.context?.organizationId;