Skip to content

Conversation

@waleedlatif1
Copy link
Collaborator

Summary

  • added admin APIs for admin management

Type of Change

  • New feature

Testing

Tested manually

Checklist

  • Code follows project style guidelines
  • Self-reviewed my changes
  • Tests added/updated and passing
  • No new warnings introduced
  • I confirm that I have read and agree to the terms outlined in the Contributor License Agreement (CLA)

@vercel
Copy link

vercel bot commented Dec 5, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Preview Comments Updated (UTC)
docs Skipped Skipped Dec 5, 2025 4:42am

@waleedlatif1 waleedlatif1 merged commit ca818a6 into staging Dec 5, 2025
9 checks passed
@waleedlatif1 waleedlatif1 deleted the feat/admin branch December 5, 2025 04:52
@greptile-apps
Copy link
Contributor

greptile-apps bot commented Dec 5, 2025

Greptile Overview

Greptile Summary

This PR introduces a comprehensive Admin API v1 system for administrative management of the Sim platform. The implementation adds 16 new API endpoints across users, workspaces, and workflows, including listing, detailed views, deletion, and import/export operations. The system uses environment-variable based authentication (ADMIN_API_KEY) with security measures like timing-safe comparisons and proper middleware patterns.

The admin API follows RESTful conventions with consistent response structures, pagination support, and proper error handling. Key functionality includes workspace export/import (ZIP and JSON formats), bulk workflow operations, user management, and folder management. The implementation leverages existing database patterns using Drizzle ORM, maintains referential integrity through transactions, and includes comprehensive TypeScript types with utility functions for data transformation.

All endpoints use the withAdminAuth middleware for authentication, standardized response helpers for consistency, and structured logging for operational visibility. The system is designed for self-hosted GitOps scenarios where programmatic admin access is required.

Important Files Changed

Filename Score Overview
apps/sim/app/api/v1/admin/auth.ts 4/5 Implements secure admin API key authentication with timing-safe comparison
apps/sim/app/api/v1/admin/middleware.ts 5/5 Provides reusable authentication middleware for admin route handlers
apps/sim/app/api/v1/admin/responses.ts 4/5 Creates standardized response utilities for consistent Admin API formatting
apps/sim/app/api/v1/admin/types.ts 5/5 Comprehensive type system with utility functions for admin operations
apps/sim/app/api/v1/admin/index.ts 4/5 Centralized documentation and barrel export for admin API module
apps/sim/app/api/v1/admin/users/route.ts 4/5 Admin endpoint for listing users with pagination support
apps/sim/app/api/v1/admin/users/[id]/route.ts 5/5 Admin endpoint for retrieving individual user details
apps/sim/app/api/v1/admin/workspaces/route.ts 5/5 Admin endpoint for listing all workspaces with pagination
apps/sim/app/api/v1/admin/workspaces/[id]/route.ts 4/5 Admin endpoint for workspace details with count aggregations
apps/sim/app/api/v1/admin/workspaces/[id]/workflows/route.ts 4/5 Workspace workflow listing and bulk deletion with proper transactions
apps/sim/app/api/v1/admin/workspaces/[id]/folders/route.ts 5/5 Workspace folder listing with pagination and proper validation
apps/sim/app/api/v1/admin/workspaces/[id]/export/route.ts 4/5 Workspace export functionality supporting both ZIP and JSON formats
apps/sim/app/api/v1/admin/workspaces/[id]/import/route.ts 3/5 Workspace import from ZIP/JSON with complex processing logic
apps/sim/app/api/v1/admin/workflows/route.ts 4/5 System-wide workflow listing with proper pagination
apps/sim/app/api/v1/admin/workflows/[id]/route.ts 4/5 Individual workflow management with transactional deletion
apps/sim/app/api/v1/admin/workflows/[id]/export/route.ts 5/5 Workflow export with structured JSON output
apps/sim/app/api/v1/admin/workflows/import/route.ts 3/5 Workflow import endpoint with potential consistency issues
apps/sim/lib/core/config/env.ts 5/5 Environment configuration for admin API key with proper validation
apps/sim/.env.example 5/5 Documentation and example for admin API configuration

Confidence score: 3/5

  • This PR introduces complex admin functionality with some implementation concerns around data consistency and error handling
  • Score reflects potential issues in import operations where workflow parsing happens twice and partial failures could leave inconsistent state
  • Pay close attention to workflow/workspace import endpoints which have complex logic and potential rollback scenarios

Sequence Diagram

