Skip to content

Commit 1394733

Browse files
authored
fix(copilot): only accept feedback on the caller's own chat (#10429)
POST /api/copilot/feedback stored a row for any chatId the caller sent. It now runs through an authorized chat use case that resolves the chat with resolveOwnedChatContext, so a foreign or unknown chat answers the same 404 and nothing is stored. Organization assistant chats keep working for their owner.
1 parent 3b11316 commit 1394733

4 files changed

Lines changed: 238 additions & 105 deletions

File tree

‎apps/sim/app/api/copilot/feedback/route.ts‎

Lines changed: 34 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
import { db } from '@sim/db'
22
import { copilotFeedback } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
4-
import { getErrorMessage } from '@sim/utils/errors'
54
import { eq } from 'drizzle-orm'
6-
import { type NextRequest, NextResponse } from 'next/server'
5+
import { NextResponse } from 'next/server'
76
import { submitCopilotFeedbackContract } from '@/lib/api/contracts'
8-
import { parseRequest, validationErrorResponse } from '@/lib/api/server'
7+
import {
8+
defineInternalJsonRoute,
9+
internalJsonPresenters,
10+
internalOrchestrationErrorPolicy,
11+
internalRateLimits,
12+
internalSessionAuth,
13+
} from '@/lib/api/server/routes'
914
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
15+
import { submitChatFeedback } from '@/lib/mothership/chat/application/submit-feedback'
1016
import {
1117
authenticateCopilotRequestSessionOnly,
1218
createInternalServerErrorResponse,
@@ -17,104 +23,32 @@ import { captureServerEvent } from '@/lib/posthog/server'
1723

1824
const logger = createLogger('CopilotFeedbackAPI')
1925

20-
/**
21-
* POST /api/copilot/feedback
22-
* Submit feedback for a copilot interaction
23-
*/
24-
export const POST = withRouteHandler(async (req: NextRequest) => {
25-
const tracker = createRequestTracker()
26-
27-
try {
28-
// Authenticate user using the same pattern as other copilot routes
29-
const { userId: authenticatedUserId, isAuthenticated } =
30-
await authenticateCopilotRequestSessionOnly()
31-
32-
if (!isAuthenticated || !authenticatedUserId) {
33-
return createUnauthorizedResponse()
34-
}
35-
36-
const parsed = await parseRequest(
37-
submitCopilotFeedbackContract,
38-
req,
39-
{},
40-
{
41-
invalidJson: 'throw',
42-
validationErrorResponse: (error) => {
43-
logger.error('Validation error:', {
44-
requestId: tracker.requestId,
45-
duration: tracker.getDuration(),
46-
errors: error.issues,
47-
})
48-
return validationErrorResponse(error, 'Invalid request data')
49-
},
50-
}
51-
)
52-
if (!parsed.success) return parsed.response
53-
54-
const { chatId, userQuery, agentResponse, isPositiveFeedback, feedback, workflowYaml } =
55-
parsed.data.body
56-
57-
logger.info('Processing copilot feedback submission', {
58-
requestId: tracker.requestId,
59-
userId: authenticatedUserId,
60-
chatId,
61-
isPositiveFeedback,
62-
userQueryLength: userQuery.length,
63-
agentResponseLength: agentResponse.length,
64-
hasFeedback: !!feedback,
65-
hasWorkflowYaml: !!workflowYaml,
66-
workflowYamlLength: workflowYaml?.length || 0,
26+
/** Records the caller's rating of an assistant reply in one of their own chats. */
27+
export const POST = defineInternalJsonRoute({
28+
contract: submitCopilotFeedbackContract,
29+
operation: submitChatFeedback.operation,
30+
auth: internalSessionAuth,
31+
rateLimit: internalRateLimits.none({
32+
reason: 'Each rated reply in the caller’s own chat adds one feedback row.',
33+
}),
34+
errorPolicy: internalOrchestrationErrorPolicy,
35+
mapInput: ({ body }) => ({
36+
chatId: body.chatId,
37+
userQuery: body.userQuery,
38+
agentResponse: body.agentResponse,
39+
isPositive: body.isPositiveFeedback,
40+
feedback: body.feedback,
41+
workflowYaml: body.workflowYaml,
42+
}),
43+
useCase: submitChatFeedback,
44+
present: internalJsonPresenters.withSuccess,
45+
onSuccess: ({ principal, input }) => {
46+
captureServerEvent(principal.userId, 'copilot_feedback_submitted', {
47+
is_positive: input.isPositive,
48+
has_text_feedback: !!input.feedback,
49+
has_workflow_yaml: !!input.workflowYaml,
6750
})
68-
69-
// Insert feedback into the database
70-
const [feedbackRecord] = await db
71-
.insert(copilotFeedback)
72-
.values({
73-
userId: authenticatedUserId,
74-
chatId,
75-
userQuery,
76-
agentResponse,
77-
isPositive: isPositiveFeedback,
78-
feedback: feedback || null,
79-
workflowYaml: workflowYaml || null,
80-
})
81-
.returning()
82-
83-
logger.info('Successfully saved copilot feedback', {
84-
requestId: tracker.requestId,
85-
feedbackId: feedbackRecord.feedbackId,
86-
userId: authenticatedUserId,
87-
isPositive: isPositiveFeedback,
88-
duration: tracker.getDuration(),
89-
})
90-
91-
captureServerEvent(authenticatedUserId, 'copilot_feedback_submitted', {
92-
is_positive: isPositiveFeedback,
93-
has_text_feedback: !!feedback,
94-
has_workflow_yaml: !!workflowYaml,
95-
})
96-
97-
return NextResponse.json({
98-
success: true,
99-
feedbackId: feedbackRecord.feedbackId,
100-
message: 'Feedback submitted successfully',
101-
metadata: {
102-
requestId: tracker.requestId,
103-
duration: tracker.getDuration(),
104-
},
105-
})
106-
} catch (error) {
107-
const duration = tracker.getDuration()
108-
109-
logger.error('Error submitting copilot feedback:', {
110-
requestId: tracker.requestId,
111-
duration,
112-
error: getErrorMessage(error, 'Unknown error'),
113-
stack: error instanceof Error ? error.stack : undefined,
114-
})
115-
116-
return createInternalServerErrorResponse('Failed to submit feedback')
117-
}
51+
},
11852
})
11953

12054
/**

‎apps/sim/lib/api/contracts/copilot.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -290,11 +290,6 @@ export const submitCopilotFeedbackContract = defineRouteContract({
290290
schema: z.object({
291291
success: z.literal(true),
292292
feedbackId: z.string(),
293-
message: z.string(),
294-
metadata: z.object({
295-
requestId: z.string(),
296-
duration: z.number(),
297-
}),
298293
}),
299294
},
300295
})
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
/** Drives POST /api/copilot/feedback against real PostgreSQL rows to prove feedback stays on the caller's own chats. */
2+
import { db } from '@sim/db'
3+
import {
4+
copilotChats,
5+
copilotFeedback,
6+
member,
7+
organization,
8+
permissions,
9+
user,
10+
workspace,
11+
} from '@sim/db/schema'
12+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
13+
import { authMock, authMockFns } from '@sim/testing/mocks/auth.mock'
14+
import { generateId } from '@sim/utils/id'
15+
import { eq, inArray } from 'drizzle-orm'
16+
import { NextRequest } from 'next/server'
17+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
18+
import { POST } from '@/app/api/copilot/feedback/route'
19+
20+
vi.mock('@/lib/auth', () => authMock)
21+
22+
const ownerId = generateId()
23+
const outsiderId = generateId()
24+
const workspaceId = generateId()
25+
const organizationId = generateId()
26+
const workspaceChatId = generateId()
27+
const organizationChatId = generateId()
28+
29+
function submitAs(userId: string, chatId: string) {
30+
authMockFns.mockGetSession.mockResolvedValueOnce({
31+
user: { id: userId },
32+
session: { id: generateId() },
33+
})
34+
return POST(
35+
new NextRequest('http://localhost:3000/api/copilot/feedback', {
36+
method: 'POST',
37+
headers: { 'content-type': 'application/json' },
38+
body: JSON.stringify({
39+
chatId,
40+
userQuery: 'What changed?',
41+
agentResponse: 'Three files changed.',
42+
isPositiveFeedback: false,
43+
feedback: 'Missed one file',
44+
}),
45+
})
46+
)
47+
}
48+
49+
async function feedbackRows(chatId: string) {
50+
return db
51+
.select({ userId: copilotFeedback.userId })
52+
.from(copilotFeedback)
53+
.where(eq(copilotFeedback.chatId, chatId))
54+
}
55+
56+
beforeAll(async () => {
57+
const now = new Date()
58+
await db.insert(user).values(
59+
[ownerId, outsiderId].map((id) => ({
60+
id,
61+
name: 'Chat feedback fixture',
62+
email: `${id}@chat-feedback.test`,
63+
emailVerified: true,
64+
createdAt: now,
65+
updatedAt: now,
66+
}))
67+
)
68+
await insertWorkspaceFixture(db, {
69+
id: workspaceId,
70+
name: 'Chat feedback fixture',
71+
ownerId,
72+
billedAccountUserId: ownerId,
73+
})
74+
await db.insert(permissions).values(
75+
[ownerId, outsiderId].map((userId) => ({
76+
id: generateId(),
77+
userId,
78+
entityType: 'workspace' as const,
79+
entityId: workspaceId,
80+
permissionType: 'admin' as const,
81+
}))
82+
)
83+
await db.insert(organization).values({
84+
id: organizationId,
85+
name: 'Chat feedback fixture',
86+
slug: organizationId,
87+
createdAt: now,
88+
})
89+
await db.insert(member).values(
90+
[ownerId, outsiderId].map((userId) => ({
91+
id: generateId(),
92+
userId,
93+
organizationId,
94+
role: 'member',
95+
createdAt: now,
96+
}))
97+
)
98+
await db.insert(copilotChats).values([
99+
{ id: workspaceChatId, userId: ownerId, workspaceId, type: 'mothership' },
100+
{ id: organizationChatId, userId: ownerId, organizationId, type: 'mothership' },
101+
])
102+
})
103+
104+
afterAll(async () => {
105+
await db
106+
.delete(copilotChats)
107+
.where(inArray(copilotChats.id, [workspaceChatId, organizationChatId]))
108+
await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId))
109+
await db.delete(organization).where(eq(organization.id, organizationId))
110+
await db.delete(user).where(inArray(user.id, [ownerId, outsiderId]))
111+
await db.$client.end()
112+
})
113+
114+
describe('copilot feedback stays on the caller’s own chats', () => {
115+
it('records feedback on the owner’s workspace and organization chats', async () => {
116+
for (const chatId of [workspaceChatId, organizationChatId]) {
117+
const response = await submitAs(ownerId, chatId)
118+
expect(response.status).toBe(200)
119+
expect(await response.json()).toMatchObject({ success: true, feedbackId: expect.any(String) })
120+
expect(await feedbackRows(chatId)).toEqual([{ userId: ownerId }])
121+
}
122+
})
123+
124+
it('answers a member’s foreign chat exactly like an unknown chat and stores nothing', async () => {
125+
const before = await Promise.all([workspaceChatId, organizationChatId].map(feedbackRows))
126+
const foreign = await submitAs(outsiderId, workspaceChatId)
127+
const foreignOrganization = await submitAs(outsiderId, organizationChatId)
128+
const unknown = await submitAs(outsiderId, generateId())
129+
130+
expect(foreign.status).toBe(404)
131+
expect(foreignOrganization.status).toBe(404)
132+
expect(unknown.status).toBe(404)
133+
const { error } = await unknown.json()
134+
expect(error).toBe('Chat not found')
135+
expect((await foreign.json()).error).toBe(error)
136+
expect((await foreignOrganization.json()).error).toBe(error)
137+
expect(await Promise.all([workspaceChatId, organizationChatId].map(feedbackRows))).toEqual(
138+
before
139+
)
140+
})
141+
})
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import type { SessionPrincipal } from '@sim/auth/principal'
2+
import { db } from '@sim/db'
3+
import { copilotFeedback } from '@sim/db/schema'
4+
import { defineWorkspaceOperation } from '@/lib/core/application'
5+
import { defineOrganizationOperation } from '@/lib/core/application/organization-operation'
6+
import { defineAuthorizedChatUseCase } from '@/lib/mothership/chat/application/authorized-chat-use-case'
7+
import { resolveOwnedChatContext } from '@/lib/mothership/chat/application/context'
8+
9+
interface SubmitChatFeedbackInput {
10+
chatId: string
11+
userQuery: string
12+
agentResponse: string
13+
isPositive: boolean
14+
feedback?: string
15+
workflowYaml?: string
16+
}
17+
18+
/**
19+
* Records the owner's rating of an assistant reply. A chat the caller does not own resolves to
20+
* not found, the same as an unknown id, so feedback never attaches to someone else's chat.
21+
*/
22+
export const submitChatFeedback = defineAuthorizedChatUseCase({
23+
// permission-group-exempt: rating a reply in the caller's own chat starts no turn and reads nothing new
24+
operation: defineWorkspaceOperation({
25+
id: 'mothership.chats.submit_feedback',
26+
minimumRole: 'read',
27+
workspaceApiKey: 'deny',
28+
capability: 'none',
29+
principalKinds: ['session'],
30+
}),
31+
/** permission-group-exempt: rating a reply in the caller's own chat starts no turn and reads nothing new. */
32+
organizationOperation: defineOrganizationOperation({
33+
id: 'mothership.chats.submit_feedback',
34+
minimumRole: 'member',
35+
capability: 'none',
36+
principalKinds: ['session'],
37+
}),
38+
resolveContext({
39+
principal,
40+
input,
41+
}: {
42+
principal: SessionPrincipal
43+
input: SubmitChatFeedbackInput
44+
}) {
45+
return resolveOwnedChatContext(principal, input.chatId)
46+
},
47+
authorizationOptions: {},
48+
async execute({ context, input }) {
49+
const [{ feedbackId }] = await db
50+
.insert(copilotFeedback)
51+
.values({
52+
userId: context.userId,
53+
chatId: context.chatId,
54+
userQuery: input.userQuery,
55+
agentResponse: input.agentResponse,
56+
isPositive: input.isPositive,
57+
feedback: input.feedback || null,
58+
workflowYaml: input.workflowYaml || null,
59+
})
60+
.returning({ feedbackId: copilotFeedback.feedbackId })
61+
return { feedbackId }
62+
},
63+
})

0 commit comments

Comments
 (0)