Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3.8k
improvement(api): migrate policy-sensitive v2 reads#6410
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
Merged
TheodoreSpeaks
merged 1 commit into
improvement/v2-endpoints
from
codex/v2-application-adminAug 8, 2026
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
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,83 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
| const mocks = vi.hoisted(() => ({ | ||
| getSession: vi.fn(), | ||
| execute: vi.fn(), | ||
| })) | ||
| vi.mock('@/lib/auth', () => ({ getSession: mocks.getSession })) | ||
| vi.mock('@/lib/audit-logs/application/list-audit-logs', () => ({ | ||
| listAuditLogs: { operation: { id: 'audit_logs.list' }, execute: mocks.execute }, | ||
| })) | ||
| import { OrchestrationError } from '@/lib/core/orchestration/types' | ||
| import { GET } from '@/app/api/audit-logs/route' | ||
| const log = { | ||
| id: 'audit-1', | ||
| workspaceId: 'workspace-1', | ||
| actorId: 'admin-1', | ||
| actorName: 'Ada', | ||
| actorEmail: 'ada@example.com', | ||
| action: 'workspace.updated', | ||
| resourceType: 'workspace', | ||
| resourceId: 'workspace-1', | ||
| resourceName: 'Engineering', | ||
| description: null, | ||
| metadata: {}, | ||
| createdAt: new Date('2026-08-01T00:00:00Z'), | ||
| } | ||
| describe('GET /api/audit-logs', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mocks.getSession.mockResolvedValue({ | ||
| user: { id: 'admin-1' }, | ||
| session: { id: 'session-1' }, | ||
| }) | ||
| mocks.execute.mockResolvedValue({ data: [log], nextCursor: 'next-1' }) | ||
| }) | ||
| it('authenticates before parsing the organization query', async () => { | ||
| const response = await GET(new NextRequest('http://localhost:3000/api/audit-logs')) | ||
| expect(response.status).toBe(400) | ||
| expect(mocks.getSession).toHaveBeenCalled() | ||
| expect(mocks.execute).not.toHaveBeenCalled() | ||
| }) | ||
| it('keeps the internal envelope while sharing the application operation', async () => { | ||
| const request = new NextRequest( | ||
| 'http://localhost:3000/api/audit-logs?organizationId=organization-1' | ||
| ) | ||
| const response = await GET(request) | ||
| expect(response.status).toBe(200) | ||
| expect(await response.json()).toMatchObject({ | ||
| success: true, | ||
| data: [{ id: 'audit-1', actorId: 'admin-1' }], | ||
| nextCursor: 'next-1', | ||
| }) | ||
| expect(mocks.execute).toHaveBeenCalledWith({ | ||
| principal: { kind: 'session', userId: 'admin-1', sessionId: 'session-1' }, | ||
| input: expect.objectContaining({ organizationId: 'organization-1' }), | ||
| request, | ||
| }) | ||
| }) | ||
| it('preserves internal typed error presentation', async () => { | ||
| mocks.execute.mockRejectedValueOnce(new OrchestrationError('forbidden', 'Admin required')) | ||
| const response = await GET( | ||
| new NextRequest('http://localhost:3000/api/audit-logs?organizationId=organization-1') | ||
| ) | ||
| expect(response.status).toBe(403) | ||
| expect(await response.json()).toEqual({ error: 'Admin required' }) | ||
| }) | ||
| }) |
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 |
|---|---|---|
| @@ -1,97 +1,42 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { listAuditLogsContract } from '@/lib/api/contracts/audit-logs' | ||
| import { getValidationErrorMessage, parseRequest } from '@/lib/api/server' | ||
| import { getSession } from '@/lib/auth' | ||
| 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' | ||
| const logger = createLogger('AuditLogsAPI') | ||
| defineInternalJsonRoute, | ||
| internalPlainOrchestrationErrorPolicy, | ||
| internalRateLimits, | ||
| internalSessionAuth, | ||
| } from '@/lib/api/server/routes' | ||
| import { listAuditLogs } from '@/lib/audit-logs/application/list-audit-logs' | ||
| import { auditLogOperations } from '@/lib/audit-logs/application/operations' | ||
| import { formatAuditLogEntry } from '@/app/api/v1/audit-logs/format' | ||
| export const dynamic = 'force-dynamic' | ||
| export const GET = withRouteHandler(async (request: NextRequest) => { | ||
| try { | ||
| const session = await getSession() | ||
| if (!session?.user?.id) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
| } | ||
| const parsed = await parseRequest( | ||
| listAuditLogsContract, | ||
| request, | ||
| {}, | ||
| { | ||
| validationErrorResponse: (error) => | ||
| NextResponse.json( | ||
| { error: getValidationErrorMessage(error, 'Invalid query parameters') }, | ||
| { status: 400 } | ||
| ), | ||
| } | ||
| ) | ||
| if (!parsed.success) return parsed.response | ||
| const authResult = await validateEnterpriseAuditAccess( | ||
| session.user.id, | ||
| parsed.data.query.organizationId | ||
| ) | ||
| if (!authResult.success) { | ||
| return authResult.response | ||
| } | ||
| const { organizationId, orgMemberIds } = authResult.context | ||
| const { | ||
| organizationId: _targetOrganizationId, | ||
| search, | ||
| action, | ||
| resourceType, | ||
| actorId, | ||
| startDate, | ||
| endDate, | ||
| includeDeparted, | ||
| limit, | ||
| cursor, | ||
| } = parsed.data.query | ||
| const orgWorkspaceIds = await getOrgWorkspaceIds(organizationId) | ||
| const scopeCondition = buildOrgScopeCondition({ | ||
| organizationId, | ||
| orgWorkspaceIds, | ||
| orgMemberIds, | ||
| includeDeparted, | ||
| }) | ||
| const filterConditions = buildFilterConditions({ | ||
| action, | ||
| resourceType, | ||
| actorId, | ||
| search, | ||
| startDate, | ||
| endDate, | ||
| }) | ||
| const { data, nextCursor } = await queryAuditLogs( | ||
| [scopeCondition, ...filterConditions], | ||
| limit, | ||
| cursor | ||
| ) | ||
| return NextResponse.json({ | ||
| success: true, | ||
| data: data.map(formatAuditLogEntry), | ||
| nextCursor, | ||
| }) | ||
| } catch (error: unknown) { | ||
| const message = getErrorMessage(error, 'Unknown error') | ||
| logger.error('Audit logs fetch error', { error: message }) | ||
| return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) | ||
| } | ||
| export const GET = defineInternalJsonRoute({ | ||
| contract: listAuditLogsContract, | ||
| auth: internalSessionAuth, | ||
| operation: auditLogOperations.list, | ||
| rateLimit: internalRateLimits.none({ | ||
| reason: 'Existing authenticated audit-log settings read has no request-rate policy', | ||
| }), | ||
| errorPolicy: internalPlainOrchestrationErrorPolicy, | ||
| mapInput: ({ query }) => ({ | ||
| organizationId: query.organizationId, | ||
| includeDeparted: query.includeDeparted, | ||
| filters: { | ||
| search: query.search, | ||
| action: query.action, | ||
| resourceType: query.resourceType, | ||
| actorId: query.actorId, | ||
| startDate: query.startDate, | ||
| endDate: query.endDate, | ||
| }, | ||
| limit: query.limit, | ||
| cursor: query.cursor, | ||
| }), | ||
| useCase: listAuditLogs, | ||
| present: ({ data, nextCursor }) => ({ | ||
| success: true, | ||
| data: data.map(formatAuditLogEntry), | ||
| nextCursor, | ||
| }), | ||
| }) | ||
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.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.