chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,413 @@
|
||||
/**
|
||||
* Tests for custom tools API routes
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import {
|
||||
authMockFns,
|
||||
createMockRequest,
|
||||
hybridAuthMockFns,
|
||||
permissionsMock,
|
||||
permissionsMockFns,
|
||||
workflowAuthzMockFns,
|
||||
workflowsUtilsMock,
|
||||
} from '@sim/testing'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockSelect,
|
||||
mockFrom,
|
||||
mockWhere,
|
||||
mockOrderBy,
|
||||
mockInsert,
|
||||
mockValues,
|
||||
mockUpdate,
|
||||
mockSet,
|
||||
mockDelete,
|
||||
mockLimit,
|
||||
mockUpsertCustomTools,
|
||||
} = vi.hoisted(() => {
|
||||
return {
|
||||
mockSelect: vi.fn(),
|
||||
mockFrom: vi.fn(),
|
||||
mockWhere: vi.fn(),
|
||||
mockOrderBy: vi.fn(),
|
||||
mockInsert: vi.fn(),
|
||||
mockValues: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockSet: vi.fn(),
|
||||
mockDelete: vi.fn(),
|
||||
mockLimit: vi.fn(),
|
||||
mockUpsertCustomTools: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
const mockGetUserEntityPermissions = permissionsMockFns.mockGetUserEntityPermissions
|
||||
|
||||
const sampleTools = [
|
||||
{
|
||||
id: 'tool-1',
|
||||
workspaceId: 'workspace-123',
|
||||
userId: 'user-123',
|
||||
title: 'Weather Tool',
|
||||
schema: {
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'getWeather',
|
||||
description: 'Get weather information for a location',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
location: {
|
||||
type: 'string',
|
||||
description: 'The city and state, e.g. San Francisco, CA',
|
||||
},
|
||||
},
|
||||
required: ['location'],
|
||||
},
|
||||
},
|
||||
},
|
||||
code: 'return { temperature: 72, conditions: "sunny" };',
|
||||
createdAt: '2023-01-01T00:00:00.000Z',
|
||||
updatedAt: '2023-01-02T00:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'tool-2',
|
||||
workspaceId: 'workspace-123',
|
||||
userId: 'user-123',
|
||||
title: 'Calculator Tool',
|
||||
schema: {
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'calculator',
|
||||
description: 'Perform basic calculations',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
operation: {
|
||||
type: 'string',
|
||||
description: 'The operation to perform (add, subtract, multiply, divide)',
|
||||
},
|
||||
a: { type: 'number', description: 'First number' },
|
||||
b: { type: 'number', description: 'Second number' },
|
||||
},
|
||||
required: ['operation', 'a', 'b'],
|
||||
},
|
||||
},
|
||||
},
|
||||
code: 'const { operation, a, b } = params; if (operation === "add") return a + b;',
|
||||
createdAt: '2023-02-01T00:00:00.000Z',
|
||||
updatedAt: '2023-02-02T00:00:00.000Z',
|
||||
},
|
||||
]
|
||||
|
||||
vi.mock('@sim/db', () => ({
|
||||
db: {
|
||||
select: (...args: unknown[]) => mockSelect(...args),
|
||||
insert: (...args: unknown[]) => mockInsert(...args),
|
||||
update: (...args: unknown[]) => mockUpdate(...args),
|
||||
delete: (...args: unknown[]) => mockDelete(...args),
|
||||
transaction: vi
|
||||
.fn()
|
||||
.mockImplementation(async (callback: (tx: Record<string, unknown>) => unknown) => {
|
||||
const txMockSelect = vi.fn().mockReturnValue({ from: mockFrom })
|
||||
const txMockInsert = vi.fn().mockReturnValue({ values: mockValues })
|
||||
const txMockUpdate = vi.fn().mockReturnValue({ set: mockSet })
|
||||
const txMockDelete = vi.fn().mockReturnValue({ where: mockWhere })
|
||||
|
||||
const txMockOrderBy = vi.fn().mockImplementation(() => {
|
||||
const queryBuilder = {
|
||||
limit: mockLimit,
|
||||
then: (resolve: (value: typeof sampleTools) => void) => {
|
||||
resolve(sampleTools)
|
||||
return queryBuilder
|
||||
},
|
||||
catch: (_reject: (error: Error) => void) => queryBuilder,
|
||||
}
|
||||
return queryBuilder
|
||||
})
|
||||
|
||||
const txMockWhere = vi.fn().mockImplementation(() => {
|
||||
const queryBuilder = {
|
||||
orderBy: txMockOrderBy,
|
||||
limit: mockLimit,
|
||||
then: (resolve: (value: typeof sampleTools) => void) => {
|
||||
resolve(sampleTools)
|
||||
return queryBuilder
|
||||
},
|
||||
catch: (_reject: (error: Error) => void) => queryBuilder,
|
||||
}
|
||||
return queryBuilder
|
||||
})
|
||||
|
||||
const txMockFrom = vi.fn().mockReturnValue({ where: txMockWhere })
|
||||
txMockSelect.mockReturnValue({ from: txMockFrom })
|
||||
|
||||
return await callback({
|
||||
select: txMockSelect,
|
||||
insert: txMockInsert,
|
||||
update: txMockUpdate,
|
||||
delete: txMockDelete,
|
||||
})
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workspaces/permissions/utils', () => permissionsMock)
|
||||
|
||||
vi.mock('drizzle-orm', () => ({
|
||||
eq: vi.fn().mockImplementation((field: unknown, value: unknown) => ({
|
||||
field,
|
||||
value,
|
||||
operator: 'eq',
|
||||
})),
|
||||
and: vi.fn().mockImplementation((...conditions: unknown[]) => ({
|
||||
operator: 'and',
|
||||
conditions,
|
||||
})),
|
||||
or: vi.fn().mockImplementation((...conditions: unknown[]) => ({
|
||||
operator: 'or',
|
||||
conditions,
|
||||
})),
|
||||
isNull: vi.fn().mockImplementation((field: unknown) => ({ field, operator: 'isNull' })),
|
||||
ne: vi.fn().mockImplementation((field: unknown, value: unknown) => ({
|
||||
field,
|
||||
value,
|
||||
operator: 'ne',
|
||||
})),
|
||||
desc: vi.fn().mockImplementation((field: unknown) => ({ field, operator: 'desc' })),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/custom-tools/operations', () => ({
|
||||
upsertCustomTools: (...args: unknown[]) => mockUpsertCustomTools(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/utils', () => workflowsUtilsMock)
|
||||
|
||||
import { DELETE, GET, POST } from '@/app/api/tools/custom/route'
|
||||
|
||||
describe('Custom Tools API Routes', () => {
|
||||
const mockSession = { user: { id: 'user-123' } }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockSelect.mockReturnValue({ from: mockFrom })
|
||||
mockFrom.mockReturnValue({ where: mockWhere })
|
||||
mockWhere.mockImplementation(() => {
|
||||
const queryBuilder = {
|
||||
orderBy: mockOrderBy,
|
||||
limit: mockLimit,
|
||||
then: (resolve: (value: typeof sampleTools) => void) => {
|
||||
resolve(sampleTools)
|
||||
return queryBuilder
|
||||
},
|
||||
catch: (_reject: (error: Error) => void) => queryBuilder,
|
||||
}
|
||||
return queryBuilder
|
||||
})
|
||||
mockOrderBy.mockImplementation(() => {
|
||||
const queryBuilder = {
|
||||
limit: mockLimit,
|
||||
then: (resolve: (value: typeof sampleTools) => void) => {
|
||||
resolve(sampleTools)
|
||||
return queryBuilder
|
||||
},
|
||||
catch: (_reject: (error: Error) => void) => queryBuilder,
|
||||
}
|
||||
return queryBuilder
|
||||
})
|
||||
mockLimit.mockResolvedValue(sampleTools)
|
||||
mockInsert.mockReturnValue({ values: mockValues })
|
||||
mockValues.mockResolvedValue({ id: 'new-tool-id' })
|
||||
mockUpdate.mockReturnValue({ set: mockSet })
|
||||
mockSet.mockReturnValue({ where: mockWhere })
|
||||
mockDelete.mockReturnValue({ where: mockWhere })
|
||||
|
||||
authMockFns.mockGetSession.mockResolvedValue(mockSession)
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'user-123',
|
||||
authType: 'session',
|
||||
})
|
||||
mockGetUserEntityPermissions.mockResolvedValue('admin')
|
||||
mockUpsertCustomTools.mockResolvedValue(sampleTools)
|
||||
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: true,
|
||||
status: 200,
|
||||
workflow: { workspaceId: 'workspace-123' },
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Test GET endpoint
|
||||
*/
|
||||
describe('GET /api/tools/custom', () => {
|
||||
it('should return tools for authenticated user with workspaceId', async () => {
|
||||
const req = new NextRequest(
|
||||
'http://localhost:3000/api/tools/custom?workspaceId=workspace-123'
|
||||
)
|
||||
|
||||
mockWhere.mockReturnValueOnce({
|
||||
orderBy: mockOrderBy.mockReturnValueOnce(Promise.resolve(sampleTools)),
|
||||
})
|
||||
|
||||
const response = await GET(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('data')
|
||||
expect(data.data).toEqual(sampleTools)
|
||||
|
||||
expect(mockSelect).toHaveBeenCalled()
|
||||
expect(mockFrom).toHaveBeenCalled()
|
||||
expect(mockWhere).toHaveBeenCalled()
|
||||
expect(mockOrderBy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should handle unauthorized access', async () => {
|
||||
const req = new NextRequest(
|
||||
'http://localhost:3000/api/tools/custom?workspaceId=workspace-123'
|
||||
)
|
||||
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'Unauthorized',
|
||||
})
|
||||
|
||||
const response = await GET(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data).toHaveProperty('error', 'Unauthorized')
|
||||
})
|
||||
|
||||
it('should handle workflowId parameter', async () => {
|
||||
const req = new NextRequest('http://localhost:3000/api/tools/custom?workflowId=workflow-123')
|
||||
|
||||
const response = await GET(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('data')
|
||||
|
||||
expect(mockWhere).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Test POST endpoint
|
||||
*/
|
||||
describe('POST /api/tools/custom', () => {
|
||||
it('should reject unauthorized requests', async () => {
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'Unauthorized',
|
||||
})
|
||||
|
||||
const req = createMockRequest('POST', { tools: [], workspaceId: 'workspace-123' })
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data).toHaveProperty('error', 'Unauthorized')
|
||||
})
|
||||
|
||||
it('should validate request data', async () => {
|
||||
const invalidTool = {
|
||||
code: 'return "invalid";',
|
||||
}
|
||||
|
||||
const req = createMockRequest('POST', { tools: [invalidTool], workspaceId: 'workspace-123' })
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data).toHaveProperty('error', 'Invalid request data')
|
||||
expect(data).toHaveProperty('details')
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Test DELETE endpoint
|
||||
*/
|
||||
describe('DELETE /api/tools/custom', () => {
|
||||
it('should delete a workspace-scoped tool by ID', async () => {
|
||||
mockLimit.mockResolvedValueOnce([sampleTools[0]])
|
||||
|
||||
const req = new NextRequest(
|
||||
'http://localhost:3000/api/tools/custom?id=tool-1&workspaceId=workspace-123'
|
||||
)
|
||||
|
||||
const response = await DELETE(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('success', true)
|
||||
|
||||
expect(mockDelete).toHaveBeenCalled()
|
||||
expect(mockWhere).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should reject requests missing tool ID', async () => {
|
||||
const req = new NextRequest('http://localhost:3000/api/tools/custom')
|
||||
|
||||
const response = await DELETE(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data).toHaveProperty('error', 'Tool ID is required')
|
||||
})
|
||||
|
||||
it('should handle tool not found', async () => {
|
||||
const mockLimitNotFound = vi.fn().mockResolvedValue([])
|
||||
mockWhere.mockReturnValueOnce({ limit: mockLimitNotFound })
|
||||
|
||||
const req = new NextRequest('http://localhost:3000/api/tools/custom?id=non-existent')
|
||||
|
||||
const response = await DELETE(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(data).toHaveProperty('error', 'Tool not found')
|
||||
})
|
||||
|
||||
it('should prevent unauthorized deletion of user-scoped tool', async () => {
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValueOnce({
|
||||
success: true,
|
||||
userId: 'user-456',
|
||||
authType: 'session',
|
||||
})
|
||||
|
||||
const userScopedTool = { ...sampleTools[0], workspaceId: null, userId: 'user-123' }
|
||||
const mockLimitUserScoped = vi.fn().mockResolvedValue([userScopedTool])
|
||||
mockWhere.mockReturnValueOnce({ limit: mockLimitUserScoped })
|
||||
|
||||
const req = new NextRequest('http://localhost:3000/api/tools/custom?id=tool-1')
|
||||
|
||||
const response = await DELETE(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(data).toHaveProperty('error', 'Access denied')
|
||||
})
|
||||
|
||||
it('should reject unauthorized requests', async () => {
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'Unauthorized',
|
||||
})
|
||||
|
||||
const req = new NextRequest('http://localhost:3000/api/tools/custom?id=tool-1')
|
||||
|
||||
const response = await DELETE(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(data).toHaveProperty('error', 'Unauthorized')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,297 @@
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { db } from '@sim/db'
|
||||
import { customTools } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { authorizeWorkflowByWorkspacePermission } from '@sim/platform-authz/workflow'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { and, desc, eq, isNull, or } from 'drizzle-orm'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
deleteCustomToolContract,
|
||||
listCustomToolsContract,
|
||||
upsertCustomToolsContract,
|
||||
} from '@/lib/api/contracts/tools/custom'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { captureServerEvent } from '@/lib/posthog/server'
|
||||
import { upsertCustomTools } from '@/lib/workflows/custom-tools/operations'
|
||||
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
||||
|
||||
const logger = createLogger('CustomToolsAPI')
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized custom tools access attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(listCustomToolsContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const userId = authResult.userId
|
||||
const { workspaceId, workflowId } = parsed.data.query
|
||||
|
||||
let resolvedWorkspaceId: string | null = workspaceId ?? null
|
||||
let resolvedFromWorkflowAuthorization = false
|
||||
|
||||
if (!resolvedWorkspaceId && workflowId) {
|
||||
const workflowAuthorization = await authorizeWorkflowByWorkspacePermission({
|
||||
workflowId,
|
||||
userId,
|
||||
action: 'read',
|
||||
})
|
||||
if (!workflowAuthorization.allowed) {
|
||||
logger.warn(`[${requestId}] Workflow authorization failed for custom tools`, {
|
||||
workflowId,
|
||||
userId,
|
||||
status: workflowAuthorization.status,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: workflowAuthorization.message || 'Access denied' },
|
||||
{ status: workflowAuthorization.status }
|
||||
)
|
||||
}
|
||||
|
||||
resolvedWorkspaceId = workflowAuthorization.workflow?.workspaceId ?? null
|
||||
resolvedFromWorkflowAuthorization = true
|
||||
}
|
||||
|
||||
if (resolvedWorkspaceId && !resolvedFromWorkflowAuthorization) {
|
||||
const userPermission = await getUserEntityPermissions(
|
||||
userId,
|
||||
'workspace',
|
||||
resolvedWorkspaceId
|
||||
)
|
||||
if (!userPermission) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} does not have access to workspace ${resolvedWorkspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
}
|
||||
}
|
||||
|
||||
const conditions = []
|
||||
|
||||
if (resolvedWorkspaceId) {
|
||||
conditions.push(eq(customTools.workspaceId, resolvedWorkspaceId))
|
||||
}
|
||||
|
||||
conditions.push(and(isNull(customTools.workspaceId), eq(customTools.userId, userId)))
|
||||
|
||||
const result = await db
|
||||
.select()
|
||||
.from(customTools)
|
||||
.where(or(...conditions))
|
||||
.orderBy(desc(customTools.createdAt))
|
||||
|
||||
return NextResponse.json({ data: result }, { status: 200 })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error fetching custom tools:`, error)
|
||||
return NextResponse.json({ error: 'Failed to fetch custom tools' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
|
||||
export const POST = withRouteHandler(async (req: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized custom tools update attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
upsertCustomToolsContract,
|
||||
req,
|
||||
{},
|
||||
{
|
||||
invalidJson: 'throw',
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Invalid custom tools data`, { errors: error.issues })
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Invalid request data',
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const userId = authResult.userId
|
||||
const { tools, workspaceId, source } = parsed.data.body
|
||||
|
||||
if (!workspaceId) {
|
||||
logger.warn(`[${requestId}] Missing workspaceId in request body`)
|
||||
return NextResponse.json({ error: 'workspaceId is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
|
||||
if (!userPermission) {
|
||||
logger.warn(`[${requestId}] User ${userId} does not have access to workspace ${workspaceId}`)
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
}
|
||||
|
||||
if (userPermission !== 'admin' && userPermission !== 'write') {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} does not have write permission for workspace ${workspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Write permission required' }, { status: 403 })
|
||||
}
|
||||
|
||||
const resultTools = await upsertCustomTools({
|
||||
tools,
|
||||
workspaceId,
|
||||
userId,
|
||||
requestId,
|
||||
})
|
||||
|
||||
for (const tool of resultTools) {
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'custom_tool_saved',
|
||||
{ tool_id: tool.id, workspace_id: workspaceId, tool_name: tool.title, source },
|
||||
{
|
||||
groups: { workspace: workspaceId },
|
||||
setOnce: { first_custom_tool_saved_at: new Date().toISOString() },
|
||||
}
|
||||
)
|
||||
|
||||
recordAudit({
|
||||
workspaceId,
|
||||
actorId: userId,
|
||||
actorName: authResult.userName ?? undefined,
|
||||
actorEmail: authResult.userEmail ?? undefined,
|
||||
action: AuditAction.CUSTOM_TOOL_CREATED,
|
||||
resourceType: AuditResourceType.CUSTOM_TOOL,
|
||||
resourceId: tool.id,
|
||||
resourceName: tool.title,
|
||||
description: `Created/updated custom tool "${tool.title}"`,
|
||||
metadata: { source },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, data: resultTools })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error updating custom tools`, error)
|
||||
const errorMessage = getErrorMessage(error, 'Failed to update custom tools')
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
|
||||
export const DELETE = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
const parsed = await parseRequest(
|
||||
deleteCustomToolContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) => {
|
||||
logger.warn(`[${requestId}] Missing tool ID for deletion`)
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Tool ID is required',
|
||||
details: error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
},
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: toolId, workspaceId, source } = parsed.data.query
|
||||
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized custom tool deletion attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = authResult.userId
|
||||
|
||||
const existingTool = await db
|
||||
.select()
|
||||
.from(customTools)
|
||||
.where(eq(customTools.id, toolId))
|
||||
.limit(1)
|
||||
|
||||
if (existingTool.length === 0) {
|
||||
logger.warn(`[${requestId}] Tool not found: ${toolId}`)
|
||||
return NextResponse.json({ error: 'Tool not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const tool = existingTool[0]
|
||||
|
||||
if (tool.workspaceId) {
|
||||
if (!workspaceId) {
|
||||
logger.warn(`[${requestId}] Missing workspaceId for workspace-scoped tool`)
|
||||
return NextResponse.json({ error: 'workspaceId is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const userPermission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
|
||||
if (!userPermission) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} does not have access to workspace ${workspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
}
|
||||
|
||||
if (userPermission !== 'admin' && userPermission !== 'write') {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} does not have write permission for workspace ${workspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Write permission required' }, { status: 403 })
|
||||
}
|
||||
|
||||
if (tool.workspaceId !== workspaceId) {
|
||||
logger.warn(`[${requestId}] Tool ${toolId} does not belong to workspace ${workspaceId}`)
|
||||
return NextResponse.json({ error: 'Tool not found' }, { status: 404 })
|
||||
}
|
||||
} else if (tool.userId !== userId) {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${userId} attempted to delete tool they don't own: ${toolId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
}
|
||||
|
||||
await db.delete(customTools).where(eq(customTools.id, toolId))
|
||||
|
||||
const toolWorkspaceId = tool.workspaceId ?? workspaceId ?? ''
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'custom_tool_deleted',
|
||||
{ tool_id: toolId, workspace_id: toolWorkspaceId, source },
|
||||
toolWorkspaceId ? { groups: { workspace: toolWorkspaceId } } : undefined
|
||||
)
|
||||
|
||||
recordAudit({
|
||||
workspaceId: tool.workspaceId || undefined,
|
||||
actorId: userId,
|
||||
actorName: authResult.userName ?? undefined,
|
||||
actorEmail: authResult.userEmail ?? undefined,
|
||||
action: AuditAction.CUSTOM_TOOL_DELETED,
|
||||
resourceType: AuditResourceType.CUSTOM_TOOL,
|
||||
resourceId: toolId,
|
||||
resourceName: tool.title,
|
||||
description: `Deleted custom tool "${tool.title}"`,
|
||||
metadata: { source },
|
||||
})
|
||||
|
||||
logger.info(`[${requestId}] Deleted tool: ${toolId}`)
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error(`[${requestId}] Error deleting custom tool:`, error)
|
||||
return NextResponse.json({ error: 'Failed to delete custom tool' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user