Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/sim/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,7 @@ API_ENCRYPTION_KEY=your_api_encryption_key # Use `openssl rand -hex 32` to gener
# OLLAMA_URL=http://localhost:11434 # URL for local Ollama server - uncomment if using local models
# VLLM_BASE_URL=http://localhost:8000 # Base URL for your self-hosted vLLM (OpenAI-compatible)
# VLLM_API_KEY= # Optional bearer token if your vLLM instance requires auth

# Admin API (Optional - for self-hosted GitOps)
# ADMIN_API_KEY= # Use `openssl rand -hex 32` to generate. Enables admin API for workflow export/import.
# Usage: curl -H "x-admin-key: your_key" https://your-instance/api/v1/admin/workspaces
79 changes: 79 additions & 0 deletions apps/sim/app/api/v1/admin/auth.ts
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) })
Copy link
Contributor

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

Suggested change
logger.warn('Invalid admin API key attempted', { keyPrefix: providedKey.slice(0, 8) })
logger.warn('Invalid admin API key attempted')

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
This is a comment left during a code review.
Path: apps/sim/app/api/v1/admin/auth.ts
Line: 58:58

Comment:
**style:** Potential information disclosure - logging partial key could aid brute force attacks

```suggestion
    logger.warn('Invalid admin API key attempted')
```

<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.

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)
}
79 changes: 79 additions & 0 deletions apps/sim/app/api/v1/admin/index.ts
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'
50 changes: 50 additions & 0 deletions apps/sim/app/api/v1/admin/middleware.ts
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)
}
}
82 changes: 82 additions & 0 deletions apps/sim/app/api/v1/admin/responses.ts
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: avoid using separator comments like this

Context Used: Context from dashboard - .cursorrules (source)

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
This 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
)
}
Loading