sequenceDiagram
    participant User as "Admin User"
    participant Client as "HTTP Client"
    participant Middleware as "Admin Auth Middleware"
    participant AuthModule as "Admin Auth Module"
    participant Handler as "API Route Handler"
    participant DB as "Database"
    participant Logger as "Logger"

    User->>Client: "Send admin API request"
    Client->>Middleware: "HTTP Request with x-admin-key header"
    
    Middleware->>AuthModule: "authenticateAdminRequest(request)"
    AuthModule->>AuthModule: "Check ADMIN_API_KEY environment variable"
    
    alt ADMIN_API_KEY not configured
        AuthModule->>Middleware: "{ authenticated: false, notConfigured: true }"
        Middleware->>Client: "503 Not Configured Response"
        Client->>User: "Admin API not configured error"
    else Missing x-admin-key header
        AuthModule->>Middleware: "{ authenticated: false, error: 'Key required' }"
        Middleware->>Client: "401 Unauthorized Response"
        Client->>User: "Authentication required error"
    else Invalid admin key
        AuthModule->>AuthModule: "constantTimeCompare(providedKey, adminKey)"
        AuthModule->>Logger: "Log invalid key attempt"
        AuthModule->>Middleware: "{ authenticated: false, error: 'Invalid key' }"
        Middleware->>Client: "401 Unauthorized Response"
        Client->>User: "Invalid admin key error"
    else Valid authentication
        AuthModule->>Middleware: "{ authenticated: true }"
        Middleware->>Handler: "Call route handler"
        
        Handler->>DB: "Database query/operation"
        DB->>Handler: "Query results"
        
        Handler->>Logger: "Log operation"
        Handler->>Middleware: "Response data"
        Middleware->>Client: "200 Success Response"
        Client->>User: "API response data"
    end
Loading

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

19 files reviewed, 8 comments

Edit Code Review Agent Settings | Greptile

Comment on lines +51 to +52
workflowCount: workflowCountResult[0].count,
folderCount: folderCountResult[0].count,
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: accessing array index [0] without checking if results exist could cause runtime error if count query returns empty array

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/sim/app/api/v1/admin/workspaces/[id]/route.ts
Line: 51:52

Comment:
**logic:** accessing array index [0] without checking if results exist could cause runtime error if count query returns empty array

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +52 to +54
// =============================================================================
// Common Error Responses
// =============================================================================
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.

Comment on lines +13 to +15
// =============================================================================
// Database Model Types (inferred from schema)
// =============================================================================
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Consider removing the section separator comments to align with the .cursorrules that state not to use ==== for comments and to avoid non-TSDoc comments

Suggested change
// =============================================================================
// Database Model Types (inferred from schema)
// =============================================================================
/**
* Database Model Types (inferred from schema)
*/

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/types.ts
Line: 13:15

Comment:
**style:** Consider removing the section separator comments to align with the .cursorrules that state not to use ==== for comments and to avoid non-TSDoc comments

```suggestion
/**
 * Database Model Types (inferred from schema)
 */
```

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

Comment on lines +319 to +324
return varsObj.map((v) => ({
id: v.id,
name: v.name,
type: v.type,
value: v.value,
}))
Copy link
Contributor

Choose a reason for hiding this comment

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

logic: Type assertion without validation creates potential runtime errors if the object structure doesn't match expected format. Should there be validation to ensure the mapped object has the required properties before type assertion?

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/sim/app/api/v1/admin/types.ts
Line: 319:324

Comment:
**logic:** Type assertion without validation creates potential runtime errors if the object structure doesn't match expected format. Should there be validation to ensure the mapped object has the required properties before type assertion?

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +68 to +86
const workflowContent =
typeof body.workflow === 'string' ? body.workflow : JSON.stringify(body.workflow)

const { data: workflowData, errors } = parseWorkflowJson(workflowContent)

if (!workflowData || errors.length > 0) {
return badRequestResponse(`Invalid workflow: ${errors.join(', ')}`)
}

const parsedWorkflow =
typeof body.workflow === 'string'
? (() => {
try {
return JSON.parse(body.workflow)
} catch {
return null
}
})()
: body.workflow
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Workflow is being parsed twice - once as string for validation and once for metadata extraction. Consider parsing once and reusing the result to avoid redundant operations.

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/workflows/import/route.ts
Line: 68:86

Comment:
**style:** Workflow is being parsed twice - once as string for validation and once for metadata extraction. Consider parsing once and reusing the result to avoid redundant operations.

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

id: workflowId,
userId: workspaceData.ownerId,
workspaceId,
folderId: folderId || null,
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Consider validating that folderId exists in the target workspace before creating the workflow to prevent orphaned folder references. Should there be validation to ensure the folderId exists within the target workspace?

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/workflows/import/route.ts
Line: 101:101

Comment:
**style:** Consider validating that folderId exists in the target workspace before creating the workflow to prevent orphaned folder references. Should there be validation to ensure the folderId exists within the target workspace?

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

Comment on lines +231 to +237
const parsedContent = (() => {
try {
return JSON.parse(wf.content)
} catch {
return null
}
})()
Copy link
Contributor

Choose a reason for hiding this comment

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

style: JSON parsing duplicates work already done by parseWorkflowJson on line 186

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/workspaces/[id]/import/route.ts
Line: 231:237

Comment:
**style:** JSON parsing duplicates work already done by parseWorkflowJson on line 186

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

}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants