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,202 @@
|
||||
/**
|
||||
* Tests for the workflow deployed-state API route.
|
||||
* Covers internal-JWT authorization (acting user required + workspace read
|
||||
* permission) and the unchanged session path.
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
|
||||
import {
|
||||
workflowAuthzMockFns,
|
||||
workflowsPersistenceUtilsMock,
|
||||
workflowsPersistenceUtilsMockFns,
|
||||
workflowsUtilsMock,
|
||||
workflowsUtilsMockFns,
|
||||
} from '@sim/testing'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockVerifyInternalToken } = vi.hoisted(() => ({
|
||||
mockVerifyInternalToken: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/internal', () => ({
|
||||
verifyInternalToken: mockVerifyInternalToken,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock)
|
||||
|
||||
vi.mock('@/lib/workflows/utils', () => workflowsUtilsMock)
|
||||
|
||||
import { GET } from './route'
|
||||
|
||||
const mockAuthorizeWorkflowByWorkspacePermission =
|
||||
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission
|
||||
const mockLoadDeployedWorkflowState = workflowsPersistenceUtilsMockFns.mockLoadDeployedWorkflowState
|
||||
const mockValidateWorkflowPermissions = workflowsUtilsMockFns.mockValidateWorkflowPermissions
|
||||
|
||||
const DEPLOYED_STATE = {
|
||||
blocks: { 'block-1': { id: 'block-1', type: 'starter' } },
|
||||
edges: [],
|
||||
loops: {},
|
||||
parallels: {},
|
||||
variables: {},
|
||||
}
|
||||
|
||||
function createRequest(options?: { bearerToken?: string }) {
|
||||
const headers: Record<string, string> = {}
|
||||
if (options?.bearerToken) {
|
||||
headers.Authorization = `Bearer ${options.bearerToken}`
|
||||
}
|
||||
return new NextRequest('http://localhost:3000/api/workflows/workflow-123/deployed', { headers })
|
||||
}
|
||||
|
||||
const routeParams = () => ({ params: Promise.resolve({ id: 'workflow-123' }) })
|
||||
|
||||
describe('GET /api/workflows/[id]/deployed', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: false })
|
||||
mockLoadDeployedWorkflowState.mockResolvedValue(DEPLOYED_STATE)
|
||||
})
|
||||
|
||||
describe('internal JWT path', () => {
|
||||
it('returns 200 when the token carries a user with read permission', async () => {
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: true, userId: 'user-123' })
|
||||
mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: true,
|
||||
status: 200,
|
||||
workflow: { id: 'workflow-123', workspaceId: 'workspace-456' },
|
||||
workspacePermission: 'read',
|
||||
})
|
||||
|
||||
const response = await GET(createRequest({ bearerToken: 'internal-token' }), routeParams())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const data = await response.json()
|
||||
expect(data.deployedState).toEqual(DEPLOYED_STATE)
|
||||
expect(mockAuthorizeWorkflowByWorkspacePermission).toHaveBeenCalledWith({
|
||||
workflowId: 'workflow-123',
|
||||
userId: 'user-123',
|
||||
action: 'read',
|
||||
})
|
||||
expect(mockValidateWorkflowPermissions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 when the acting user lacks read permission', async () => {
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: true, userId: 'user-123' })
|
||||
mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: false,
|
||||
status: 403,
|
||||
message: 'Unauthorized: Access denied to read this workflow',
|
||||
workflow: { id: 'workflow-123', workspaceId: 'workspace-456' },
|
||||
workspacePermission: null,
|
||||
})
|
||||
|
||||
const response = await GET(createRequest({ bearerToken: 'internal-token' }), routeParams())
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
const data = await response.json()
|
||||
expect(data.error).toBe('Unauthorized: Access denied to read this workflow')
|
||||
expect(mockLoadDeployedWorkflowState).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 when the token carries no acting user (fail closed)', async () => {
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: true, userId: undefined })
|
||||
|
||||
const response = await GET(createRequest({ bearerToken: 'internal-token' }), routeParams())
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
const data = await response.json()
|
||||
expect(data.error).toBe('Forbidden')
|
||||
expect(mockAuthorizeWorkflowByWorkspacePermission).not.toHaveBeenCalled()
|
||||
expect(mockLoadDeployedWorkflowState).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the workflow does not exist', async () => {
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: true, userId: 'user-123' })
|
||||
mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: false,
|
||||
status: 404,
|
||||
message: 'Workflow not found',
|
||||
workflow: null,
|
||||
workspacePermission: null,
|
||||
})
|
||||
|
||||
const response = await GET(createRequest({ bearerToken: 'internal-token' }), routeParams())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
const data = await response.json()
|
||||
expect(data.error).toBe('Workflow not found')
|
||||
expect(mockLoadDeployedWorkflowState).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('session path', () => {
|
||||
it('returns 200 when session permissions validate', async () => {
|
||||
mockValidateWorkflowPermissions.mockResolvedValue({
|
||||
error: null,
|
||||
session: { user: { id: 'user-123' } },
|
||||
workflow: { id: 'workflow-123' },
|
||||
})
|
||||
|
||||
const response = await GET(createRequest(), routeParams())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const data = await response.json()
|
||||
expect(data.deployedState).toEqual(DEPLOYED_STATE)
|
||||
expect(mockValidateWorkflowPermissions).toHaveBeenCalledWith(
|
||||
'workflow-123',
|
||||
expect.any(String),
|
||||
'read'
|
||||
)
|
||||
expect(mockAuthorizeWorkflowByWorkspacePermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('propagates validateWorkflowPermissions errors unchanged', async () => {
|
||||
mockValidateWorkflowPermissions.mockResolvedValue({
|
||||
error: { message: 'Unauthorized', status: 401 },
|
||||
session: null,
|
||||
workflow: null,
|
||||
})
|
||||
|
||||
const response = await GET(createRequest(), routeParams())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
const data = await response.json()
|
||||
expect(data.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('falls back to session validation when the bearer token is not a valid internal token', async () => {
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: false })
|
||||
mockValidateWorkflowPermissions.mockResolvedValue({
|
||||
error: { message: 'Unauthorized', status: 401 },
|
||||
session: null,
|
||||
workflow: null,
|
||||
})
|
||||
|
||||
const response = await GET(createRequest({ bearerToken: 'not-internal' }), routeParams())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(mockValidateWorkflowPermissions).toHaveBeenCalled()
|
||||
expect(mockAuthorizeWorkflowByWorkspacePermission).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null deployedState when loading the snapshot fails', async () => {
|
||||
mockVerifyInternalToken.mockResolvedValue({ valid: true, userId: 'user-123' })
|
||||
mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: true,
|
||||
status: 200,
|
||||
workflow: { id: 'workflow-123', workspaceId: 'workspace-456' },
|
||||
workspacePermission: 'admin',
|
||||
})
|
||||
mockLoadDeployedWorkflowState.mockRejectedValue(new Error('no active deployment'))
|
||||
|
||||
const response = await GET(createRequest({ bearerToken: 'internal-token' }), routeParams())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const data = await response.json()
|
||||
expect(data.deployedState).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { authorizeWorkflowByWorkspacePermission } from '@sim/platform-authz/workflow'
|
||||
import type { NextRequest, NextResponse } from 'next/server'
|
||||
import { getDeployedWorkflowStateContract } from '@/lib/api/contracts/deployments'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { verifyInternalToken } from '@/lib/auth/internal'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { loadDeployedWorkflowState } from '@/lib/workflows/persistence/utils'
|
||||
import { validateWorkflowPermissions } from '@/lib/workflows/utils'
|
||||
import { createErrorResponse, createSuccessResponse } from '@/app/api/workflows/utils'
|
||||
|
||||
const logger = createLogger('WorkflowDeployedStateAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
function addNoCacheHeaders(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/workflows/[id]/deployed
|
||||
* Returns the active deployed state snapshot for a workflow.
|
||||
*
|
||||
* Internal (server-to-server) calls must carry the acting user in the internal
|
||||
* JWT payload (`generateInternalToken(userId)` — the executor's
|
||||
* `buildAuthHeaders(ctx.userId)` always embeds it) and are authorized as that
|
||||
* user with the same workspace-read semantics as the sibling
|
||||
* `/api/workflows/[id]` route. Internal calls without a user id are rejected
|
||||
* (fail closed). Session calls are authorized via
|
||||
* `validateWorkflowPermissions` as before.
|
||||
*/
|
||||
export const GET = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
const parsed = await parseRequest(getDeployedWorkflowStateContract, request, context)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { id } = parsed.data.params
|
||||
|
||||
try {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
let isInternalCall = false
|
||||
let internalCallUserId: string | undefined
|
||||
|
||||
if (authHeader?.startsWith('Bearer ')) {
|
||||
const token = authHeader.split(' ')[1]
|
||||
const verification = await verifyInternalToken(token)
|
||||
isInternalCall = verification.valid
|
||||
internalCallUserId = verification.userId
|
||||
}
|
||||
|
||||
if (isInternalCall) {
|
||||
if (!internalCallUserId) {
|
||||
logger.warn(`[${requestId}] Internal call without acting user denied for workflow ${id}`)
|
||||
return addNoCacheHeaders(createErrorResponse('Forbidden', 403))
|
||||
}
|
||||
|
||||
const authorization = await authorizeWorkflowByWorkspacePermission({
|
||||
workflowId: id,
|
||||
userId: internalCallUserId,
|
||||
action: 'read',
|
||||
})
|
||||
if (!authorization.workflow) {
|
||||
logger.warn(`[${requestId}] Workflow ${id} not found for internal call`)
|
||||
return addNoCacheHeaders(createErrorResponse('Workflow not found', 404))
|
||||
}
|
||||
if (!authorization.allowed) {
|
||||
logger.warn(
|
||||
`[${requestId}] Internal call user ${internalCallUserId} denied read access to workflow ${id}`
|
||||
)
|
||||
return addNoCacheHeaders(
|
||||
createErrorResponse(authorization.message || 'Access denied', authorization.status)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
const { error } = await validateWorkflowPermissions(id, requestId, 'read')
|
||||
if (error) {
|
||||
const response = createErrorResponse(error.message, error.status)
|
||||
return addNoCacheHeaders(response)
|
||||
}
|
||||
}
|
||||
|
||||
let deployedState = null
|
||||
try {
|
||||
const data = await loadDeployedWorkflowState(id)
|
||||
deployedState = {
|
||||
blocks: data.blocks,
|
||||
edges: data.edges,
|
||||
loops: data.loops,
|
||||
parallels: data.parallels,
|
||||
variables: data.variables,
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`[${requestId}] Failed to load deployed state for workflow ${id}`, { error })
|
||||
deployedState = null
|
||||
}
|
||||
|
||||
const response = createSuccessResponse({ deployedState })
|
||||
return addNoCacheHeaders(response)
|
||||
} catch (error: any) {
|
||||
logger.error(`[${requestId}] Error fetching deployed state: ${id}`, error)
|
||||
const response = createErrorResponse(error.message || 'Failed to fetch deployed state', 500)
|
||||
return addNoCacheHeaders(response)
|
||||
}
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user