-
Notifications
You must be signed in to change notification settings - Fork 3.4k
fix(workflows): harden workflow API auth routes #3559
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PlaneInABottle
wants to merge
21
commits into
simstudioai:staging
Choose a base branch
from
PlaneInABottle:fix/workflow-api-auth-hardening
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,705
−224
Open
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
507c84f
fix(workflows): tighten shared workflow access validation
PlaneInABottle 2b05c74
fix(workflows): allow app auth on workflow lifecycle actions
PlaneInABottle 46b46fb
fix(workflows): support app auth on deployment routes
PlaneInABottle 0616aa6
fix: harden workflow API auth routes
PlaneInABottle 7b31f55
fix: harden workflow API auth follow-ups
PlaneInABottle 5499177
fix: align workflow audit actors for API keys
PlaneInABottle 39c014a
fix: align workflow audit metadata helpers
PlaneInABottle 2c267c0
refactor: inline workflow access wrappers
PlaneInABottle 2d4271d
test(workflows): fix auth route lint issues
5493e78
fix(workflows): sync MCP tools on revert
965e9ac
test(workflows): stabilize async route queue mocks
abbf8c9
fix(workflows): enforce deployment patch auth ordering
8bb57d4
test(workflows): reset async route mocks between tests
818e477
test(workflows): deflake workflow route auth tests
cd24443
fix(workflows): preserve auth ordering and harden async tests
ecee883
test(workflows): fix AuthType mock shape in async route test
d3d15e6
Merge upstream/staging into fix/workflow-api-auth-hardening
866dd93
fix(workflows): harden deployment auth and audit actor metadata
a2aaddb
fix(workflows): remove dead deployment actor guard
3103042
fix(workflows): scope workspace API keys to workflow access
ce2ed79
fix(workflows): use AuthType enum in middleware auth checks
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,239 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
|
|
||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { | ||
| mockCleanupWebhooksForWorkflow, | ||
| mockRecordAudit, | ||
| mockDbLimit, | ||
| mockDbOrderBy, | ||
| mockDbFrom, | ||
| mockDbSelect, | ||
| mockDbSet, | ||
| mockDbUpdate, | ||
| mockDbWhere, | ||
| mockCreateSchedulesForDeploy, | ||
| mockDeployWorkflow, | ||
| mockLoadWorkflowFromNormalizedTables, | ||
| mockRemoveMcpToolsForWorkflow, | ||
| mockSaveTriggerWebhooksForDeploy, | ||
| mockSyncMcpToolsForWorkflow, | ||
| mockUndeployWorkflow, | ||
| mockValidatePublicApiAllowed, | ||
| mockValidateWorkflowAccess, | ||
| mockValidateWorkflowPermissions, | ||
| } = vi.hoisted(() => ({ | ||
| mockCleanupWebhooksForWorkflow: vi.fn(), | ||
| mockRecordAudit: vi.fn(), | ||
| mockDbLimit: vi.fn(), | ||
| mockDbOrderBy: vi.fn(), | ||
| mockDbFrom: vi.fn(), | ||
| mockDbSelect: vi.fn(), | ||
| mockDbSet: vi.fn(), | ||
| mockDbUpdate: vi.fn(), | ||
| mockDbWhere: vi.fn(), | ||
| mockCreateSchedulesForDeploy: vi.fn(), | ||
| mockDeployWorkflow: vi.fn(), | ||
| mockLoadWorkflowFromNormalizedTables: vi.fn(), | ||
| mockRemoveMcpToolsForWorkflow: vi.fn(), | ||
| mockSaveTriggerWebhooksForDeploy: vi.fn(), | ||
| mockSyncMcpToolsForWorkflow: vi.fn(), | ||
| mockUndeployWorkflow: vi.fn(), | ||
| mockValidatePublicApiAllowed: vi.fn(), | ||
| mockValidateWorkflowAccess: vi.fn(), | ||
| mockValidateWorkflowPermissions: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@sim/logger', () => ({ | ||
| createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/workflows/utils', () => ({ | ||
| validateWorkflowPermissions: (...args: unknown[]) => mockValidateWorkflowPermissions(...args), | ||
| })) | ||
|
|
||
| vi.mock('@/app/api/workflows/middleware', () => ({ | ||
| validateWorkflowAccess: (...args: unknown[]) => mockValidateWorkflowAccess(...args), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/core/utils/request', () => ({ | ||
| generateRequestId: () => 'req-123', | ||
| })) | ||
|
|
||
| vi.mock('@sim/db', () => ({ | ||
| db: { select: mockDbSelect, update: mockDbUpdate }, | ||
| workflow: { variables: 'variables', id: 'id' }, | ||
| workflowDeploymentVersion: { | ||
| state: 'state', | ||
| workflowId: 'workflowId', | ||
| isActive: 'isActive', | ||
| createdAt: 'createdAt', | ||
| id: 'id', | ||
| }, | ||
| })) | ||
|
|
||
| vi.mock('drizzle-orm', async (importOriginal) => { | ||
| const actual = await importOriginal<typeof import('drizzle-orm')>() | ||
| return { | ||
| ...actual, | ||
| and: vi.fn(), | ||
| desc: vi.fn(), | ||
| eq: vi.fn(), | ||
| } | ||
| }) | ||
|
|
||
| vi.mock('@/lib/workflows/persistence/utils', () => ({ | ||
| loadWorkflowFromNormalizedTables: (...args: unknown[]) => | ||
| mockLoadWorkflowFromNormalizedTables(...args), | ||
| deployWorkflow: (...args: unknown[]) => mockDeployWorkflow(...args), | ||
| undeployWorkflow: (...args: unknown[]) => mockUndeployWorkflow(...args), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/workflows/comparison', () => ({ | ||
| hasWorkflowChanged: vi.fn().mockReturnValue(false), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/workflows/schedules', () => ({ | ||
| cleanupDeploymentVersion: vi.fn(), | ||
| createSchedulesForDeploy: (...args: unknown[]) => mockCreateSchedulesForDeploy(...args), | ||
| validateWorkflowSchedules: vi.fn().mockReturnValue({ isValid: true }), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/webhooks/deploy', () => ({ | ||
| cleanupWebhooksForWorkflow: (...args: unknown[]) => mockCleanupWebhooksForWorkflow(...args), | ||
| restorePreviousVersionWebhooks: vi.fn(), | ||
| saveTriggerWebhooksForDeploy: (...args: unknown[]) => mockSaveTriggerWebhooksForDeploy(...args), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/mcp/workflow-mcp-sync', () => ({ | ||
| removeMcpToolsForWorkflow: (...args: unknown[]) => mockRemoveMcpToolsForWorkflow(...args), | ||
| syncMcpToolsForWorkflow: (...args: unknown[]) => mockSyncMcpToolsForWorkflow(...args), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/audit/log', () => ({ | ||
| AuditAction: {}, | ||
| AuditResourceType: {}, | ||
| recordAudit: (...args: unknown[]) => mockRecordAudit(...args), | ||
| })) | ||
|
|
||
| vi.mock('@/ee/access-control/utils/permission-check', () => ({ | ||
| PublicApiNotAllowedError: class PublicApiNotAllowedError extends Error {}, | ||
| validatePublicApiAllowed: (...args: unknown[]) => mockValidatePublicApiAllowed(...args), | ||
| })) | ||
|
|
||
| import { DELETE, PATCH, POST } from '@/app/api/workflows/[id]/deploy/route' | ||
|
|
||
| describe('Workflow deploy route', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockDbSelect.mockReturnValue({ from: mockDbFrom }) | ||
| mockDbFrom.mockReturnValue({ where: mockDbWhere }) | ||
| mockDbWhere.mockReturnValue({ limit: mockDbLimit, orderBy: mockDbOrderBy }) | ||
| mockDbOrderBy.mockReturnValue({ limit: mockDbLimit }) | ||
| mockDbLimit.mockResolvedValue([]) | ||
| mockDbUpdate.mockReturnValue({ set: mockDbSet }) | ||
| mockDbSet.mockReturnValue({ where: mockDbWhere }) | ||
| mockCleanupWebhooksForWorkflow.mockResolvedValue(undefined) | ||
| mockCreateSchedulesForDeploy.mockResolvedValue({ success: true }) | ||
| mockLoadWorkflowFromNormalizedTables.mockResolvedValue({ | ||
| blocks: { 'block-1': { id: 'block-1', type: 'start_trigger', name: 'Start' } }, | ||
| edges: [], | ||
| loops: {}, | ||
| parallels: {}, | ||
| }) | ||
| mockSaveTriggerWebhooksForDeploy.mockResolvedValue({ success: true, warnings: [] }) | ||
| mockRemoveMcpToolsForWorkflow.mockResolvedValue(undefined) | ||
| mockSyncMcpToolsForWorkflow.mockResolvedValue(undefined) | ||
| mockValidatePublicApiAllowed.mockResolvedValue(undefined) | ||
| }) | ||
|
|
||
| it('allows API-key auth for deploy using hybrid auth userId', async () => { | ||
| mockValidateWorkflowAccess.mockResolvedValue({ | ||
| workflow: { id: 'wf-1', name: 'Test Workflow', workspaceId: 'ws-1' }, | ||
| auth: { | ||
| success: true, | ||
| userId: 'api-user', | ||
| authType: 'api_key', | ||
| }, | ||
| }) | ||
| mockDeployWorkflow.mockResolvedValue({ | ||
| success: true, | ||
| deployedAt: '2024-01-01T00:00:00Z', | ||
| deploymentVersionId: 'dep-1', | ||
| }) | ||
|
|
||
| const req = new NextRequest('http://localhost:3000/api/workflows/wf-1/deploy', { | ||
| method: 'POST', | ||
| headers: { 'x-api-key': 'test-key' }, | ||
| }) | ||
| const response = await POST(req, { params: Promise.resolve({ id: 'wf-1' }) }) | ||
|
|
||
| expect(response.status).toBe(200) | ||
| const data = await response.json() | ||
| expect(data.isDeployed).toBe(true) | ||
| expect(mockDeployWorkflow).toHaveBeenCalledWith({ | ||
| workflowId: 'wf-1', | ||
| deployedBy: 'api-user', | ||
| workflowName: 'Test Workflow', | ||
| }) | ||
| expect(mockValidateWorkflowPermissions).not.toHaveBeenCalled() | ||
| expect(mockRecordAudit).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| actorId: 'api-user', | ||
| actorName: undefined, | ||
| actorEmail: undefined, | ||
| }) | ||
| ) | ||
| }) | ||
|
|
||
| it('allows API-key auth for undeploy using hybrid auth userId', async () => { | ||
| mockValidateWorkflowAccess.mockResolvedValue({ | ||
| workflow: { id: 'wf-1', name: 'Test Workflow', workspaceId: 'ws-1' }, | ||
| auth: { | ||
| success: true, | ||
| userId: 'api-user', | ||
| authType: 'api_key', | ||
| }, | ||
| }) | ||
| mockUndeployWorkflow.mockResolvedValue({ success: true }) | ||
|
|
||
| const req = new NextRequest('http://localhost:3000/api/workflows/wf-1/deploy', { | ||
| method: 'DELETE', | ||
| headers: { 'x-api-key': 'test-key' }, | ||
| }) | ||
| const response = await DELETE(req, { params: Promise.resolve({ id: 'wf-1' }) }) | ||
|
|
||
| expect(response.status).toBe(200) | ||
| const data = await response.json() | ||
| expect(data.isDeployed).toBe(false) | ||
| expect(mockUndeployWorkflow).toHaveBeenCalledWith({ workflowId: 'wf-1' }) | ||
| expect(mockValidateWorkflowPermissions).not.toHaveBeenCalled() | ||
| expect(mockRecordAudit).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| actorId: 'api-user', | ||
| actorName: undefined, | ||
| actorEmail: undefined, | ||
| }) | ||
| ) | ||
| }) | ||
|
|
||
| it('checks public API restrictions against hybrid auth userId', async () => { | ||
| mockValidateWorkflowAccess.mockResolvedValue({ | ||
| workflow: { id: 'wf-1', name: 'Test Workflow', workspaceId: 'ws-1' }, | ||
| auth: { success: true, userId: 'api-user', authType: 'api_key' }, | ||
| }) | ||
|
|
||
| const req = new NextRequest('http://localhost:3000/api/workflows/wf-1/deploy', { | ||
| method: 'PATCH', | ||
| headers: { 'content-type': 'application/json', 'x-api-key': 'test-key' }, | ||
| body: JSON.stringify({ isPublicApi: true }), | ||
| }) | ||
| const response = await PATCH(req, { params: Promise.resolve({ id: 'wf-1' }) }) | ||
|
|
||
| expect(response.status).toBe(200) | ||
| expect(mockValidatePublicApiAllowed).toHaveBeenCalledWith('api-user') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.