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

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,129 @@
/**
* @vitest-environment node
*
* Tests for GET /api/v1/audit-logs/[id] — verifies the lookup is constrained
* by the organization scope and 404s for rows outside it.
*/
import { createMockRequest, dbChainMock, dbChainMockFns } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockCheckRateLimit,
mockValidateEnterpriseAuditAccess,
mockBuildOrgScopeCondition,
mockGetOrgWorkspaceIds,
} = vi.hoisted(() => ({
mockCheckRateLimit: vi.fn(),
mockValidateEnterpriseAuditAccess: vi.fn(),
mockBuildOrgScopeCondition: vi.fn(),
mockGetOrgWorkspaceIds: vi.fn(),
}))
vi.mock('@sim/db', () => dbChainMock)
vi.mock('@/app/api/v1/middleware', () => ({
checkRateLimit: mockCheckRateLimit,
createRateLimitResponse: vi.fn(),
}))
vi.mock('@/app/api/v1/audit-logs/auth', () => ({
validateEnterpriseAuditAccess: mockValidateEnterpriseAuditAccess,
}))
vi.mock('@/app/api/v1/audit-logs/query', () => ({
buildOrgScopeCondition: mockBuildOrgScopeCondition,
getOrgWorkspaceIds: mockGetOrgWorkspaceIds,
}))
vi.mock('@/app/api/v1/logs/meta', () => ({
getUserLimits: vi.fn().mockResolvedValue({}),
createApiResponse: vi.fn((body: unknown) => ({ body, headers: {} })),
}))
import { GET } from '@/app/api/v1/audit-logs/[id]/route'
const ORG_ID = 'org-1'
const MEMBER_IDS = ['admin-1', 'member-1']
const ORG_WORKSPACE_IDS = ['ws-org-1']
const SCOPE_SENTINEL = { type: 'org-scope-sentinel' }
const AUDIT_ROW = {
id: 'log-1',
workspaceId: 'ws-org-1',
actorId: 'member-1',
actorName: 'Member',
actorEmail: 'member@example.com',
action: 'workflow.created',
resourceType: 'workflow',
resourceId: 'wf-1',
resourceName: 'My Workflow',
description: 'Created workflow',
metadata: {},
ipAddress: '127.0.0.1',
userAgent: 'test',
createdAt: new Date('2026-01-01T00:00:00Z'),
}
function callRoute(id: string) {
const request = createMockRequest(
'GET',
undefined,
{},
`http://localhost:3000/api/v1/audit-logs/${id}`
)
return GET(request, { params: Promise.resolve({ id }) })
}
describe('GET /api/v1/audit-logs/[id]', () => {
beforeEach(() => {
vi.clearAllMocks()
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'admin-1' })
mockValidateEnterpriseAuditAccess.mockResolvedValue({
success: true,
context: { organizationId: ORG_ID, orgMemberIds: MEMBER_IDS },
})
mockGetOrgWorkspaceIds.mockResolvedValue(ORG_WORKSPACE_IDS)
mockBuildOrgScopeCondition.mockReturnValue(SCOPE_SENTINEL)
})
it('constrains the lookup with the org scope condition (includeDeparted)', async () => {
dbChainMockFns.limit.mockResolvedValueOnce([AUDIT_ROW])
const response = await callRoute('log-1')
expect(response.status).toBe(200)
expect(mockBuildOrgScopeCondition).toHaveBeenCalledWith({
organizationId: ORG_ID,
orgWorkspaceIds: ORG_WORKSPACE_IDS,
orgMemberIds: MEMBER_IDS,
includeDeparted: true,
})
expect(dbChainMockFns.where).toHaveBeenCalledWith(
expect.objectContaining({
type: 'and',
conditions: expect.arrayContaining([SCOPE_SENTINEL]),
})
)
})
it('returns 404 when the row is outside the organization scope', async () => {
dbChainMockFns.limit.mockResolvedValueOnce([])
const response = await callRoute('log-outside-org')
expect(response.status).toBe(404)
const body = await response.json()
expect(body.error).toBe('Audit log not found')
})
it('excludes ipAddress and userAgent from the response', async () => {
dbChainMockFns.limit.mockResolvedValueOnce([AUDIT_ROW])
const response = await callRoute('log-1')
const body = await response.json()
expect(body.data.id).toBe('log-1')
expect(body.data.ipAddress).toBeUndefined()
expect(body.data.userAgent).toBeUndefined()
})
})
@@ -0,0 +1,88 @@
/**
* GET /api/v1/audit-logs/[id]
*
* Get a single audit log entry by ID, scoped to the authenticated user's organization.
* Requires enterprise subscription and org admin/owner role.
*
* Scope is the organization boundary: logs within org-attached workspaces and
* org-level events (including those from departed members or system actions
* with null actorId).
*
* Response: { data: AuditLogEntry, limits: UserLimits }
*/
import { db } from '@sim/db'
import { auditLog } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { and, eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { v1GetAuditLogContract } from '@/lib/api/contracts/v1/audit-logs'
import { parseRequest } from '@/lib/api/server'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { validateEnterpriseAuditAccess } from '@/app/api/v1/audit-logs/auth'
import { formatAuditLogEntry } from '@/app/api/v1/audit-logs/format'
import { buildOrgScopeCondition, getOrgWorkspaceIds } from '@/app/api/v1/audit-logs/query'
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
import { checkRateLimit, createRateLimitResponse } from '@/app/api/v1/middleware'
const logger = createLogger('V1AuditLogDetailAPI')
export const revalidate = 0
export const GET = withRouteHandler(
async (request: NextRequest, context: { params: Promise<{ id: string }> }) => {
const requestId = generateId().slice(0, 8)
try {
const rateLimit = await checkRateLimit(request, 'audit-logs')
if (!rateLimit.allowed) {
return createRateLimitResponse(rateLimit)
}
const userId = rateLimit.userId!
const parsed = await parseRequest(v1GetAuditLogContract, request, context, {
validationErrorResponse: () =>
NextResponse.json({ error: 'Invalid audit log ID' }, { status: 400 }),
})
if (!parsed.success) return parsed.response
const { id } = parsed.data.params
const authResult = await validateEnterpriseAuditAccess(userId)
if (!authResult.success) {
return authResult.response
}
const { organizationId, orgMemberIds } = authResult.context
const orgWorkspaceIds = await getOrgWorkspaceIds(organizationId)
const scopeCondition = buildOrgScopeCondition({
organizationId,
orgWorkspaceIds,
orgMemberIds,
includeDeparted: true,
})
const [log] = await db
.select()
.from(auditLog)
.where(and(eq(auditLog.id, id), scopeCondition))
.limit(1)
if (!log) {
return NextResponse.json({ error: 'Audit log not found' }, { status: 404 })
}
const limits = await getUserLimits(userId)
const response = createApiResponse({ data: formatAuditLogEntry(log) }, limits, rateLimit)
return NextResponse.json(response.body, { headers: response.headers })
} catch (error: unknown) {
const message = getErrorMessage(error, 'Unknown error')
logger.error(`[${requestId}] Audit log detail fetch error`, { error: message })
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
)
+116
View File
@@ -0,0 +1,116 @@
/**
* Enterprise audit log authorization.
*
* Validates that the authenticated user is an admin/owner of an enterprise organization
* and returns the organization context needed for scoped queries.
*/
import { db } from '@sim/db'
import { member, subscription } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, inArray } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { getEffectiveBillingStatus } from '@/lib/billing/core/access'
import { USABLE_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils'
const logger = createLogger('V1AuditLogsAuth')
interface EnterpriseAuditContext {
organizationId: string
orgMemberIds: string[]
}
type AuthResult =
| { success: true; context: EnterpriseAuditContext }
| { success: false; response: NextResponse }
/**
* Validates enterprise audit log access for the given user.
*
* Checks:
* 1. User belongs to an organization
* 2. User has admin or owner role
* 3. Organization has an active enterprise subscription
*
* Returns the organization ID and all member user IDs on success,
* or an error response on failure.
*/
export async function validateEnterpriseAuditAccess(userId: string): Promise<AuthResult> {
const [membership] = await db
.select({ organizationId: member.organizationId, role: member.role })
.from(member)
.where(eq(member.userId, userId))
.limit(1)
if (!membership) {
return {
success: false,
response: NextResponse.json({ error: 'Not a member of any organization' }, { status: 403 }),
}
}
if (membership.role !== 'admin' && membership.role !== 'owner') {
return {
success: false,
response: NextResponse.json(
{ error: 'Organization admin or owner role required' },
{ status: 403 }
),
}
}
const billingStatus = await getEffectiveBillingStatus(userId)
if (billingStatus.billingBlocked) {
return {
success: false,
response: NextResponse.json(
{ error: 'Active enterprise subscription required' },
{ status: 403 }
),
}
}
const [orgSub, orgMembers] = await Promise.all([
db
.select({ id: subscription.id })
.from(subscription)
.where(
and(
eq(subscription.referenceId, membership.organizationId),
eq(subscription.plan, 'enterprise'),
inArray(subscription.status, USABLE_SUBSCRIPTION_STATUSES)
)
)
.limit(1),
db
.select({ userId: member.userId })
.from(member)
.where(eq(member.organizationId, membership.organizationId)),
])
if (orgSub.length === 0) {
return {
success: false,
response: NextResponse.json(
{ error: 'Active enterprise subscription required' },
{ status: 403 }
),
}
}
const orgMemberIds = orgMembers.map((m) => m.userId)
logger.info('Enterprise audit access validated', {
userId,
organizationId: membership.organizationId,
memberCount: orgMemberIds.length,
})
return {
success: true,
context: {
organizationId: membership.organizationId,
orgMemberIds,
},
}
}
+43
View File
@@ -0,0 +1,43 @@
/**
* Enterprise audit log response formatting.
*
* Defines the shape returned by the enterprise audit log API.
* Excludes `ipAddress` and `userAgent` for privacy.
*/
import type { auditLog } from '@sim/db/schema'
import type { InferSelectModel } from 'drizzle-orm'
type DbAuditLog = InferSelectModel<typeof auditLog>
export interface EnterpriseAuditLogEntry {
id: string
workspaceId: string | null
actorId: string | null
actorName: string | null
actorEmail: string | null
action: string
resourceType: string
resourceId: string | null
resourceName: string | null
description: string | null
metadata: unknown
createdAt: string
}
export function formatAuditLogEntry(log: DbAuditLog): EnterpriseAuditLogEntry {
return {
id: log.id,
workspaceId: log.workspaceId,
actorId: log.actorId,
actorName: log.actorName,
actorEmail: log.actorEmail,
action: log.action,
resourceType: log.resourceType,
resourceId: log.resourceId,
resourceName: log.resourceName,
description: log.description,
metadata: log.metadata,
createdAt: log.createdAt.toISOString(),
}
}
@@ -0,0 +1,172 @@
/**
* @vitest-environment node
*
* Tests for the enterprise audit-log tenant boundary. The global drizzle-orm
* mock returns structured operator objects, so these tests assert directly on
* the predicate tree.
*/
import { dbChainMock, dbChainMockFns } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@sim/db', () => dbChainMock)
import { buildOrgScopeCondition, getOrgWorkspaceIds } from '@/app/api/v1/audit-logs/query'
const ORG_ID = 'org-1'
const MEMBER_IDS = ['user-1', 'user-2']
const WORKSPACE_IDS = ['ws-1', 'ws-2']
interface MockCondition {
type?: string
conditions?: MockCondition[]
column?: string
values?: string[]
left?: string
right?: string
strings?: string[]
}
function asCondition(value: unknown): MockCondition {
return value as MockCondition
}
/**
* Asserts the condition matches null-workspace rows tied to the organization
* via metadata or the organization resource itself.
*/
function expectOrgLevelCondition(condition: MockCondition, organizationId: string): void {
expect(condition.type).toBe('and')
const [nullCheck, orgLink] = condition.conditions!
expect(nullCheck).toMatchObject({ type: 'isNull', column: 'workspaceId' })
expect(orgLink.type).toBe('or')
const [metadataMatch, orgResourceMatch] = orgLink.conditions!
expect(metadataMatch.strings?.join('?')).toContain("->>'organizationId' =")
expect(metadataMatch.values).toContain(organizationId)
expect(orgResourceMatch.type).toBe('and')
expect(orgResourceMatch.conditions).toEqual([
expect.objectContaining({ type: 'eq', left: 'resourceType', right: 'organization' }),
expect.objectContaining({ type: 'eq', left: 'resourceId', right: organizationId }),
])
}
describe('buildOrgScopeCondition', () => {
it('never uses actor membership as a standalone boundary (default scope)', () => {
const condition = asCondition(
buildOrgScopeCondition({
organizationId: ORG_ID,
orgWorkspaceIds: WORKSPACE_IDS,
orgMemberIds: MEMBER_IDS,
includeDeparted: false,
})
)
expect(condition.type).toBe('and')
const [orgScope, actorFilter] = condition.conditions!
expect(orgScope.type).toBe('or')
const [workspaceScope, orgLevel] = orgScope.conditions!
expect(workspaceScope).toMatchObject({
type: 'inArray',
column: 'workspaceId',
values: WORKSPACE_IDS,
})
expectOrgLevelCondition(orgLevel, ORG_ID)
expect(actorFilter).toMatchObject({
type: 'or',
conditions: [
expect.objectContaining({ type: 'inArray', column: 'actorId', values: MEMBER_IDS }),
expect.objectContaining({ type: 'isNull', column: 'actorId' }),
],
})
})
it('omits the actor filter entirely when includeDeparted is true', () => {
const condition = asCondition(
buildOrgScopeCondition({
organizationId: ORG_ID,
orgWorkspaceIds: WORKSPACE_IDS,
orgMemberIds: MEMBER_IDS,
includeDeparted: true,
})
)
expect(condition.type).toBe('or')
const [workspaceScope, orgLevel] = condition.conditions!
expect(workspaceScope).toMatchObject({
type: 'inArray',
column: 'workspaceId',
values: WORKSPACE_IDS,
})
expectOrgLevelCondition(orgLevel, ORG_ID)
expect(JSON.stringify(condition)).not.toContain('actorId')
})
it('falls back to the org-level branch alone when the org has no workspaces', () => {
const condition = asCondition(
buildOrgScopeCondition({
organizationId: ORG_ID,
orgWorkspaceIds: [],
orgMemberIds: MEMBER_IDS,
includeDeparted: true,
})
)
expectOrgLevelCondition(condition, ORG_ID)
})
it('still applies the actor filter on top of the org scope with no workspaces', () => {
const condition = asCondition(
buildOrgScopeCondition({
organizationId: ORG_ID,
orgWorkspaceIds: [],
orgMemberIds: MEMBER_IDS,
includeDeparted: false,
})
)
expect(condition.type).toBe('and')
const [orgLevel, actorFilter] = condition.conditions!
expectOrgLevelCondition(orgLevel, ORG_ID)
expect(actorFilter).toMatchObject({
type: 'or',
conditions: [
expect.objectContaining({ type: 'inArray', column: 'actorId', values: MEMBER_IDS }),
expect.objectContaining({ type: 'isNull', column: 'actorId' }),
],
})
})
it('only matches system events when the org has no current members', () => {
const condition = asCondition(
buildOrgScopeCondition({
organizationId: ORG_ID,
orgWorkspaceIds: WORKSPACE_IDS,
orgMemberIds: [],
includeDeparted: false,
})
)
expect(condition.type).toBe('and')
const [, actorFilter] = condition.conditions!
expect(actorFilter).toMatchObject({ type: 'isNull', column: 'actorId' })
})
})
describe('getOrgWorkspaceIds', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('selects workspaces by organization ownership, not member ownership', async () => {
const ids = await getOrgWorkspaceIds(ORG_ID)
expect(ids).toEqual([])
expect(dbChainMockFns.where).toHaveBeenCalledWith(
expect.objectContaining({ type: 'eq', left: 'organizationId', right: ORG_ID })
)
})
})
+179
View File
@@ -0,0 +1,179 @@
import { AuditResourceType } from '@sim/audit'
import { db, dbReplica } from '@sim/db'
import { auditLog, workspace } from '@sim/db/schema'
import type { InferSelectModel } from 'drizzle-orm'
import { and, desc, eq, gte, ilike, inArray, isNull, lt, lte, or, type SQL, sql } from 'drizzle-orm'
type DbAuditLog = InferSelectModel<typeof auditLog>
interface CursorData {
createdAt: string
id: string
}
function encodeCursor(data: CursorData): string {
return Buffer.from(JSON.stringify(data)).toString('base64')
}
function decodeCursor(cursor: string): CursorData | null {
try {
return JSON.parse(Buffer.from(cursor, 'base64').toString())
} catch {
return null
}
}
export interface AuditLogFilterParams {
action?: string
resourceType?: string
resourceId?: string
workspaceId?: string
actorId?: string
actorEmail?: string
search?: string
startDate?: string
endDate?: string
}
export function buildFilterConditions(params: AuditLogFilterParams): SQL<unknown>[] {
const conditions: SQL<unknown>[] = []
if (params.action) conditions.push(eq(auditLog.action, params.action))
if (params.resourceType) {
const types = params.resourceType.split(',').filter(Boolean)
if (types.length === 1) conditions.push(eq(auditLog.resourceType, types[0]))
else if (types.length > 1) conditions.push(inArray(auditLog.resourceType, types))
}
if (params.resourceId) conditions.push(eq(auditLog.resourceId, params.resourceId))
if (params.workspaceId) conditions.push(eq(auditLog.workspaceId, params.workspaceId))
if (params.actorId) conditions.push(eq(auditLog.actorId, params.actorId))
if (params.actorEmail) conditions.push(eq(auditLog.actorEmail, params.actorEmail))
if (params.search) {
const escaped = params.search.replace(/[%_\\]/g, '\\$&')
const searchTerm = `%${escaped}%`
conditions.push(
or(
ilike(auditLog.action, searchTerm),
ilike(auditLog.actorEmail, searchTerm),
ilike(auditLog.actorName, searchTerm),
ilike(auditLog.resourceName, searchTerm),
ilike(auditLog.description, searchTerm)
)!
)
}
if (params.startDate) conditions.push(gte(auditLog.createdAt, new Date(params.startDate)))
if (params.endDate) conditions.push(lte(auditLog.createdAt, new Date(params.endDate)))
return conditions
}
/**
* Returns the IDs of all workspaces attached to the organization.
*/
export async function getOrgWorkspaceIds(organizationId: string): Promise<string[]> {
const rows = await db
.select({ id: workspace.id })
.from(workspace)
.where(eq(workspace.organizationId, organizationId))
return rows.map((row) => row.id)
}
export interface OrgScopeParams {
organizationId: string
orgWorkspaceIds: string[]
orgMemberIds: string[]
includeDeparted: boolean
}
/**
* Builds the tenant-boundary predicate for organization audit log access:
* rows in org-attached workspaces, plus org-level rows (`workspace_id IS
* NULL`) tied to the org via `metadata.organizationId` or the organization
* resource itself. Actor membership is never a standalone boundary — when
* `includeDeparted` is false it only narrows the org scope to current members
* and system events (null actor).
*/
export function buildOrgScopeCondition(params: OrgScopeParams): SQL<unknown> {
const { organizationId, orgWorkspaceIds, orgMemberIds, includeDeparted } = params
const orgLevelCondition = and(
isNull(auditLog.workspaceId),
or(
sql`${auditLog.metadata}->>'organizationId' = ${organizationId}`,
and(
eq(auditLog.resourceType, AuditResourceType.ORGANIZATION),
eq(auditLog.resourceId, organizationId)
)
)
)!
const orgScope =
orgWorkspaceIds.length > 0
? or(inArray(auditLog.workspaceId, orgWorkspaceIds), orgLevelCondition)!
: orgLevelCondition
if (includeDeparted) {
return orgScope
}
const currentActorCondition =
orgMemberIds.length > 0
? or(inArray(auditLog.actorId, orgMemberIds), isNull(auditLog.actorId))!
: isNull(auditLog.actorId)
return and(orgScope, currentActorCondition)!
}
function buildCursorCondition(cursor: string): SQL<unknown> | null {
const cursorData = decodeCursor(cursor)
if (!cursorData?.createdAt || !cursorData.id) return null
const cursorDate = new Date(cursorData.createdAt)
if (Number.isNaN(cursorDate.getTime())) return null
return or(
lt(auditLog.createdAt, cursorDate),
and(eq(auditLog.createdAt, cursorDate), lt(auditLog.id, cursorData.id))
)!
}
interface CursorPaginatedResult {
data: DbAuditLog[]
nextCursor?: string
}
export async function queryAuditLogs(
conditions: SQL<unknown>[],
limit: number,
cursor?: string
): Promise<CursorPaginatedResult> {
const allConditions = [...conditions]
if (cursor) {
const cursorCondition = buildCursorCondition(cursor)
if (cursorCondition) allConditions.push(cursorCondition)
}
const rows = await dbReplica
.select()
.from(auditLog)
.where(allConditions.length > 0 ? and(...allConditions) : undefined)
.orderBy(desc(auditLog.createdAt), desc(auditLog.id))
.limit(limit + 1)
const hasMore = rows.length > limit
const data = rows.slice(0, limit)
let nextCursor: string | undefined
if (hasMore && data.length > 0) {
const last = data[data.length - 1]
nextCursor = encodeCursor({
createdAt: last.createdAt.toISOString(),
id: last.id,
})
}
return { data, nextCursor }
}
@@ -0,0 +1,130 @@
/**
* @vitest-environment node
*
* Tests for GET /api/v1/audit-logs — verifies filters are validated against
* the caller's organization and the scope is built from the org context.
*/
import { createMockRequest } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockCheckRateLimit,
mockValidateEnterpriseAuditAccess,
mockBuildOrgScopeCondition,
mockGetOrgWorkspaceIds,
mockQueryAuditLogs,
mockBuildFilterConditions,
} = vi.hoisted(() => ({
mockCheckRateLimit: vi.fn(),
mockValidateEnterpriseAuditAccess: vi.fn(),
mockBuildOrgScopeCondition: vi.fn(),
mockGetOrgWorkspaceIds: vi.fn(),
mockQueryAuditLogs: vi.fn(),
mockBuildFilterConditions: vi.fn(),
}))
vi.mock('@/app/api/v1/middleware', () => ({
checkRateLimit: mockCheckRateLimit,
createRateLimitResponse: vi.fn(),
}))
vi.mock('@/app/api/v1/audit-logs/auth', () => ({
validateEnterpriseAuditAccess: mockValidateEnterpriseAuditAccess,
}))
vi.mock('@/app/api/v1/audit-logs/query', () => ({
buildFilterConditions: mockBuildFilterConditions,
buildOrgScopeCondition: mockBuildOrgScopeCondition,
getOrgWorkspaceIds: mockGetOrgWorkspaceIds,
queryAuditLogs: mockQueryAuditLogs,
}))
vi.mock('@/app/api/v1/logs/meta', () => ({
getUserLimits: vi.fn().mockResolvedValue({}),
createApiResponse: vi.fn((body: unknown) => ({ body, headers: {} })),
}))
import { GET } from '@/app/api/v1/audit-logs/route'
const ORG_ID = 'org-1'
const MEMBER_IDS = ['admin-1', 'member-1']
const ORG_WORKSPACE_IDS = ['ws-org-1', 'ws-org-2']
const SCOPE_SENTINEL = { type: 'org-scope-sentinel' }
function makeRequest(query: string) {
return createMockRequest('GET', undefined, {}, `http://localhost:3000/api/v1/audit-logs${query}`)
}
describe('GET /api/v1/audit-logs', () => {
beforeEach(() => {
vi.clearAllMocks()
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'admin-1' })
mockValidateEnterpriseAuditAccess.mockResolvedValue({
success: true,
context: { organizationId: ORG_ID, orgMemberIds: MEMBER_IDS },
})
mockGetOrgWorkspaceIds.mockResolvedValue(ORG_WORKSPACE_IDS)
mockBuildOrgScopeCondition.mockReturnValue(SCOPE_SENTINEL)
mockBuildFilterConditions.mockReturnValue([])
mockQueryAuditLogs.mockResolvedValue({ data: [], nextCursor: undefined })
})
it('rejects an actorId that is not a current org member', async () => {
const response = await GET(makeRequest('?actorId=outsider-1'))
expect(response.status).toBe(400)
const body = await response.json()
expect(body.error).toBe('actorId is not a member of your organization')
expect(mockQueryAuditLogs).not.toHaveBeenCalled()
})
it('rejects a workspaceId that does not belong to the organization', async () => {
const response = await GET(makeRequest('?workspaceId=ws-other-org'))
expect(response.status).toBe(400)
const body = await response.json()
expect(body.error).toBe('workspaceId does not belong to your organization')
expect(mockQueryAuditLogs).not.toHaveBeenCalled()
})
it('accepts a workspaceId that belongs to the organization', async () => {
const response = await GET(makeRequest('?workspaceId=ws-org-1'))
expect(response.status).toBe(200)
expect(mockQueryAuditLogs).toHaveBeenCalled()
})
it('builds the scope from the organization context, never from actors alone', async () => {
const response = await GET(makeRequest('?actorId=member-1'))
expect(response.status).toBe(200)
expect(mockBuildOrgScopeCondition).toHaveBeenCalledWith({
organizationId: ORG_ID,
orgWorkspaceIds: ORG_WORKSPACE_IDS,
orgMemberIds: MEMBER_IDS,
includeDeparted: false,
})
const [conditions] = mockQueryAuditLogs.mock.calls[0]
expect(conditions[0]).toBe(SCOPE_SENTINEL)
})
it('passes includeDeparted through to the scope builder', async () => {
const response = await GET(makeRequest('?includeDeparted=true'))
expect(response.status).toBe(200)
expect(mockBuildOrgScopeCondition).toHaveBeenCalledWith(
expect.objectContaining({ includeDeparted: true })
)
})
it('returns the auth failure response when enterprise access is denied', async () => {
const denied = new Response(JSON.stringify({ error: 'nope' }), { status: 403 })
mockValidateEnterpriseAuditAccess.mockResolvedValue({ success: false, response: denied })
const response = await GET(makeRequest(''))
expect(response.status).toBe(403)
expect(mockQueryAuditLogs).not.toHaveBeenCalled()
})
})
+131
View File
@@ -0,0 +1,131 @@
/**
* GET /api/v1/audit-logs
*
* List audit logs scoped to the authenticated user's organization.
* Requires enterprise subscription and org admin/owner role.
*
* Query Parameters:
* - action: string (optional) - Filter by action (e.g., "workflow.created")
* - resourceType: string (optional) - Filter by resource type(s), comma-separated (e.g., "workflow,api_key")
* - resourceId: string (optional) - Filter by resource ID
* - workspaceId: string (optional) - Filter by workspace ID
* - actorId: string (optional) - Filter by actor user ID (must be an org member)
* - startDate: string (optional) - ISO 8601 date, filter createdAt >= startDate
* - endDate: string (optional) - ISO 8601 date, filter createdAt <= endDate
* - includeDeparted: boolean (optional, default: false) - Include logs from departed members
* - limit: number (optional, default: 50, max: 100)
* - cursor: string (optional) - Opaque cursor for pagination
*
* Response: { data: AuditLogEntry[], nextCursor?: string, limits: UserLimits }
*/
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { v1ListAuditLogsContract } from '@/lib/api/contracts/v1/audit-logs'
import { getValidationErrorMessage, parseRequest } from '@/lib/api/server'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { validateEnterpriseAuditAccess } from '@/app/api/v1/audit-logs/auth'
import { formatAuditLogEntry } from '@/app/api/v1/audit-logs/format'
import {
buildFilterConditions,
buildOrgScopeCondition,
getOrgWorkspaceIds,
queryAuditLogs,
} from '@/app/api/v1/audit-logs/query'
import { createApiResponse, getUserLimits } from '@/app/api/v1/logs/meta'
import { checkRateLimit, createRateLimitResponse } from '@/app/api/v1/middleware'
const logger = createLogger('V1AuditLogsAPI')
export const dynamic = 'force-dynamic'
export const revalidate = 0
export const GET = withRouteHandler(async (request: NextRequest) => {
const requestId = generateId().slice(0, 8)
try {
const rateLimit = await checkRateLimit(request, 'audit-logs')
if (!rateLimit.allowed) {
return createRateLimitResponse(rateLimit)
}
const userId = rateLimit.userId!
const authResult = await validateEnterpriseAuditAccess(userId)
if (!authResult.success) {
return authResult.response
}
const { organizationId, orgMemberIds } = authResult.context
const parsed = await parseRequest(
v1ListAuditLogsContract,
request,
{},
{
validationErrorResponse: (error) =>
NextResponse.json(
{
error: getValidationErrorMessage(error, 'Invalid parameters'),
details: error.issues,
},
{ status: 400 }
),
}
)
if (!parsed.success) return parsed.response
const params = parsed.data.query
if (params.actorId && !orgMemberIds.includes(params.actorId)) {
return NextResponse.json(
{ error: 'actorId is not a member of your organization' },
{ status: 400 }
)
}
const orgWorkspaceIds = await getOrgWorkspaceIds(organizationId)
if (params.workspaceId && !orgWorkspaceIds.includes(params.workspaceId)) {
return NextResponse.json(
{ error: 'workspaceId does not belong to your organization' },
{ status: 400 }
)
}
const scopeCondition = buildOrgScopeCondition({
organizationId,
orgWorkspaceIds,
orgMemberIds,
includeDeparted: params.includeDeparted,
})
const filterConditions = buildFilterConditions({
action: params.action,
resourceType: params.resourceType,
resourceId: params.resourceId,
workspaceId: params.workspaceId,
actorId: params.actorId,
startDate: params.startDate,
endDate: params.endDate,
})
const { data, nextCursor } = await queryAuditLogs(
[scopeCondition, ...filterConditions],
params.limit,
params.cursor
)
const formattedLogs = data.map(formatAuditLogEntry)
const limits = await getUserLimits(userId)
const response = createApiResponse({ data: formattedLogs, nextCursor }, limits, rateLimit)
return NextResponse.json(response.body, { headers: response.headers })
} catch (error: unknown) {
const message = getErrorMessage(error, 'Unknown error')
logger.error(`[${requestId}] Audit logs fetch error`, { error: message })
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
})