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,85 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertWorkflowMutable, WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { deploymentsDeployContract } from '@/lib/api/contracts/tools/deployments'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { performFullDeploy } from '@/lib/workflows/orchestration'
|
||||
import { statusForOrchestrationError } from '@/lib/workflows/orchestration/types'
|
||||
import {
|
||||
authenticateDeploymentToolRequest,
|
||||
authorizeDeploymentWorkflow,
|
||||
deploymentToolError,
|
||||
} from '@/app/api/tools/deployments/utils'
|
||||
|
||||
const logger = createLogger('DeploymentsDeployAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 120
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const auth = await authenticateDeploymentToolRequest(request, requestId)
|
||||
if (!auth.ok) return auth.response
|
||||
|
||||
const parsed = await parseRequest(
|
||||
deploymentsDeployContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
deploymentToolError(getValidationErrorMessage(error, 'Invalid request data'), 400),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { workflowId, workspaceId, name, description } = parsed.data.body
|
||||
|
||||
const access = await authorizeDeploymentWorkflow(auth.userId, workflowId, workspaceId, 'admin')
|
||||
if (!access.ok) return access.response
|
||||
|
||||
await assertWorkflowMutable(workflowId)
|
||||
|
||||
logger.info(`[${requestId}] Deploying workflow ${workflowId} via deployments tool`, {
|
||||
userId: auth.userId,
|
||||
})
|
||||
|
||||
const result = await performFullDeploy({
|
||||
workflowId,
|
||||
userId: auth.userId,
|
||||
workflowName: access.workflow.name || undefined,
|
||||
versionName: name,
|
||||
versionDescription: description ?? undefined,
|
||||
requestId,
|
||||
request,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return deploymentToolError(
|
||||
result.error || 'Failed to deploy workflow',
|
||||
statusForOrchestrationError(result.errorCode)
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
workflowId,
|
||||
isDeployed: true,
|
||||
deployedAt: result.deployedAt?.toISOString() ?? null,
|
||||
version: result.version,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return deploymentToolError(error.message, error.status)
|
||||
}
|
||||
logger.error(`[${requestId}] Deployment tool deploy error`, { error })
|
||||
return deploymentToolError('Failed to deploy workflow', 500)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertWorkflowMutable, WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { deploymentsPromoteContract } from '@/lib/api/contracts/tools/deployments'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { performActivateVersion } from '@/lib/workflows/orchestration'
|
||||
import { statusForOrchestrationError } from '@/lib/workflows/orchestration/types'
|
||||
import {
|
||||
authenticateDeploymentToolRequest,
|
||||
authorizeDeploymentWorkflow,
|
||||
deploymentToolError,
|
||||
} from '@/app/api/tools/deployments/utils'
|
||||
|
||||
const logger = createLogger('DeploymentsPromoteAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 120
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const auth = await authenticateDeploymentToolRequest(request, requestId)
|
||||
if (!auth.ok) return auth.response
|
||||
|
||||
const parsed = await parseRequest(
|
||||
deploymentsPromoteContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
deploymentToolError(getValidationErrorMessage(error, 'Invalid request data'), 400),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { workflowId, workspaceId, version } = parsed.data.body
|
||||
|
||||
const access = await authorizeDeploymentWorkflow(auth.userId, workflowId, workspaceId, 'admin')
|
||||
if (!access.ok) return access.response
|
||||
|
||||
await assertWorkflowMutable(workflowId)
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Promoting workflow ${workflowId} to version ${version} via deployments tool`,
|
||||
{ userId: auth.userId }
|
||||
)
|
||||
|
||||
const result = await performActivateVersion({
|
||||
workflowId,
|
||||
version,
|
||||
userId: auth.userId,
|
||||
workflow: access.workflow as Record<string, unknown>,
|
||||
requestId,
|
||||
request,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return deploymentToolError(
|
||||
result.error || 'Failed to promote deployment version',
|
||||
statusForOrchestrationError(result.errorCode)
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
workflowId,
|
||||
isDeployed: true,
|
||||
deployedAt: result.deployedAt?.toISOString() ?? null,
|
||||
version,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return deploymentToolError(error.message, error.status)
|
||||
}
|
||||
logger.error(`[${requestId}] Deployment tool promote error`, { error })
|
||||
return deploymentToolError('Failed to promote deployment version', 500)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*
|
||||
* Tests for the deployment tool routes under /api/tools/deployments — verifies
|
||||
* session/internal auth, workspace permission enforcement, and the mapping of
|
||||
* orchestration results to tool responses.
|
||||
*/
|
||||
|
||||
import { WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { createMockRequest, hybridAuthMockFns, workflowAuthzMockFns } from '@sim/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockEnforceUserRateLimit,
|
||||
mockPerformFullDeploy,
|
||||
mockPerformFullUndeploy,
|
||||
mockPerformActivateVersion,
|
||||
mockListWorkflowVersions,
|
||||
mockGetWorkflowDeploymentVersion,
|
||||
} = vi.hoisted(() => ({
|
||||
mockEnforceUserRateLimit: vi.fn(),
|
||||
mockPerformFullDeploy: vi.fn(),
|
||||
mockPerformFullUndeploy: vi.fn(),
|
||||
mockPerformActivateVersion: vi.fn(),
|
||||
mockListWorkflowVersions: vi.fn(),
|
||||
mockGetWorkflowDeploymentVersion: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/rate-limiter', () => ({
|
||||
enforceUserRateLimit: mockEnforceUserRateLimit,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/orchestration', () => ({
|
||||
performFullDeploy: mockPerformFullDeploy,
|
||||
performFullUndeploy: mockPerformFullUndeploy,
|
||||
performActivateVersion: mockPerformActivateVersion,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/persistence/utils', () => ({
|
||||
listWorkflowVersions: mockListWorkflowVersions,
|
||||
getWorkflowDeploymentVersion: mockGetWorkflowDeploymentVersion,
|
||||
}))
|
||||
|
||||
import { POST as deployPost } from '@/app/api/tools/deployments/deploy/route'
|
||||
import { POST as promotePost } from '@/app/api/tools/deployments/promote/route'
|
||||
import { POST as undeployPost } from '@/app/api/tools/deployments/undeploy/route'
|
||||
import { GET as getVersionGet } from '@/app/api/tools/deployments/version/route'
|
||||
import { GET as listVersionsGet } from '@/app/api/tools/deployments/versions/route'
|
||||
|
||||
const WORKFLOW_ID = 'wf-1'
|
||||
const WORKFLOW_RECORD = {
|
||||
id: WORKFLOW_ID,
|
||||
name: 'My Workflow',
|
||||
workspaceId: 'ws-1',
|
||||
isDeployed: true,
|
||||
}
|
||||
|
||||
function authorized() {
|
||||
return { allowed: true, status: 200, workflow: WORKFLOW_RECORD, workspacePermission: 'admin' }
|
||||
}
|
||||
|
||||
function makePost(path: string, body: unknown) {
|
||||
return createMockRequest('POST', body, {}, `http://localhost:3000/api/tools/deployments/${path}`)
|
||||
}
|
||||
|
||||
function makeGet(path: string, query: string) {
|
||||
return createMockRequest(
|
||||
'GET',
|
||||
undefined,
|
||||
{},
|
||||
`http://localhost:3000/api/tools/deployments/${path}?${query}`
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'user-1',
|
||||
authType: 'internal_jwt',
|
||||
})
|
||||
mockEnforceUserRateLimit.mockResolvedValue(null)
|
||||
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue(authorized())
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('POST /api/tools/deployments/deploy', () => {
|
||||
beforeEach(() => {
|
||||
mockPerformFullDeploy.mockResolvedValue({
|
||||
success: true,
|
||||
deployedAt: new Date('2026-06-12T00:00:00Z'),
|
||||
version: 4,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unauthenticated requests', async () => {
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Unauthorized',
|
||||
})
|
||||
|
||||
const response = await deployPost(
|
||||
makePost('deploy', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires admin permission on the workflow workspace', async () => {
|
||||
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
allowed: false,
|
||||
status: 403,
|
||||
message: 'Access denied',
|
||||
workflow: WORKFLOW_RECORD,
|
||||
workspacePermission: 'write',
|
||||
})
|
||||
|
||||
const response = await deployPost(
|
||||
makePost('deploy', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
expect(workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission).toHaveBeenCalledWith({
|
||||
workflowId: WORKFLOW_ID,
|
||||
userId: 'user-1',
|
||||
action: 'admin',
|
||||
})
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('deploys and returns the new version', async () => {
|
||||
const response = await deployPost(
|
||||
makePost('deploy', {
|
||||
workflowId: WORKFLOW_ID,
|
||||
workspaceId: 'ws-1',
|
||||
name: 'Release 4',
|
||||
description: 'Fixes the agent prompt',
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformFullDeploy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workflowId: WORKFLOW_ID,
|
||||
userId: 'user-1',
|
||||
versionName: 'Release 4',
|
||||
versionDescription: 'Fixes the agent prompt',
|
||||
})
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body).toEqual({
|
||||
success: true,
|
||||
output: {
|
||||
workflowId: WORKFLOW_ID,
|
||||
isDeployed: true,
|
||||
deployedAt: '2026-06-12T00:00:00.000Z',
|
||||
version: 4,
|
||||
warnings: [],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 423 when the workflow is locked', async () => {
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockRejectedValue(new WorkflowLockedError())
|
||||
|
||||
const response = await deployPost(
|
||||
makePost('deploy', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(423)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a request without a workflowId', async () => {
|
||||
const response = await deployPost(makePost('deploy', { workspaceId: 'ws-1' }))
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the workflow belongs to a different workspace', async () => {
|
||||
const response = await deployPost(
|
||||
makePost('deploy', { workflowId: WORKFLOW_ID, workspaceId: 'ws-other' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Workflow not found in this workspace')
|
||||
expect(mockPerformFullDeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/tools/deployments/undeploy', () => {
|
||||
beforeEach(() => {
|
||||
mockPerformFullUndeploy.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
it('returns 400 when the workflow is not deployed', async () => {
|
||||
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
|
||||
...authorized(),
|
||||
workflow: { ...WORKFLOW_RECORD, isDeployed: false },
|
||||
})
|
||||
|
||||
const response = await undeployPost(
|
||||
makePost('undeploy', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformFullUndeploy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('undeploys a deployed workflow', async () => {
|
||||
const response = await undeployPost(
|
||||
makePost('undeploy', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformFullUndeploy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ workflowId: WORKFLOW_ID, userId: 'user-1' })
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.output).toEqual({
|
||||
workflowId: WORKFLOW_ID,
|
||||
isDeployed: false,
|
||||
deployedAt: null,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/tools/deployments/promote', () => {
|
||||
beforeEach(() => {
|
||||
mockPerformActivateVersion.mockResolvedValue({
|
||||
success: true,
|
||||
deployedAt: new Date('2026-06-12T00:00:00Z'),
|
||||
})
|
||||
})
|
||||
|
||||
it('promotes the given version to live', async () => {
|
||||
const response = await promotePost(
|
||||
makePost('promote', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1', version: 3 })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformActivateVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ workflowId: WORKFLOW_ID, version: 3, userId: 'user-1' })
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.output).toEqual({
|
||||
workflowId: WORKFLOW_ID,
|
||||
isDeployed: true,
|
||||
deployedAt: '2026-06-12T00:00:00.000Z',
|
||||
version: 3,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a missing version', async () => {
|
||||
const response = await promotePost(
|
||||
makePost('promote', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1' })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps a missing target version to 404', async () => {
|
||||
mockPerformActivateVersion.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Deployment version not found',
|
||||
errorCode: 'not_found',
|
||||
})
|
||||
|
||||
const response = await promotePost(
|
||||
makePost('promote', { workflowId: WORKFLOW_ID, workspaceId: 'ws-1', version: 99 })
|
||||
)
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/tools/deployments/versions', () => {
|
||||
it('lists deployment versions with read permission', async () => {
|
||||
const versions = [
|
||||
{
|
||||
id: 'v-2',
|
||||
version: 2,
|
||||
name: null,
|
||||
description: null,
|
||||
isActive: true,
|
||||
createdAt: '2026-06-12T00:00:00.000Z',
|
||||
createdBy: 'user-1',
|
||||
deployedByName: 'Waleed',
|
||||
},
|
||||
]
|
||||
mockListWorkflowVersions.mockResolvedValue({ versions })
|
||||
|
||||
const response = await listVersionsGet(
|
||||
makeGet('versions', `workflowId=${WORKFLOW_ID}&workspaceId=ws-1`)
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission).toHaveBeenCalledWith({
|
||||
workflowId: WORKFLOW_ID,
|
||||
userId: 'user-1',
|
||||
action: 'read',
|
||||
})
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.output).toEqual({ workflowId: WORKFLOW_ID, versions })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/tools/deployments/version', () => {
|
||||
it('returns version metadata and the deployed state', async () => {
|
||||
mockGetWorkflowDeploymentVersion.mockResolvedValue({
|
||||
id: 'v-3',
|
||||
version: 3,
|
||||
name: 'Release 3',
|
||||
description: null,
|
||||
isActive: false,
|
||||
createdAt: '2026-06-12T00:00:00.000Z',
|
||||
state: { blocks: {}, edges: [] },
|
||||
})
|
||||
|
||||
const response = await getVersionGet(
|
||||
makeGet('version', `workflowId=${WORKFLOW_ID}&workspaceId=ws-1&version=3`)
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const body = await response.json()
|
||||
expect(body.output).toEqual({
|
||||
workflowId: WORKFLOW_ID,
|
||||
version: 3,
|
||||
name: 'Release 3',
|
||||
description: null,
|
||||
isActive: false,
|
||||
createdAt: '2026-06-12T00:00:00.000Z',
|
||||
deployedState: { blocks: {}, edges: [] },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 404 when the version does not exist', async () => {
|
||||
mockGetWorkflowDeploymentVersion.mockResolvedValue(null)
|
||||
|
||||
const response = await getVersionGet(
|
||||
makeGet('version', `workflowId=${WORKFLOW_ID}&workspaceId=ws-1&version=9`)
|
||||
)
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertWorkflowMutable, WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { deploymentsUndeployContract } from '@/lib/api/contracts/tools/deployments'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { performFullUndeploy } from '@/lib/workflows/orchestration'
|
||||
import {
|
||||
authenticateDeploymentToolRequest,
|
||||
authorizeDeploymentWorkflow,
|
||||
deploymentToolError,
|
||||
} from '@/app/api/tools/deployments/utils'
|
||||
|
||||
const logger = createLogger('DeploymentsUndeployAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 120
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const auth = await authenticateDeploymentToolRequest(request, requestId)
|
||||
if (!auth.ok) return auth.response
|
||||
|
||||
const parsed = await parseRequest(
|
||||
deploymentsUndeployContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
deploymentToolError(getValidationErrorMessage(error, 'Invalid request data'), 400),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { workflowId, workspaceId } = parsed.data.body
|
||||
|
||||
const access = await authorizeDeploymentWorkflow(auth.userId, workflowId, workspaceId, 'admin')
|
||||
if (!access.ok) return access.response
|
||||
|
||||
if (!access.workflow.isDeployed) {
|
||||
return deploymentToolError('Workflow is not deployed', 400)
|
||||
}
|
||||
|
||||
await assertWorkflowMutable(workflowId)
|
||||
|
||||
logger.info(`[${requestId}] Undeploying workflow ${workflowId} via deployments tool`, {
|
||||
userId: auth.userId,
|
||||
})
|
||||
|
||||
const result = await performFullUndeploy({
|
||||
workflowId,
|
||||
userId: auth.userId,
|
||||
requestId,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return deploymentToolError(result.error || 'Failed to undeploy workflow', 500)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
workflowId,
|
||||
isDeployed: false,
|
||||
deployedAt: null,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return deploymentToolError(error.message, error.status)
|
||||
}
|
||||
logger.error(`[${requestId}] Deployment tool undeploy error`, { error })
|
||||
return deploymentToolError('Failed to undeploy workflow', 500)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import {
|
||||
authorizeWorkflowByWorkspacePermission,
|
||||
type WorkflowWorkspaceAuthorizationResult,
|
||||
} from '@sim/platform-authz/workflow'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { enforceUserRateLimit } from '@/lib/core/rate-limiter'
|
||||
|
||||
const logger = createLogger('DeploymentToolsAPI')
|
||||
|
||||
export type AuthorizedDeploymentWorkflow = NonNullable<
|
||||
WorkflowWorkspaceAuthorizationResult['workflow']
|
||||
>
|
||||
|
||||
/** Standard error body for deployment tool routes, matching the generic tool response shape. */
|
||||
export function deploymentToolError(error: string, status: number): NextResponse {
|
||||
return NextResponse.json({ success: false, error }, { status })
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates a deployment tool request via session or internal token (API
|
||||
* keys are rejected) and applies per-user rate limiting. Runs before request
|
||||
* parsing, so it must not read the body.
|
||||
*/
|
||||
export async function authenticateDeploymentToolRequest(
|
||||
request: NextRequest,
|
||||
requestId: string
|
||||
): Promise<{ ok: true; userId: string } | { ok: false; response: NextResponse }> {
|
||||
const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!auth.success || !auth.userId) {
|
||||
logger.warn(`[${requestId}] Unauthorized deployment tool request`, { error: auth.error })
|
||||
return {
|
||||
ok: false,
|
||||
response: deploymentToolError(auth.error || 'Authentication required', 401),
|
||||
}
|
||||
}
|
||||
|
||||
const rateLimited = await enforceUserRateLimit('deployment-tools', auth.userId)
|
||||
if (rateLimited) return { ok: false, response: rateLimited }
|
||||
|
||||
return { ok: true, userId: auth.userId }
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies the user holds the required workspace permission on the target
|
||||
* workflow and that the workflow belongs to the calling workspace. Deployment
|
||||
* mutations require `admin`, reads require `read`, matching the UI deploy
|
||||
* routes. The workspace binding keeps workflow-driven executions (schedules,
|
||||
* webhooks) from reaching into other workspaces the actor administers.
|
||||
*/
|
||||
export async function authorizeDeploymentWorkflow(
|
||||
userId: string,
|
||||
workflowId: string,
|
||||
workspaceId: string,
|
||||
action: 'read' | 'admin'
|
||||
): Promise<
|
||||
{ ok: true; workflow: AuthorizedDeploymentWorkflow } | { ok: false; response: NextResponse }
|
||||
> {
|
||||
const authorization = await authorizeWorkflowByWorkspacePermission({
|
||||
workflowId,
|
||||
userId,
|
||||
action,
|
||||
})
|
||||
|
||||
if (!authorization.allowed || !authorization.workflow) {
|
||||
return {
|
||||
ok: false,
|
||||
response: deploymentToolError(authorization.message || 'Access denied', authorization.status),
|
||||
}
|
||||
}
|
||||
|
||||
if (authorization.workflow.workspaceId !== workspaceId) {
|
||||
return {
|
||||
ok: false,
|
||||
response: deploymentToolError('Workflow not found in this workspace', 404),
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, workflow: authorization.workflow }
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { deploymentsGetVersionContract } from '@/lib/api/contracts/tools/deployments'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getWorkflowDeploymentVersion } from '@/lib/workflows/persistence/utils'
|
||||
import {
|
||||
authenticateDeploymentToolRequest,
|
||||
authorizeDeploymentWorkflow,
|
||||
deploymentToolError,
|
||||
} from '@/app/api/tools/deployments/utils'
|
||||
|
||||
const logger = createLogger('DeploymentsGetVersionAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const auth = await authenticateDeploymentToolRequest(request, requestId)
|
||||
if (!auth.ok) return auth.response
|
||||
|
||||
const parsed = await parseRequest(
|
||||
deploymentsGetVersionContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
deploymentToolError(getValidationErrorMessage(error, 'Invalid request data'), 400),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { workflowId, workspaceId, version } = parsed.data.query
|
||||
|
||||
const access = await authorizeDeploymentWorkflow(auth.userId, workflowId, workspaceId, 'read')
|
||||
if (!access.ok) return access.response
|
||||
|
||||
const row = await getWorkflowDeploymentVersion(workflowId, version)
|
||||
if (!row) {
|
||||
return deploymentToolError('Deployment version not found', 404)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: {
|
||||
workflowId,
|
||||
version: row.version,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
isActive: row.isActive,
|
||||
createdAt: row.createdAt,
|
||||
deployedState: row.state,
|
||||
},
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
logger.error(`[${requestId}] Deployment tool get version error`, { error })
|
||||
return deploymentToolError('Failed to get deployment version', 500)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { deploymentsListVersionsContract } from '@/lib/api/contracts/tools/deployments'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { listWorkflowVersions } from '@/lib/workflows/persistence/utils'
|
||||
import {
|
||||
authenticateDeploymentToolRequest,
|
||||
authorizeDeploymentWorkflow,
|
||||
deploymentToolError,
|
||||
} from '@/app/api/tools/deployments/utils'
|
||||
|
||||
const logger = createLogger('DeploymentsListVersionsAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const auth = await authenticateDeploymentToolRequest(request, requestId)
|
||||
if (!auth.ok) return auth.response
|
||||
|
||||
const parsed = await parseRequest(
|
||||
deploymentsListVersionsContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
deploymentToolError(getValidationErrorMessage(error, 'Invalid request data'), 400),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { workflowId, workspaceId } = parsed.data.query
|
||||
|
||||
const access = await authorizeDeploymentWorkflow(auth.userId, workflowId, workspaceId, 'read')
|
||||
if (!access.ok) return access.response
|
||||
|
||||
const { versions } = await listWorkflowVersions(workflowId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
output: { workflowId, versions },
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
logger.error(`[${requestId}] Deployment tool list versions error`, { error })
|
||||
return deploymentToolError('Failed to list deployment versions', 500)
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user