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,216 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*
|
||||
* Tests for POST /api/v1/workflows/[id]/rollback — verifies target version
|
||||
* resolution (previous version by default, explicit version when provided)
|
||||
* and the mapping of activation results to v1 API responses.
|
||||
*/
|
||||
|
||||
import { WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { createMockRequest, workflowAuthzMockFns } from '@sim/testing'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockCheckRateLimit,
|
||||
mockValidateWorkspaceAccess,
|
||||
mockPerformActivateVersion,
|
||||
mockFindPreviousDeploymentVersion,
|
||||
} = vi.hoisted(() => ({
|
||||
mockCheckRateLimit: vi.fn(),
|
||||
mockValidateWorkspaceAccess: vi.fn(),
|
||||
mockPerformActivateVersion: vi.fn(),
|
||||
mockFindPreviousDeploymentVersion: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/persistence/utils', () => ({
|
||||
findPreviousDeploymentVersion: mockFindPreviousDeploymentVersion,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v1/middleware', () => ({
|
||||
checkRateLimit: mockCheckRateLimit,
|
||||
createRateLimitResponse: vi.fn(() =>
|
||||
NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
),
|
||||
validateWorkspaceAccess: mockValidateWorkspaceAccess,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workflows/orchestration', () => ({
|
||||
performActivateVersion: mockPerformActivateVersion,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/v1/logs/meta', () => ({
|
||||
getUserLimits: vi.fn().mockResolvedValue({}),
|
||||
createApiResponse: vi.fn((body: unknown) => ({ body, headers: {} })),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/posthog/server', () => ({
|
||||
captureServerEvent: vi.fn(),
|
||||
}))
|
||||
|
||||
import { POST } from '@/app/api/v1/workflows/[id]/rollback/route'
|
||||
|
||||
const WORKFLOW_ID = 'wf-1'
|
||||
const WORKFLOW_RECORD = {
|
||||
id: WORKFLOW_ID,
|
||||
name: 'My Workflow',
|
||||
workspaceId: 'ws-1',
|
||||
isDeployed: true,
|
||||
}
|
||||
|
||||
function makeContext(id = WORKFLOW_ID) {
|
||||
return { params: Promise.resolve({ id }) }
|
||||
}
|
||||
|
||||
function makeRequest(body?: unknown) {
|
||||
return createMockRequest(
|
||||
'POST',
|
||||
body,
|
||||
{},
|
||||
`http://localhost:3000/api/v1/workflows/${WORKFLOW_ID}/rollback`
|
||||
)
|
||||
}
|
||||
|
||||
describe('POST /api/v1/workflows/[id]/rollback', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'user-1' })
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(null)
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(WORKFLOW_RECORD)
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockResolvedValue(undefined)
|
||||
mockPerformActivateVersion.mockResolvedValue({
|
||||
success: true,
|
||||
deployedAt: new Date('2026-06-12T00:00:00Z'),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unauthenticated requests', async () => {
|
||||
mockCheckRateLimit.mockResolvedValue({ allowed: false, error: 'Invalid API key' })
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the workflow does not exist', async () => {
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue(null)
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 423 when the workflow is locked', async () => {
|
||||
workflowAuthzMockFns.mockAssertWorkflowMutable.mockRejectedValue(new WorkflowLockedError())
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(423)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls back to the previous version when no version is given', async () => {
|
||||
mockFindPreviousDeploymentVersion.mockResolvedValue({ ok: true, version: 4 })
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformActivateVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ workflowId: WORKFLOW_ID, version: 4, userId: 'user-1' })
|
||||
)
|
||||
|
||||
const body = await response.json()
|
||||
expect(body.data).toEqual({
|
||||
id: WORKFLOW_ID,
|
||||
isDeployed: true,
|
||||
deployedAt: '2026-06-12T00:00:00.000Z',
|
||||
version: 4,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 400 when the workflow is not deployed, even with an explicit version', async () => {
|
||||
workflowAuthzMockFns.mockGetActiveWorkflowRecord.mockResolvedValue({
|
||||
...WORKFLOW_RECORD,
|
||||
isDeployed: false,
|
||||
})
|
||||
|
||||
const response = await POST(makeRequest({ version: 2 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Workflow is not deployed')
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls back to an explicit version when provided', async () => {
|
||||
const response = await POST(makeRequest({ version: 2 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockPerformActivateVersion).toHaveBeenCalledWith(expect.objectContaining({ version: 2 }))
|
||||
expect(mockFindPreviousDeploymentVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a non-integer version', async () => {
|
||||
const response = await POST(makeRequest({ version: 1.5 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when there is no active deployment to roll back from', async () => {
|
||||
mockFindPreviousDeploymentVersion.mockResolvedValue({ ok: false, reason: 'no_active_version' })
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Workflow has no active deployment to roll back from')
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when there is no previous version to roll back to', async () => {
|
||||
mockFindPreviousDeploymentVersion.mockResolvedValue({
|
||||
ok: false,
|
||||
reason: 'no_previous_version',
|
||||
})
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('No previous deployment version to roll back to')
|
||||
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 POST(makeRequest({ version: 99 }), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('masks missing admin permission as 404', async () => {
|
||||
mockValidateWorkspaceAccess.mockResolvedValue(
|
||||
NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||
)
|
||||
|
||||
const response = await POST(makeRequest(), makeContext())
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(mockValidateWorkspaceAccess).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ allowed: true }),
|
||||
'user-1',
|
||||
'ws-1',
|
||||
'admin'
|
||||
)
|
||||
expect(mockPerformActivateVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertWorkflowMutable, WorkflowLockedError } from '@sim/platform-authz/workflow'
|
||||
import { getErrorMessage } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import {
|
||||
v1RollbackWorkflowBodySchema,
|
||||
v1RollbackWorkflowContract,
|
||||
} from '@/lib/api/contracts/v1/workflows'
|
||||
import { parseOptionalJsonBody, parseRequest, validationErrorResponse } from '@/lib/api/server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { captureServerEvent } from '@/lib/posthog/server'
|
||||
import { performActivateVersion } from '@/lib/workflows/orchestration'
|
||||
import { statusForOrchestrationError } from '@/lib/workflows/orchestration/types'
|
||||
import { findPreviousDeploymentVersion } from '@/lib/workflows/persistence/utils'
|
||||
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
|
||||
import { checkRateLimit, createRateLimitResponse } from '@/app/api/v1/middleware'
|
||||
import { resolveV1DeploymentWorkflow } from '@/app/api/v1/workflows/utils'
|
||||
|
||||
const logger = createLogger('V1WorkflowRollbackAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const runtime = 'nodejs'
|
||||
export const maxDuration = 120
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const rateLimit = await checkRateLimit(request, 'workflow-rollback')
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit)
|
||||
}
|
||||
|
||||
const userId = rateLimit.userId!
|
||||
const parsed = await parseRequest(v1RollbackWorkflowContract, request, context, {
|
||||
validationErrorResponse: () =>
|
||||
NextResponse.json({ error: 'Invalid workflow ID' }, { status: 400 }),
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id } = parsed.data.params
|
||||
|
||||
const rawBody = await parseOptionalJsonBody(request)
|
||||
if (!rawBody.success) return rawBody.response
|
||||
const body = v1RollbackWorkflowBodySchema.safeParse(rawBody.data ?? {})
|
||||
if (!body.success) {
|
||||
return validationErrorResponse(body.error)
|
||||
}
|
||||
|
||||
const target = await resolveV1DeploymentWorkflow(rateLimit, userId, id)
|
||||
if (!target.ok) return target.response
|
||||
const { workflow, workspaceId } = target
|
||||
|
||||
if (!workflow.isDeployed) {
|
||||
return NextResponse.json({ error: 'Workflow is not deployed' }, { status: 400 })
|
||||
}
|
||||
|
||||
await assertWorkflowMutable(id)
|
||||
|
||||
let targetVersion = body.data.version
|
||||
if (targetVersion === undefined) {
|
||||
const previous = await findPreviousDeploymentVersion(id)
|
||||
if (!previous.ok) {
|
||||
const message =
|
||||
previous.reason === 'no_active_version'
|
||||
? 'Workflow has no active deployment to roll back from'
|
||||
: 'No previous deployment version to roll back to'
|
||||
return NextResponse.json({ error: message }, { status: 400 })
|
||||
}
|
||||
targetVersion = previous.version
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Rolling back workflow ${id} to version ${targetVersion} via v1 API`,
|
||||
{ userId }
|
||||
)
|
||||
|
||||
const result = await performActivateVersion({
|
||||
workflowId: id,
|
||||
version: targetVersion,
|
||||
userId,
|
||||
workflow: workflow as Record<string, unknown>,
|
||||
requestId,
|
||||
request,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return NextResponse.json(
|
||||
{ error: result.error || 'Failed to roll back workflow' },
|
||||
{ status: statusForOrchestrationError(result.errorCode) }
|
||||
)
|
||||
}
|
||||
|
||||
captureServerEvent(
|
||||
userId,
|
||||
'deployment_version_activated',
|
||||
{ workflow_id: id, workspace_id: workspaceId, version: targetVersion },
|
||||
{ groups: { workspace: workspaceId } }
|
||||
)
|
||||
|
||||
const limits = await getUserLimits(userId)
|
||||
const apiResponse = createApiResponse(
|
||||
{
|
||||
data: {
|
||||
id,
|
||||
isDeployed: true,
|
||||
deployedAt: result.deployedAt?.toISOString() ?? null,
|
||||
version: targetVersion,
|
||||
warnings: result.warnings ?? [],
|
||||
},
|
||||
},
|
||||
limits,
|
||||
rateLimit
|
||||
)
|
||||
|
||||
return NextResponse.json(apiResponse.body, { headers: apiResponse.headers })
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof WorkflowLockedError) {
|
||||
return NextResponse.json({ error: error.message }, { status: error.status })
|
||||
}
|
||||
const message = getErrorMessage(error, 'Unknown error')
|
||||
logger.error(`[${requestId}] Workflow rollback error`, { error: message })
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user