> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.sophra.org/llms.txt
> Use this file to discover all available pages before exploring further.

# API Key Management System

> A robust API key management system for Sophra's authentication and authorization infrastructure

The API Key Management System is a critical component of Sophra's authentication and authorization infrastructure, providing a secure and flexible mechanism for managing API access across the platform. This system is implemented as a set of RESTful endpoints within the Next.js 14 framework, leveraging TypeScript for type safety and Prisma ORM for database interactions. It forms a crucial part of Sophra's microservices architecture, enabling fine-grained control over service-to-service communication and external API access.

The system is designed with scalability and security at its core, implementing best practices such as cryptographically secure key generation, role-based access control, and comprehensive error handling. It integrates seamlessly with Sophra's broader authentication framework, working in tandem with JWT-based user authentication to provide a dual-layer security model that caters to both user sessions and service-level access control.

One of the key architectural decisions in this component is the use of a middleware-based approach for admin authentication. This design pattern ensures that all API key management operations are restricted to authorized administrators, maintaining a clear separation of concerns and enhancing overall system security. The middleware is implemented as a higher-order function, allowing for easy composition and reuse across different endpoints.

Performance considerations have been carefully addressed in the implementation. The system utilizes Prisma's efficient querying capabilities to minimize database load, and implements caching strategies to reduce latency on frequently accessed data. The API key generation process uses Node.js's crypto module, ensuring a cryptographically secure source of randomness without compromising on performance.

A unique feature of this API key management system is its flexibility in key configuration. It supports advanced features such as IP address restrictions, rate limiting, and key expiration, allowing for granular control over API access. This level of configurability enables Sophra to implement sophisticated access patterns, enhancing both security and operational efficiency across the platform.

## Exported Components

<CodeGroup>
  ```typescript theme={null}
  interface ApiKey {
    id: string;                 // Unique identifier for the API key
    key: string;                // The actual API key (hashed in storage)
    name: string;               // Human-readable name for the key
    clientId: string;           // Associated client identifier
    description?: string;       // Optional description of the key's purpose
    isActive: boolean;          // Whether the key is currently active
    expiresAt?: Date;           // Optional expiration date
    createdAt: Date;            // Timestamp of key creation
    lastUsedAt?: Date;          // Timestamp of last key usage
    allowedIps?: string[];      // List of IP addresses allowed to use this key
    rateLimit?: number;         // Optional rate limit for the key
    usageCount: number;         // Number of times the key has been used
  }

  interface ApiKeyCreateInput {
    name: string;
    clientId: string;
    description?: string;
    rateLimit?: number;
    allowedIps?: string[];
    expiresAt?: Date;
  }

  interface ApiKeyUpdateInput {
    id: string;
    name?: string;
    clientId?: string;
    description?: string;
    isActive?: boolean;
    rateLimit?: number;
    allowedIps?: string[];
    expiresAt?: Date;
    regenerateKey?: boolean;
  }

  // HTTP method handlers
  export async function POST(req: NextRequest): Promise<NextResponse>;
  export async function GET(req: NextRequest): Promise<NextResponse>;
  export async function PUT(req: NextRequest): Promise<NextResponse>;
  export async function PATCH(req: NextRequest): Promise<NextResponse>;
  export async function DELETE(req: NextRequest): Promise<NextResponse>;
  ```
</CodeGroup>

## Implementation Examples

<CodeGroup>
  ```typescript theme={null}
  // Creating a new API key
  const response = await fetch('/api/keys', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      name: 'Search Service Key',
      clientId: 'search-service',
      description: 'API key for the Search Service',
      rateLimit: 1000,
      allowedIps: ['10.0.0.1', '10.0.0.2'],
      expiresAt: '2024-12-31T23:59:59Z'
    })
  });

  const newApiKey = await response.json();
  console.log('New API Key:', newApiKey.key);

  // Listing all API keys
  const apiKeys = await fetch('/api/keys').then(res => res.json());
  console.log('API Keys:', apiKeys);

  // Updating an API key
  await fetch('/api/keys', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      id: 'existing-key-id',
      name: 'Updated Search Service Key',
      rateLimit: 2000,
      regenerateKey: true
    })
  });

  // Deleting an API key
  await fetch('/api/keys?id=key-to-delete', { method: 'DELETE' });
  ```
</CodeGroup>

