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
|
||||
*/
|
||||
import {
|
||||
authMockFns,
|
||||
hybridAuthMockFns,
|
||||
storageServiceMock,
|
||||
storageServiceMockFns,
|
||||
} from '@sim/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const mockVerifyFileAccess = vi.fn()
|
||||
const mockVerifyWorkspaceFileAccess = vi.fn()
|
||||
const mockGetStorageProvider = vi.fn()
|
||||
const mockIsUsingCloudStorage = vi.fn()
|
||||
|
||||
return {
|
||||
mockVerifyFileAccess,
|
||||
mockVerifyWorkspaceFileAccess,
|
||||
mockGetStorageProvider,
|
||||
mockIsUsingCloudStorage,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('drizzle-orm', () => ({
|
||||
and: vi.fn((...conditions: unknown[]) => ({ conditions, type: 'and' })),
|
||||
eq: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'eq' })),
|
||||
or: vi.fn((...conditions: unknown[]) => ({ type: 'or', conditions })),
|
||||
gte: vi.fn((field: unknown, value: unknown) => ({ type: 'gte', field, value })),
|
||||
lte: vi.fn((field: unknown, value: unknown) => ({ type: 'lte', field, value })),
|
||||
gt: vi.fn((field: unknown, value: unknown) => ({ type: 'gt', field, value })),
|
||||
lt: vi.fn((field: unknown, value: unknown) => ({ type: 'lt', field, value })),
|
||||
ne: vi.fn((field: unknown, value: unknown) => ({ type: 'ne', field, value })),
|
||||
asc: vi.fn((field: unknown) => ({ field, type: 'asc' })),
|
||||
desc: vi.fn((field: unknown) => ({ field, type: 'desc' })),
|
||||
isNull: vi.fn((field: unknown) => ({ field, type: 'isNull' })),
|
||||
isNotNull: vi.fn((field: unknown) => ({ field, type: 'isNotNull' })),
|
||||
inArray: vi.fn((field: unknown, values: unknown) => ({ field, values, type: 'inArray' })),
|
||||
notInArray: vi.fn((field: unknown, values: unknown) => ({ field, values, type: 'notInArray' })),
|
||||
like: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'like' })),
|
||||
ilike: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'ilike' })),
|
||||
count: vi.fn((field: unknown) => ({ field, type: 'count' })),
|
||||
sum: vi.fn((field: unknown) => ({ field, type: 'sum' })),
|
||||
avg: vi.fn((field: unknown) => ({ field, type: 'avg' })),
|
||||
min: vi.fn((field: unknown) => ({ field, type: 'min' })),
|
||||
max: vi.fn((field: unknown) => ({ field, type: 'max' })),
|
||||
sql: vi.fn((strings: unknown, ...values: unknown[]) => ({ type: 'sql', sql: strings, values })),
|
||||
}))
|
||||
|
||||
vi.mock('@sim/utils/id', () => ({
|
||||
generateId: vi.fn(() => 'test-uuid'),
|
||||
generateShortId: vi.fn(() => 'mock-short-id'),
|
||||
isValidUuid: vi.fn((v: string) =>
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v)
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/api/files/authorization', () => ({
|
||||
verifyFileAccess: mocks.mockVerifyFileAccess,
|
||||
verifyWorkspaceFileAccess: mocks.mockVerifyWorkspaceFileAccess,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/uploads', () => ({
|
||||
getStorageProvider: mocks.mockGetStorageProvider,
|
||||
isUsingCloudStorage: mocks.mockIsUsingCloudStorage,
|
||||
StorageService: {
|
||||
uploadFile: storageServiceMockFns.mockUploadFile,
|
||||
downloadFile: storageServiceMockFns.mockDownloadFile,
|
||||
deleteFile: storageServiceMockFns.mockDeleteFile,
|
||||
hasCloudStorage: storageServiceMockFns.mockHasCloudStorage,
|
||||
},
|
||||
uploadFile: storageServiceMockFns.mockUploadFile,
|
||||
downloadFile: storageServiceMockFns.mockDownloadFile,
|
||||
deleteFile: storageServiceMockFns.mockDeleteFile,
|
||||
hasCloudStorage: storageServiceMockFns.mockHasCloudStorage,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/uploads/core/storage-service', () => storageServiceMock)
|
||||
|
||||
vi.mock('@/lib/uploads/server/metadata', () => ({
|
||||
deleteFileMetadata: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/uploads/setup.server', () => ({}))
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
access: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockResolvedValue({ isFile: () => true }),
|
||||
}))
|
||||
|
||||
import { createMockRequest } from '@sim/testing'
|
||||
import { POST } from '@/app/api/files/delete/route'
|
||||
|
||||
describe('File Delete API Route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
vi.stubGlobal('crypto', {
|
||||
randomUUID: vi.fn().mockReturnValue('mock-uuid-1234-5678'),
|
||||
})
|
||||
|
||||
authMockFns.mockGetSession.mockResolvedValue({ user: { id: 'test-user-id' } })
|
||||
hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({
|
||||
success: true,
|
||||
userId: 'test-user-id',
|
||||
error: undefined,
|
||||
})
|
||||
mocks.mockVerifyFileAccess.mockResolvedValue(true)
|
||||
mocks.mockVerifyWorkspaceFileAccess.mockResolvedValue(true)
|
||||
storageServiceMockFns.mockDeleteFile.mockResolvedValue(undefined)
|
||||
storageServiceMockFns.mockHasCloudStorage.mockReturnValue(true)
|
||||
mocks.mockGetStorageProvider.mockReturnValue('s3')
|
||||
mocks.mockIsUsingCloudStorage.mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('should handle local file deletion successfully', async () => {
|
||||
storageServiceMockFns.mockHasCloudStorage.mockReturnValue(false)
|
||||
mocks.mockGetStorageProvider.mockReturnValue('local')
|
||||
mocks.mockIsUsingCloudStorage.mockReturnValue(false)
|
||||
|
||||
const req = createMockRequest('POST', {
|
||||
filePath: '/api/files/serve/workspace/test-workspace-id/test-file.txt',
|
||||
})
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('success', true)
|
||||
expect(data).toHaveProperty('message')
|
||||
expect(['File deleted successfully', "File not found, but that's okay"]).toContain(data.message)
|
||||
})
|
||||
|
||||
it('should handle file not found gracefully', async () => {
|
||||
storageServiceMockFns.mockHasCloudStorage.mockReturnValue(false)
|
||||
mocks.mockGetStorageProvider.mockReturnValue('local')
|
||||
mocks.mockIsUsingCloudStorage.mockReturnValue(false)
|
||||
|
||||
const req = createMockRequest('POST', {
|
||||
filePath: '/api/files/serve/workspace/test-workspace-id/nonexistent.txt',
|
||||
})
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('success', true)
|
||||
expect(data).toHaveProperty('message')
|
||||
})
|
||||
|
||||
it('should handle S3 file deletion successfully', async () => {
|
||||
const req = createMockRequest('POST', {
|
||||
filePath: '/api/files/serve/workspace/test-workspace-id/1234567890-test-file.txt',
|
||||
})
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('success', true)
|
||||
expect(data).toHaveProperty('message', 'File deleted successfully')
|
||||
|
||||
expect(storageServiceMockFns.mockDeleteFile).toHaveBeenCalledWith({
|
||||
key: 'workspace/test-workspace-id/1234567890-test-file.txt',
|
||||
context: 'workspace',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle Azure Blob file deletion successfully', async () => {
|
||||
mocks.mockGetStorageProvider.mockReturnValue('blob')
|
||||
|
||||
const req = createMockRequest('POST', {
|
||||
filePath: '/api/files/serve/workspace/test-workspace-id/1234567890-test-document.pdf',
|
||||
})
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(data).toHaveProperty('success', true)
|
||||
expect(data).toHaveProperty('message', 'File deleted successfully')
|
||||
|
||||
expect(storageServiceMockFns.mockDeleteFile).toHaveBeenCalledWith({
|
||||
key: 'workspace/test-workspace-id/1234567890-test-document.pdf',
|
||||
context: 'workspace',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle missing file path', async () => {
|
||||
const req = createMockRequest('POST', {})
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data).toHaveProperty('error', 'InvalidRequestError')
|
||||
expect(data).toHaveProperty('message', 'No file path provided')
|
||||
})
|
||||
|
||||
it('rejects a client context that disagrees with the key prefix', async () => {
|
||||
const req = createMockRequest('POST', {
|
||||
filePath: '/api/files/serve/s3/workspace/victim-ws/1234-report.pdf',
|
||||
context: 'og-images',
|
||||
})
|
||||
|
||||
const response = await POST(req)
|
||||
const data = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(data).toHaveProperty('error', 'InvalidRequestError')
|
||||
expect(mocks.mockVerifyFileAccess).not.toHaveBeenCalled()
|
||||
expect(storageServiceMockFns.mockDeleteFile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { fileDeleteContract } from '@/lib/api/contracts/storage-transfer'
|
||||
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import type { StorageContext } from '@/lib/uploads/config'
|
||||
import { deleteFile, hasCloudStorage } from '@/lib/uploads/core/storage-service'
|
||||
import { deleteFileMetadata } from '@/lib/uploads/server/metadata'
|
||||
import { extractStorageKey, inferContextFromKey } from '@/lib/uploads/utils/file-utils'
|
||||
import { verifyFileAccess, verifyKBFileWriteAccess } from '@/app/api/files/authorization'
|
||||
import {
|
||||
createErrorResponse,
|
||||
createSuccessResponse,
|
||||
extractFilename,
|
||||
FileNotFoundError,
|
||||
InvalidRequestError,
|
||||
} from '@/app/api/files/utils'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('FilesDeleteAPI')
|
||||
|
||||
/**
|
||||
* Main API route handler for file deletion
|
||||
*/
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
|
||||
|
||||
if (!authResult.success || !authResult.userId) {
|
||||
logger.warn('Unauthorized file delete request', {
|
||||
error: authResult.error || 'Missing userId',
|
||||
})
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = authResult.userId
|
||||
|
||||
const parsed = await parseRequest(
|
||||
fileDeleteContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
createErrorResponse(
|
||||
new InvalidRequestError(getValidationErrorMessage(error, 'Invalid request data'))
|
||||
),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { filePath, context } = parsed.data.body
|
||||
|
||||
logger.info('File delete request received:', { filePath, context, userId })
|
||||
|
||||
if (!filePath) {
|
||||
throw new InvalidRequestError('No file path provided')
|
||||
}
|
||||
|
||||
try {
|
||||
const key = extractStorageKeyFromPath(filePath)
|
||||
|
||||
// Derive context from the trusted key prefix, never the client-supplied value; a supplied context must agree with the key.
|
||||
const storageContext: StorageContext = inferContextFromKey(key)
|
||||
if (context && context !== storageContext) {
|
||||
logger.warn('File delete context mismatch', { key, context, inferred: storageContext })
|
||||
throw new InvalidRequestError(`Provided context "${context}" does not match the file key`)
|
||||
}
|
||||
|
||||
// Deletes require write/admin on the owning workspace; KB deletes are binding-only with no read fallback.
|
||||
const hasAccess =
|
||||
storageContext === 'knowledge-base'
|
||||
? await verifyKBFileWriteAccess(key, userId)
|
||||
: await verifyFileAccess(key, userId, undefined, storageContext, !hasCloudStorage(), {
|
||||
requireWrite: true,
|
||||
})
|
||||
|
||||
if (!hasAccess) {
|
||||
logger.warn('Unauthorized file delete attempt', { userId, key, context: storageContext })
|
||||
throw new FileNotFoundError(`File not found: ${key}`)
|
||||
}
|
||||
|
||||
logger.info(`Deleting file with key: ${key}, context: ${storageContext}`)
|
||||
|
||||
await deleteFile({
|
||||
key,
|
||||
context: storageContext,
|
||||
})
|
||||
await deleteFileMetadata(key)
|
||||
|
||||
logger.info(`File successfully deleted: ${key}`)
|
||||
|
||||
return createSuccessResponse({
|
||||
success: true,
|
||||
message: 'File deleted successfully',
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Error deleting file:', error)
|
||||
|
||||
if (error instanceof FileNotFoundError) {
|
||||
return createErrorResponse(error)
|
||||
}
|
||||
|
||||
return createErrorResponse(
|
||||
error instanceof Error ? error : new Error('Failed to delete file')
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error parsing request:', error)
|
||||
return createErrorResponse(error instanceof Error ? error : new Error('Invalid request'))
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Extract storage key from file path
|
||||
*/
|
||||
function extractStorageKeyFromPath(filePath: string): string {
|
||||
if (filePath.startsWith('/api/files/serve/')) {
|
||||
return extractStorageKey(filePath)
|
||||
}
|
||||
|
||||
return extractFilename(filePath)
|
||||
}
|
||||
Reference in New Issue
Block a user