Skip to content

Commit 3d9c993

Browse files
authored
fix(knowledge-wh): fixed authentication error on webhook trigger
fix(knowledge-wh): fixed authentication error on webhook trigger
1 parent e557499 commit 3d9c993

File tree

5 files changed

+51
-28
lines changed

5 files changed

+51
-28
lines changed

apps/sim/app/api/knowledge/[id]/documents/[documentId]/chunks/route.ts

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { type NextRequest, NextResponse } from 'next/server'
44
import { z } from 'zod'
55
import { getSession } from '@/lib/auth'
66
import { createLogger } from '@/lib/logs/console-logger'
7+
import { getUserId } from '@/app/api/auth/oauth/utils'
78
import { db } from '@/db'
89
import { document, embedding } from '@/db/schema'
910
import { checkDocumentAccess, generateEmbeddings } from '../../../../utils'
@@ -158,13 +159,19 @@ export async function POST(
158159
const { id: knowledgeBaseId, documentId } = await params
159160

160161
try {
161-
const session = await getSession()
162-
if (!session?.user?.id) {
163-
logger.warn(`[${requestId}] Unauthorized chunk creation attempt`)
164-
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
162+
const body = await req.json()
163+
const { workflowId, ...searchParams } = body
164+
165+
const userId = await getUserId(requestId, workflowId)
166+
167+
if (!userId) {
168+
const errorMessage = workflowId ? 'Workflow not found' : 'Unauthorized'
169+
const statusCode = workflowId ? 404 : 401
170+
logger.warn(`[${requestId}] Authentication failed: ${errorMessage}`)
171+
return NextResponse.json({ error: errorMessage }, { status: statusCode })
165172
}
166173

167-
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, session.user.id)
174+
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, userId)
168175

169176
if (!accessCheck.hasAccess) {
170177
if (accessCheck.notFound) {
@@ -174,7 +181,7 @@ export async function POST(
174181
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
175182
}
176183
logger.warn(
177-
`[${requestId}] User ${session.user.id} attempted unauthorized chunk creation: ${accessCheck.reason}`
184+
`[${requestId}] User ${userId} attempted unauthorized chunk creation: ${accessCheck.reason}`
178185
)
179186
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
180187
}
@@ -194,10 +201,8 @@ export async function POST(
194201
return NextResponse.json({ error: 'Cannot add chunks to failed document' }, { status: 400 })
195202
}
196203

197-
const body = await req.json()
198-
199204
try {
200-
const validatedData = CreateChunkSchema.parse(body)
205+
const validatedData = CreateChunkSchema.parse(searchParams)
201206

202207
// Generate embedding for the content first (outside transaction for performance)
203208
logger.info(`[${requestId}] Generating embedding for manual chunk`)

apps/sim/app/api/knowledge/search/route.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { and, eq, isNull, sql } from 'drizzle-orm'
22
import { type NextRequest, NextResponse } from 'next/server'
33
import { z } from 'zod'
4-
import { getSession } from '@/lib/auth'
54
import { retryWithExponentialBackoff } from '@/lib/documents/utils'
65
import { env } from '@/lib/env'
76
import { createLogger } from '@/lib/logs/console-logger'
7+
import { getUserId } from '@/app/api/auth/oauth/utils'
88
import { db } from '@/db'
99
import { embedding, knowledgeBase } from '@/db/schema'
1010

@@ -87,16 +87,20 @@ export async function POST(request: NextRequest) {
8787
try {
8888
logger.info(`[${requestId}] Processing vector search request`)
8989

90-
const session = await getSession()
91-
if (!session?.user?.id) {
92-
logger.warn(`[${requestId}] Unauthorized vector search attempt`)
93-
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
94-
}
95-
9690
const body = await request.json()
91+
const { workflowId, ...searchParams } = body
92+
93+
const userId = await getUserId(requestId, workflowId)
94+
95+
if (!userId) {
96+
const errorMessage = workflowId ? 'Workflow not found' : 'Unauthorized'
97+
const statusCode = workflowId ? 404 : 401
98+
logger.warn(`[${requestId}] Authentication failed: ${errorMessage}`)
99+
return NextResponse.json({ error: errorMessage }, { status: statusCode })
100+
}
97101

98102
try {
99-
const validatedData = VectorSearchSchema.parse(body)
103+
const validatedData = VectorSearchSchema.parse(searchParams)
100104

101105
// Verify the knowledge base exists and user has access
102106
const kb = await db
@@ -105,7 +109,7 @@ export async function POST(request: NextRequest) {
105109
.where(
106110
and(
107111
eq(knowledgeBase.id, validatedData.knowledgeBaseId),
108-
eq(knowledgeBase.userId, session.user.id),
112+
eq(knowledgeBase.userId, userId),
109113
isNull(knowledgeBase.deletedAt)
110114
)
111115
)

apps/sim/lib/webhooks/utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -674,7 +674,7 @@ export async function executeWorkflowFromPayload(
674674
serializedWorkflow,
675675
processedBlockStates,
676676
decryptedEnvVars,
677-
input, // Use the provided input (might be single event or batch)
677+
input,
678678
workflowVariables
679679
)
680680

apps/sim/tools/knowledge/search.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,18 @@ export const knowledgeSearchTool: ToolConfig<any, KnowledgeSearchResponse> = {
2929
headers: () => ({
3030
'Content-Type': 'application/json',
3131
}),
32-
body: (params) => ({
33-
knowledgeBaseId: params.knowledgeBaseId,
34-
query: params.query,
35-
topK: params.topK ? Number.parseInt(params.topK.toString()) : 10,
36-
}),
32+
body: (params) => {
33+
const workflowId = params._context?.workflowId
34+
35+
const requestBody = {
36+
knowledgeBaseId: params.knowledgeBaseId,
37+
query: params.query,
38+
topK: params.topK ? Number.parseInt(params.topK.toString()) : 10,
39+
...(workflowId && { workflowId }),
40+
}
41+
42+
return requestBody
43+
},
3744
isInternalRoute: true,
3845
},
3946
transformResponse: async (response): Promise<KnowledgeSearchResponse> => {

apps/sim/tools/knowledge/upload_chunk.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,17 @@ export const knowledgeUploadChunkTool: ToolConfig<any, KnowledgeUploadChunkRespo
3030
headers: () => ({
3131
'Content-Type': 'application/json',
3232
}),
33-
body: (params) => ({
34-
content: params.content,
35-
enabled: true,
36-
}),
33+
body: (params) => {
34+
const workflowId = params._context?.workflowId
35+
36+
const requestBody = {
37+
content: params.content,
38+
enabled: true,
39+
...(workflowId && { workflowId }),
40+
}
41+
42+
return requestBody
43+
},
3744
isInternalRoute: true,
3845
},
3946
transformResponse: async (response): Promise<KnowledgeUploadChunkResponse> => {

0 commit comments

Comments
 (0)