## Sophra Integration Details

The API Key Management System integrates deeply with Sophra's authentication and authorization services. It works in conjunction with the JWT-based user authentication system to provide a comprehensive security model.

<Accordion title="Authentication Flow">
  ```mermaid theme={null}
  sequenceDiagram
      participant Client
      participant APIGateway
      participant KeyManagement
      participant AuthService
      participant Database

      Client->>APIGateway: Request with API Key
      APIGateway->>AuthService: Validate API Key
      AuthService->>KeyManagement: Check Key Validity
      KeyManagement->>Database: Query Key Details
      Database-->>KeyManagement: Key Information
      KeyManagement-->>AuthService: Key Validity Result
      AuthService-->>APIGateway: Authentication Result
      APIGateway->>Client: Authenticated Response
  ```
</Accordion>

The system also integrates with Sophra's logging and monitoring infrastructure, sending key usage metrics to Prometheus for real-time monitoring and alerting.

## Error Handling

The API Key Management System implements comprehensive error handling to ensure system stability and provide meaningful feedback. Here are some key error scenarios and their handling strategies:

<AccordionGroup>
  <Accordion title="Invalid API Key">
    * Scenario: An API request is made with an invalid or expired key
    * Handling: Return a 401 Unauthorized response
    * Logging: Log the attempt with the IP address for security auditing
  </Accordion>

  <Accordion title="Rate Limit Exceeded">
    * Scenario: An API key exceeds its configured rate limit
    * Handling: Return a 429 Too Many Requests response
    * Action: Temporarily suspend the key and notify the admin
  </Accordion>

  <Accordion title="Database Connection Failure">
    * Scenario: Unable to connect to the database during key operations
    * Handling: Return a 503 Service Unavailable response
    * Recovery: Implement retry logic with exponential backoff
    * Monitoring: Trigger a high-priority alert for immediate attention
  </Accordion>
</AccordionGroup>

## Data Flow

<Accordion title="API Key Creation Flow">
  ```mermaid theme={null}
  sequenceDiagram
      participant Admin
      participant APIGateway
      participant KeyManagement
      participant Database

      Admin->>APIGateway: POST /api/keys
      APIGateway->>KeyManagement: Create Key Request
      KeyManagement->>KeyManagement: Generate Secure Key
      KeyManagement->>Database: Store New Key
      Database-->>KeyManagement: Confirmation
      KeyManagement-->>APIGateway: New Key Details
      APIGateway-->>Admin: API Key Response
  ```
</Accordion>

## Performance Considerations

The API Key Management System is optimized for high-performance operations:

* Caching: Frequently accessed key metadata is cached in Redis, reducing database load
* Indexing: Database indices on `key` and `clientId` fields for fast lookups
* Batch Operations: Bulk key operations are supported for efficient management of multiple keys

<Note>
  In benchmark tests, the system demonstrated the ability to handle 10,000 key validations per second with an average latency of 5ms.
</Note>

## Security Implementation

Security is paramount in the API Key Management System:

* Key Storage: API keys are hashed using bcrypt before storage
* Access Control: All management operations require admin authentication
* Audit Logging: Every key operation is logged for security auditing
* IP Restrictions: Optional IP-based access control for each key

<CodeGroup>
  ```typescript theme={null}
  // Admin authentication middleware
  async function withAdminAuth(
    request: NextRequest,
    handler: (request: NextRequest) => Promise<NextResponse>
  ) {
    const middlewareResponse = await adminMiddleware(request);
    if (middlewareResponse.status !== 200) {
      return middlewareResponse;
    }
    return handler(request);
  }

  // Usage in route handlers
  export async function POST(req: NextRequest) {
    return withAdminAuth(req, async (request) => {
      // Protected key creation logic
    });
  }
  ```
</CodeGroup>

## Configuration

The API Key Management System is highly configurable to adapt to different deployment environments:

<CodeGroup>
  ```env theme={null}
  DATABASE_URL="postgresql://user:password@localhost:5432/sophra"
  REDIS_URL="redis://localhost:6379"
  API_KEY_SALT="your-secret-salt"
  DEFAULT_KEY_EXPIRY_DAYS=365
  MAX_KEYS_PER_CLIENT=10
  ```
</CodeGroup>

These environment variables can be adjusted to fine-tune the system's behavior, such as database connections, key expiration policies, and security settings.
