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,124 @@
|
||||
/**
|
||||
* Tests for the folder reorder API route.
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { authMockFns, createMockRequest, permissionsMock, permissionsMockFns } from '@sim/testing'
|
||||
import { drizzleOrmMock } from '@sim/testing/mocks'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockLogger } = vi.hoisted(() => ({
|
||||
mockLogger: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
trace: vi.fn(),
|
||||
fatal: vi.fn(),
|
||||
child: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockGetUserEntityPermissions = permissionsMockFns.mockGetUserEntityPermissions
|
||||
|
||||
vi.mock('drizzle-orm', () => drizzleOrmMock)
|
||||
vi.mock('@sim/logger', () => ({
|
||||
createLogger: vi.fn().mockReturnValue(mockLogger),
|
||||
runWithRequestContext: <T>(_ctx: unknown, fn: () => T): T => fn(),
|
||||
getRequestContext: () => undefined,
|
||||
}))
|
||||
vi.mock('@/lib/workspaces/permissions/utils', () => permissionsMock)
|
||||
|
||||
import { db } from '@sim/db'
|
||||
import { PUT } from '@/app/api/folders/reorder/route'
|
||||
|
||||
const mockDb = db as any
|
||||
|
||||
describe('PUT /api/folders/reorder', () => {
|
||||
const mockFrom = vi.fn()
|
||||
const mockWhere = vi.fn()
|
||||
const mockTxUpdate = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'user-123' } })
|
||||
mockGetUserEntityPermissions.mockResolvedValue('admin')
|
||||
|
||||
mockDb.select.mockReturnValue({ from: mockFrom })
|
||||
mockFrom.mockReturnValue({ where: mockWhere })
|
||||
|
||||
mockTxUpdate.mockReturnValue({
|
||||
set: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(undefined) }),
|
||||
})
|
||||
mockDb.transaction.mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) =>
|
||||
cb({ update: mockTxUpdate })
|
||||
)
|
||||
})
|
||||
|
||||
it('reorders folders when updates are valid', async () => {
|
||||
mockWhere
|
||||
.mockReturnValueOnce([{ id: 'folder-1', workspaceId: 'workspace-123' }])
|
||||
.mockReturnValueOnce([{ id: 'folder-1', parentId: null }])
|
||||
|
||||
const req = createMockRequest('PUT', {
|
||||
workspaceId: 'workspace-123',
|
||||
updates: [{ id: 'folder-1', sortOrder: 2, parentId: null }],
|
||||
})
|
||||
|
||||
const response = await PUT(req)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const data = await response.json()
|
||||
expect(data).toMatchObject({ success: true, updated: 1 })
|
||||
})
|
||||
|
||||
it('rejects a parentId that belongs to another workspace', async () => {
|
||||
mockWhere
|
||||
.mockReturnValueOnce([{ id: 'folder-1', workspaceId: 'workspace-123' }])
|
||||
.mockReturnValueOnce([{ id: 'foreign', workspaceId: 'workspace-OTHER', archivedAt: null }])
|
||||
|
||||
const req = createMockRequest('PUT', {
|
||||
workspaceId: 'workspace-123',
|
||||
updates: [{ id: 'folder-1', sortOrder: 0, parentId: 'foreign' }],
|
||||
})
|
||||
|
||||
const response = await PUT(req)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const data = await response.json()
|
||||
expect(data.error).toBe('Parent folder not found')
|
||||
expect(mockDb.transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a batch that would form a cycle', async () => {
|
||||
mockWhere
|
||||
.mockReturnValueOnce([
|
||||
{ id: 'A', workspaceId: 'workspace-123' },
|
||||
{ id: 'B', workspaceId: 'workspace-123' },
|
||||
])
|
||||
.mockReturnValueOnce([
|
||||
{ id: 'A', workspaceId: 'workspace-123', archivedAt: null },
|
||||
{ id: 'B', workspaceId: 'workspace-123', archivedAt: null },
|
||||
])
|
||||
.mockReturnValueOnce([
|
||||
{ id: 'A', parentId: null },
|
||||
{ id: 'B', parentId: null },
|
||||
])
|
||||
|
||||
const req = createMockRequest('PUT', {
|
||||
workspaceId: 'workspace-123',
|
||||
updates: [
|
||||
{ id: 'A', sortOrder: 0, parentId: 'B' },
|
||||
{ id: 'B', sortOrder: 0, parentId: 'A' },
|
||||
],
|
||||
})
|
||||
|
||||
const response = await PUT(req)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const data = await response.json()
|
||||
expect(data.error).toBe('Cannot create circular folder reference')
|
||||
expect(mockDb.transaction).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import { db } from '@sim/db'
|
||||
import { workflowFolder } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { assertFolderMutable, FolderLockedError } from '@sim/platform-authz/workflow'
|
||||
import { eq, inArray } from 'drizzle-orm'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { reorderFoldersContract } from '@/lib/api/contracts'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
||||
|
||||
const logger = createLogger('FolderReorderAPI')
|
||||
|
||||
export const PUT = withRouteHandler(async (req: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
const session = await getSession()
|
||||
|
||||
if (!session?.user?.id) {
|
||||
logger.warn(`[${requestId}] Unauthorized folder reorder attempt`)
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = await parseRequest(reorderFoldersContract, req, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
const { workspaceId, updates } = parsed.data.body
|
||||
|
||||
const permission = await getUserEntityPermissions(session.user.id, 'workspace', workspaceId)
|
||||
if (!permission || permission === 'read') {
|
||||
logger.warn(
|
||||
`[${requestId}] User ${session.user.id} lacks write permission for workspace ${workspaceId}`
|
||||
)
|
||||
return NextResponse.json({ error: 'Write access required' }, { status: 403 })
|
||||
}
|
||||
|
||||
const folderIds = updates.map((u) => u.id)
|
||||
const existingFolders = await db
|
||||
.select({ id: workflowFolder.id, workspaceId: workflowFolder.workspaceId })
|
||||
.from(workflowFolder)
|
||||
.where(inArray(workflowFolder.id, folderIds))
|
||||
|
||||
const validIds = new Set(
|
||||
existingFolders.filter((f) => f.workspaceId === workspaceId).map((f) => f.id)
|
||||
)
|
||||
|
||||
const validUpdates = updates.filter((u) => validIds.has(u.id))
|
||||
|
||||
if (validUpdates.length === 0) {
|
||||
return NextResponse.json({ error: 'No valid folders to update' }, { status: 400 })
|
||||
}
|
||||
|
||||
const targetParentIds = Array.from(
|
||||
new Set(validUpdates.map((u) => u.parentId).filter((id): id is string => Boolean(id)))
|
||||
)
|
||||
|
||||
if (targetParentIds.length > 0) {
|
||||
const parentFolders = await db
|
||||
.select({
|
||||
id: workflowFolder.id,
|
||||
workspaceId: workflowFolder.workspaceId,
|
||||
archivedAt: workflowFolder.archivedAt,
|
||||
})
|
||||
.from(workflowFolder)
|
||||
.where(inArray(workflowFolder.id, targetParentIds))
|
||||
|
||||
const validParentIds = new Set(
|
||||
parentFolders.filter((f) => f.workspaceId === workspaceId && !f.archivedAt).map((f) => f.id)
|
||||
)
|
||||
|
||||
for (const update of validUpdates) {
|
||||
if (!update.parentId) continue
|
||||
if (update.parentId === update.id) {
|
||||
return NextResponse.json({ error: 'Folder cannot be its own parent' }, { status: 400 })
|
||||
}
|
||||
if (!validParentIds.has(update.parentId)) {
|
||||
return NextResponse.json({ error: 'Parent folder not found' }, { status: 400 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const workspaceFolders = await db
|
||||
.select({ id: workflowFolder.id, parentId: workflowFolder.parentId })
|
||||
.from(workflowFolder)
|
||||
.where(eq(workflowFolder.workspaceId, workspaceId))
|
||||
|
||||
const parentById = new Map<string, string | null>()
|
||||
for (const folder of workspaceFolders) {
|
||||
parentById.set(folder.id, folder.parentId)
|
||||
}
|
||||
for (const update of validUpdates) {
|
||||
if (update.parentId !== undefined) {
|
||||
parentById.set(update.id, update.parentId || null)
|
||||
}
|
||||
}
|
||||
|
||||
for (const update of validUpdates) {
|
||||
const visited = new Set<string>()
|
||||
let cursor: string | null = update.id
|
||||
while (cursor) {
|
||||
if (visited.has(cursor)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cannot create circular folder reference' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
visited.add(cursor)
|
||||
cursor = parentById.get(cursor) ?? null
|
||||
}
|
||||
}
|
||||
|
||||
for (const update of validUpdates) {
|
||||
await assertFolderMutable(update.id)
|
||||
if (update.parentId !== undefined) {
|
||||
await assertFolderMutable(update.parentId)
|
||||
}
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
for (const update of validUpdates) {
|
||||
const updateData: Record<string, unknown> = {
|
||||
sortOrder: update.sortOrder,
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
if (update.parentId !== undefined) {
|
||||
updateData.parentId = update.parentId || null
|
||||
}
|
||||
await tx.update(workflowFolder).set(updateData).where(eq(workflowFolder.id, update.id))
|
||||
}
|
||||
})
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] Reordered ${validUpdates.length} folders in workspace ${workspaceId}`
|
||||
)
|
||||
|
||||
return NextResponse.json({ success: true, updated: validUpdates.length })
|
||||
} catch (error) {
|
||||
if (error instanceof FolderLockedError) {
|
||||
return NextResponse.json({ error: error.message }, { status: error.status })
|
||||
}
|
||||
|
||||
logger.error(`[${requestId}] Error reordering folders`, error)
|
||||
return NextResponse.json({ error: 'Failed to reorder folders' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user