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,108 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { authMockFns, dbChainMock, dbChainMockFns, resetDbChainMock } from '@sim/testing'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Override global db mock with the configurable chain mock
|
||||
vi.mock('@sim/db', () => dbChainMock)
|
||||
|
||||
const { mockValidateWorkflowAccess, mockGetWorkspaceBilledAccountUserId } = vi.hoisted(() => ({
|
||||
mockValidateWorkflowAccess: vi.fn(),
|
||||
mockGetWorkspaceBilledAccountUserId: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/workflows/middleware', () => ({
|
||||
validateWorkflowAccess: mockValidateWorkflowAccess,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workspaces/utils', () => ({
|
||||
getWorkspaceBilledAccountUserId: mockGetWorkspaceBilledAccountUserId,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/logs/execution/logging-session', () => ({
|
||||
LoggingSession: vi.fn().mockImplementation(() => ({
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
markAsFailed: vi.fn().mockResolvedValue(undefined),
|
||||
safeCompleteWithError: vi.fn().mockResolvedValue(undefined),
|
||||
safeComplete: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/logs/execution/trace-spans/trace-spans', () => ({
|
||||
buildTraceSpans: vi.fn().mockReturnValue([]),
|
||||
}))
|
||||
|
||||
import { POST } from './route'
|
||||
|
||||
const makeRequest = (workflowId: string, body: unknown) =>
|
||||
new NextRequest(`http://localhost/api/workflows/${workflowId}/log`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
const validResult = { success: true, output: { value: 42 } }
|
||||
|
||||
describe('POST /api/workflows/[id]/log cross-tenant guard', () => {
|
||||
const OWNER_WORKFLOW_ID = 'wf-owner'
|
||||
const ATTACKER_WORKFLOW_ID = 'wf-attacker'
|
||||
const VICTIM_EXECUTION_ID = 'exec-victim-uuid'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetDbChainMock()
|
||||
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })
|
||||
mockValidateWorkflowAccess.mockResolvedValue({ error: null })
|
||||
mockGetWorkspaceBilledAccountUserId.mockResolvedValue('user-1')
|
||||
// Default: no existing log (fresh execution)
|
||||
dbChainMockFns.limit.mockResolvedValue([])
|
||||
})
|
||||
|
||||
it('returns 404 when executionId belongs to a different workflow', async () => {
|
||||
dbChainMockFns.limit.mockResolvedValueOnce([{ workflowId: OWNER_WORKFLOW_ID }])
|
||||
|
||||
const res = await POST(
|
||||
makeRequest(ATTACKER_WORKFLOW_ID, {
|
||||
executionId: VICTIM_EXECUTION_ID,
|
||||
result: validResult,
|
||||
}),
|
||||
{ params: Promise.resolve({ id: ATTACKER_WORKFLOW_ID }) }
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('Execution not found')
|
||||
})
|
||||
|
||||
it('proceeds when executionId belongs to the same workflow', async () => {
|
||||
dbChainMockFns.limit.mockResolvedValueOnce([{ workflowId: OWNER_WORKFLOW_ID }])
|
||||
|
||||
const res = await POST(
|
||||
makeRequest(OWNER_WORKFLOW_ID, {
|
||||
executionId: VICTIM_EXECUTION_ID,
|
||||
result: validResult,
|
||||
}),
|
||||
{ params: Promise.resolve({ id: OWNER_WORKFLOW_ID }) }
|
||||
)
|
||||
|
||||
expect(res.status).not.toBe(404)
|
||||
expect(res.status).not.toBe(403)
|
||||
})
|
||||
|
||||
it('proceeds when executionId has no existing log row (fresh execution)', async () => {
|
||||
dbChainMockFns.limit.mockResolvedValueOnce([])
|
||||
|
||||
const res = await POST(
|
||||
makeRequest(OWNER_WORKFLOW_ID, {
|
||||
executionId: 'brand-new-execution-id',
|
||||
result: validResult,
|
||||
}),
|
||||
{ params: Promise.resolve({ id: OWNER_WORKFLOW_ID }) }
|
||||
)
|
||||
|
||||
expect(res.status).not.toBe(404)
|
||||
expect(res.status).not.toBe(403)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
import { db } from '@sim/db'
|
||||
import { workflowExecutionLogs } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { workflowLogContract } from '@/lib/api/contracts/workflows'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { LoggingSession } from '@/lib/logs/execution/logging-session'
|
||||
import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans'
|
||||
import { getWorkspaceBilledAccountUserId } from '@/lib/workspaces/utils'
|
||||
import { validateWorkflowAccess } from '@/app/api/workflows/middleware'
|
||||
import { createErrorResponse, createSuccessResponse } from '@/app/api/workflows/utils'
|
||||
import type { ExecutionResult } from '@/executor/types'
|
||||
|
||||
const logger = createLogger('WorkflowLogAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const { id } = await context.params
|
||||
|
||||
try {
|
||||
const accessValidation = await validateWorkflowAccess(request, id, false)
|
||||
if (accessValidation.error) {
|
||||
logger.warn(
|
||||
`[${requestId}] Workflow access validation failed: ${accessValidation.error.message}`
|
||||
)
|
||||
return createErrorResponse(accessValidation.error.message, accessValidation.error.status)
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(workflowLogContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { logs, executionId, result } = parsed.data.body
|
||||
|
||||
if (result) {
|
||||
if (!executionId) {
|
||||
logger.warn(`[${requestId}] Missing executionId for result logging`)
|
||||
return createErrorResponse('executionId is required when logging results', 400)
|
||||
}
|
||||
|
||||
const [existingLog] = await db
|
||||
.select({ workflowId: workflowExecutionLogs.workflowId })
|
||||
.from(workflowExecutionLogs)
|
||||
.where(eq(workflowExecutionLogs.executionId, executionId))
|
||||
.limit(1)
|
||||
|
||||
if (existingLog && existingLog.workflowId !== id) {
|
||||
logger.warn(
|
||||
`[${requestId}] executionId ${executionId} belongs to workflow ${existingLog.workflowId}, not ${id}`
|
||||
)
|
||||
return createErrorResponse('Execution not found', 404)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Persisting execution result for workflow: ${id}`, {
|
||||
executionId,
|
||||
success: result.success,
|
||||
})
|
||||
|
||||
const isChatExecution = result.metadata?.source === 'chat'
|
||||
|
||||
const triggerType = isChatExecution ? 'chat' : 'manual'
|
||||
const loggingSession = new LoggingSession(id, executionId, triggerType, requestId)
|
||||
|
||||
const workspaceId = accessValidation.workflow.workspaceId
|
||||
if (!workspaceId) {
|
||||
logger.error(`[${requestId}] Workflow ${id} has no workspaceId`)
|
||||
return createErrorResponse('Workflow has no associated workspace', 500)
|
||||
}
|
||||
const billedAccountUserId = await getWorkspaceBilledAccountUserId(workspaceId)
|
||||
if (!billedAccountUserId) {
|
||||
logger.error(
|
||||
`[${requestId}] Unable to resolve billed account for workspace ${workspaceId}`
|
||||
)
|
||||
return createErrorResponse('Unable to resolve billing account for this workspace', 500)
|
||||
}
|
||||
|
||||
await loggingSession.safeStart({
|
||||
userId: billedAccountUserId,
|
||||
workspaceId,
|
||||
variables: {},
|
||||
})
|
||||
|
||||
const resultWithOutput = {
|
||||
...result,
|
||||
output: result.output ?? {},
|
||||
}
|
||||
|
||||
const { traceSpans, totalDuration } = buildTraceSpans(resultWithOutput as ExecutionResult)
|
||||
|
||||
if (result.success === false) {
|
||||
const message = result.error || 'Workflow run failed'
|
||||
await loggingSession.safeCompleteWithError({
|
||||
endedAt: new Date().toISOString(),
|
||||
totalDurationMs: totalDuration || result.metadata?.duration || 0,
|
||||
error: { message },
|
||||
traceSpans,
|
||||
})
|
||||
} else {
|
||||
await loggingSession.safeComplete({
|
||||
endedAt: new Date().toISOString(),
|
||||
totalDurationMs: totalDuration || result.metadata?.duration || 0,
|
||||
finalOutput: result.output || {},
|
||||
traceSpans,
|
||||
})
|
||||
}
|
||||
|
||||
return createSuccessResponse({
|
||||
message: 'Run logs persisted successfully',
|
||||
})
|
||||
}
|
||||
|
||||
if (!logs || !Array.isArray(logs) || logs.length === 0) {
|
||||
logger.warn(`[${requestId}] No logs provided for workflow: ${id}`)
|
||||
return createErrorResponse('No logs provided', 400)
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Persisting ${logs.length} logs for workflow: ${id}`, {
|
||||
executionId,
|
||||
})
|
||||
|
||||
return createSuccessResponse({ message: 'Logs persisted successfully' })
|
||||
} catch (error: any) {
|
||||
logger.error(`[${requestId}] Error persisting logs for workflow: ${id}`, error)
|
||||
return createErrorResponse(error.message || 'Failed to persist logs', 500)
|
||||
}
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user