-
Notifications
You must be signed in to change notification settings - Fork 3.2k
feat(admin): added admin APIs for admin management #2206
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
Merged
Changes from all commits
Commits
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
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,79 @@ | ||
| /** | ||
| * Admin API Authentication | ||
| * | ||
| * Authenticates admin API requests using the ADMIN_API_KEY environment variable. | ||
| * Designed for self-hosted deployments where GitOps/scripted access is needed. | ||
| * | ||
| * Usage: | ||
| * curl -H "x-admin-key: your_admin_key" https://your-instance/api/v1/admin/... | ||
| */ | ||
|
|
||
| import { createHash, timingSafeEqual } from 'crypto' | ||
| import type { NextRequest } from 'next/server' | ||
| import { env } from '@/lib/core/config/env' | ||
| import { createLogger } from '@/lib/logs/console/logger' | ||
|
|
||
| const logger = createLogger('AdminAuth') | ||
|
|
||
| export interface AdminAuthSuccess { | ||
| authenticated: true | ||
| } | ||
|
|
||
| export interface AdminAuthFailure { | ||
| authenticated: false | ||
| error: string | ||
| notConfigured?: boolean | ||
| } | ||
|
|
||
| export type AdminAuthResult = AdminAuthSuccess | AdminAuthFailure | ||
|
|
||
| /** | ||
| * Authenticate an admin API request. | ||
| * | ||
| * @param request - The incoming Next.js request | ||
| * @returns Authentication result with success status and optional error | ||
| */ | ||
| export function authenticateAdminRequest(request: NextRequest): AdminAuthResult { | ||
| const adminKey = env.ADMIN_API_KEY | ||
|
|
||
| if (!adminKey) { | ||
| logger.warn('ADMIN_API_KEY environment variable is not set') | ||
| return { | ||
| authenticated: false, | ||
| error: 'Admin API is not configured. Set ADMIN_API_KEY environment variable.', | ||
| notConfigured: true, | ||
| } | ||
| } | ||
|
|
||
| const providedKey = request.headers.get('x-admin-key') | ||
|
|
||
| if (!providedKey) { | ||
| return { | ||
| authenticated: false, | ||
| error: 'Admin API key required. Provide x-admin-key header.', | ||
| } | ||
| } | ||
|
|
||
| if (!constantTimeCompare(providedKey, adminKey)) { | ||
| logger.warn('Invalid admin API key attempted', { keyPrefix: providedKey.slice(0, 8) }) | ||
| return { | ||
| authenticated: false, | ||
| error: 'Invalid admin API key', | ||
| } | ||
| } | ||
|
|
||
| return { authenticated: true } | ||
| } | ||
|
|
||
| /** | ||
| * Constant-time string comparison. | ||
| * | ||
| * @param a - First string to compare | ||
| * @param b - Second string to compare | ||
| * @returns True if strings are equal, false otherwise | ||
| */ | ||
| function constantTimeCompare(a: string, b: string): boolean { | ||
| const aHash = createHash('sha256').update(a).digest() | ||
| const bHash = createHash('sha256').update(b).digest() | ||
| return timingSafeEqual(aHash, bHash) | ||
| } | ||
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,79 @@ | ||
| /** | ||
| * Admin API v1 | ||
| * | ||
| * A RESTful API for administrative operations on Sim. | ||
| * | ||
| * Authentication: | ||
| * Set ADMIN_API_KEY environment variable and use x-admin-key header. | ||
| * | ||
| * Endpoints: | ||
| * GET /api/v1/admin/users - List all users | ||
| * GET /api/v1/admin/users/:id - Get user details | ||
| * GET /api/v1/admin/workspaces - List all workspaces | ||
| * GET /api/v1/admin/workspaces/:id - Get workspace details | ||
| * GET /api/v1/admin/workspaces/:id/workflows - List workspace workflows | ||
| * DELETE /api/v1/admin/workspaces/:id/workflows - Delete all workspace workflows | ||
| * GET /api/v1/admin/workspaces/:id/folders - List workspace folders | ||
| * GET /api/v1/admin/workspaces/:id/export - Export workspace (ZIP/JSON) | ||
| * POST /api/v1/admin/workspaces/:id/import - Import into workspace | ||
| * GET /api/v1/admin/workflows - List all workflows | ||
| * GET /api/v1/admin/workflows/:id - Get workflow details | ||
| * DELETE /api/v1/admin/workflows/:id - Delete workflow | ||
| * GET /api/v1/admin/workflows/:id/export - Export workflow (JSON) | ||
| * POST /api/v1/admin/workflows/import - Import single workflow | ||
| */ | ||
|
|
||
| export type { AdminAuthFailure, AdminAuthResult, AdminAuthSuccess } from '@/app/api/v1/admin/auth' | ||
| export { authenticateAdminRequest } from '@/app/api/v1/admin/auth' | ||
| export type { AdminRouteHandler, AdminRouteHandlerWithParams } from '@/app/api/v1/admin/middleware' | ||
| export { withAdminAuth, withAdminAuthParams } from '@/app/api/v1/admin/middleware' | ||
| export { | ||
| badRequestResponse, | ||
| errorResponse, | ||
| forbiddenResponse, | ||
| internalErrorResponse, | ||
| listResponse, | ||
| notConfiguredResponse, | ||
| notFoundResponse, | ||
| singleResponse, | ||
| unauthorizedResponse, | ||
| } from '@/app/api/v1/admin/responses' | ||
| export type { | ||
| AdminErrorResponse, | ||
| AdminFolder, | ||
| AdminListResponse, | ||
| AdminSingleResponse, | ||
| AdminUser, | ||
| AdminWorkflow, | ||
| AdminWorkflowDetail, | ||
| AdminWorkspace, | ||
| AdminWorkspaceDetail, | ||
| DbUser, | ||
| DbWorkflow, | ||
| DbWorkflowFolder, | ||
| DbWorkspace, | ||
| FolderExportPayload, | ||
| ImportResult, | ||
| PaginationMeta, | ||
| PaginationParams, | ||
| VariableType, | ||
| WorkflowExportPayload, | ||
| WorkflowExportState, | ||
| WorkflowImportRequest, | ||
| WorkflowVariable, | ||
| WorkspaceExportPayload, | ||
| WorkspaceImportRequest, | ||
| WorkspaceImportResponse, | ||
| } from '@/app/api/v1/admin/types' | ||
| export { | ||
| createPaginationMeta, | ||
| DEFAULT_LIMIT, | ||
| extractWorkflowMetadata, | ||
| MAX_LIMIT, | ||
| parsePaginationParams, | ||
| parseWorkflowVariables, | ||
| toAdminFolder, | ||
| toAdminUser, | ||
| toAdminWorkflow, | ||
| toAdminWorkspace, | ||
| } from '@/app/api/v1/admin/types' |
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,50 @@ | ||
| import type { NextRequest, NextResponse } from 'next/server' | ||
| import { authenticateAdminRequest } from '@/app/api/v1/admin/auth' | ||
| import { notConfiguredResponse, unauthorizedResponse } from '@/app/api/v1/admin/responses' | ||
|
|
||
| export type AdminRouteHandler = (request: NextRequest) => Promise<NextResponse> | ||
|
|
||
| export type AdminRouteHandlerWithParams<TParams> = ( | ||
| request: NextRequest, | ||
| context: { params: Promise<TParams> } | ||
| ) => Promise<NextResponse> | ||
|
|
||
| /** | ||
| * Wrap a route handler with admin authentication. | ||
| * Returns early with an error response if authentication fails. | ||
| */ | ||
| export function withAdminAuth(handler: AdminRouteHandler): AdminRouteHandler { | ||
| return async (request: NextRequest) => { | ||
| const auth = authenticateAdminRequest(request) | ||
|
|
||
| if (!auth.authenticated) { | ||
| if (auth.notConfigured) { | ||
| return notConfiguredResponse() | ||
| } | ||
| return unauthorizedResponse(auth.error) | ||
| } | ||
|
|
||
| return handler(request) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Wrap a route handler with params with admin authentication. | ||
| * Returns early with an error response if authentication fails. | ||
| */ | ||
| export function withAdminAuthParams<TParams>( | ||
| handler: AdminRouteHandlerWithParams<TParams> | ||
| ): AdminRouteHandlerWithParams<TParams> { | ||
| return async (request: NextRequest, context: { params: Promise<TParams> }) => { | ||
| const auth = authenticateAdminRequest(request) | ||
|
|
||
| if (!auth.authenticated) { | ||
| if (auth.notConfigured) { | ||
| return notConfiguredResponse() | ||
| } | ||
| return unauthorizedResponse(auth.error) | ||
| } | ||
|
|
||
| return handler(request, context) | ||
| } | ||
| } |
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,82 @@ | ||
| /** | ||
| * Admin API Response Helpers | ||
| * | ||
| * Consistent response formatting for all Admin API endpoints. | ||
| */ | ||
|
|
||
| import { NextResponse } from 'next/server' | ||
| import type { | ||
| AdminErrorResponse, | ||
| AdminListResponse, | ||
| AdminSingleResponse, | ||
| PaginationMeta, | ||
| } from '@/app/api/v1/admin/types' | ||
|
|
||
| /** | ||
| * Create a successful list response with pagination | ||
| */ | ||
| export function listResponse<T>( | ||
| data: T[], | ||
| pagination: PaginationMeta | ||
| ): NextResponse<AdminListResponse<T>> { | ||
| return NextResponse.json({ data, pagination }) | ||
| } | ||
|
|
||
| /** | ||
| * Create a successful single resource response | ||
| */ | ||
| export function singleResponse<T>(data: T): NextResponse<AdminSingleResponse<T>> { | ||
| return NextResponse.json({ data }) | ||
| } | ||
|
|
||
| /** | ||
| * Create an error response | ||
| */ | ||
| export function errorResponse( | ||
| code: string, | ||
| message: string, | ||
| status: number, | ||
| details?: unknown | ||
| ): NextResponse<AdminErrorResponse> { | ||
| const body: AdminErrorResponse = { | ||
| error: { code, message }, | ||
| } | ||
|
|
||
| if (details !== undefined) { | ||
| body.error.details = details | ||
| } | ||
|
|
||
| return NextResponse.json(body, { status }) | ||
| } | ||
|
|
||
| // ============================================================================= | ||
| // Common Error Responses | ||
| // ============================================================================= | ||
|
Comment on lines
+52
to
+54
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. style: avoid using separator comments like this Context Used: Context from Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! Prompt To Fix With AIThis is a comment left during a code review.
Path: apps/sim/app/api/v1/admin/responses.ts
Line: 52:54
Comment:
**style:** avoid using separator comments like this
**Context Used:** Context from `dashboard` - .cursorrules ([source](https://app.greptile.com/review/custom-context?memory=493a526c-5c62-4263-a434-6a91d855febe))
<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>
How can I resolve this? If you propose a fix, please make it concise. |
||
|
|
||
| export function unauthorizedResponse(message = 'Authentication required'): NextResponse { | ||
| return errorResponse('UNAUTHORIZED', message, 401) | ||
| } | ||
|
|
||
| export function forbiddenResponse(message = 'Access denied'): NextResponse { | ||
| return errorResponse('FORBIDDEN', message, 403) | ||
| } | ||
|
|
||
| export function notFoundResponse(resource: string): NextResponse { | ||
| return errorResponse('NOT_FOUND', `${resource} not found`, 404) | ||
| } | ||
|
|
||
| export function badRequestResponse(message: string, details?: unknown): NextResponse { | ||
| return errorResponse('BAD_REQUEST', message, 400, details) | ||
| } | ||
|
|
||
| export function internalErrorResponse(message = 'Internal server error'): NextResponse { | ||
| return errorResponse('INTERNAL_ERROR', message, 500) | ||
| } | ||
|
|
||
| export function notConfiguredResponse(): NextResponse { | ||
| return errorResponse( | ||
| 'NOT_CONFIGURED', | ||
| 'Admin API is not configured. Set ADMIN_API_KEY environment variable.', | ||
| 503 | ||
| ) | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
style: Potential information disclosure - logging partial key could aid brute force attacks
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Prompt To Fix With AI