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

# Admin Permissions Module

> A robust permission management system for Sophra's admin API endpoints

The Admin Permissions Module is a critical component of Sophra's security infrastructure, providing granular access control for administrative API endpoints. This module implements a sophisticated token-based authorization system, allowing for fine-grained control over administrative actions within the Sophra ecosystem. By leveraging a purpose-driven token architecture, it ensures that administrative access is tightly scoped and follows the principle of least privilege.

At its core, the module defines a set of administrative token purposes, each corresponding to specific operational domains within Sophra. These purposes include API management, monitoring, deployment, backup, and maintenance. The module then maps these purposes to specific API endpoints, creating a comprehensive permission matrix that governs access across the entire administrative API surface.

The architectural decision to use purpose-driven tokens offers several advantages. It allows for clear separation of concerns, enabling administrators to be granted precisely the level of access required for their role. This approach significantly reduces the attack surface by limiting the potential impact of compromised credentials. Furthermore, it facilitates auditing and compliance by making it straightforward to track and review administrative actions based on token purposes.

From a performance perspective, the module is designed for efficiency. It utilizes a static mapping of endpoints to required purposes, allowing for constant-time lookups when validating permissions. This design choice ensures that permission checks add minimal overhead to API requests, maintaining Sophra's high-performance characteristics even under heavy administrative load.

One of the unique features of this module is its ability to extract token purposes from standardized token names. This clever design allows for intuitive token management while still enforcing strict access controls. The module also provides utility functions for determining accessible endpoints and identifying super admin tokens, further enhancing its flexibility and integration capabilities within the broader Sophra ecosystem.

## Exported Components

<CodeGroup>
  ```typescript AdminTokenPurpose theme={null}
  type AdminTokenPurpose =
    | "api"
    | "monitoring"
    | "deployment"
    | "backup"
    | "maintenance";
  ```

  ```typescript AdminTokenPayload theme={null}
  interface AdminTokenPayload {
    name: string;
    type: "admin";
    purpose?: AdminTokenPurpose;
  }
  ```
</CodeGroup>

The module exports three key functions:

<CodeGroup>
  ```typescript hasPermission theme={null}
  export function hasPermission(
    tokenPayload: AdminTokenPayload,
    endpoint: string
  ): boolean
  ```

  ```typescript getAccessibleEndpoints theme={null}
  export function getAccessibleEndpoints(
    tokenPayload: AdminTokenPayload
  ): string[]
  ```

  ```typescript isSuperAdmin theme={null}
  export function isSuperAdmin(tokenPayload: AdminTokenPayload): boolean
  ```
</CodeGroup>

## Implementation Examples

<CodeGroup>
  ```typescript Token Validation theme={null}
  const adminToken: AdminTokenPayload = {
    name: "prod-api-1",
    type: "admin"
  };

  if (hasPermission(adminToken, "/api/keys")) {
    // Proceed with API key management
  } else {
    throw new Error("Unauthorized access to API key management");
  }
  ```

  ```typescript Endpoint Access theme={null}
  const monitoringToken: AdminTokenPayload = {
    name: "prod-monitoring-1",
    type: "admin"
  };

  const accessibleEndpoints = getAccessibleEndpoints(monitoringToken);
  console.log("Accessible endpoints:", accessibleEndpoints);
  // Output: ["/api/metrics", "/api/logs"]
  ```
</CodeGroup>

## Sophra Integration Details

The Admin Permissions Module integrates tightly with Sophra's authentication middleware and API gateway. When an administrative request is received, the following sequence occurs:

<Accordion title="Authentication and Authorization Flow">
  ```mermaid theme={null}
  sequenceDiagram
    participant Client
    participant APIGateway
    participant AuthMiddleware
    participant PermissionsModule
    participant TargetEndpoint

    Client->>APIGateway: Admin API Request
    APIGateway->>AuthMiddleware: Validate Admin Token
    AuthMiddleware->>PermissionsModule: Check Permission
    PermissionsModule-->>AuthMiddleware: Permission Result
    alt Permission Granted
      AuthMiddleware->>TargetEndpoint: Forward Request
      TargetEndpoint-->>Client: API Response
    else Permission Denied
      AuthMiddleware-->>Client: 403 Forbidden
    end
  ```
</Accordion>

## Error Handling

The module implements robust error handling to ensure security and provide clear feedback:

<AccordionGroup>
  <Accordion title="Invalid Token Format">
    If a token name doesn't conform to the expected format (e.g., "env-purpose-id"), the `getTokenPurpose` function returns `null`, resulting in a permission denial.
  </Accordion>

  <Accordion title="Unknown Endpoint">
    Requests to undefined endpoints in the `endpointPermissions` map are automatically denied, preventing access to potentially sensitive or unintended routes.
  </Accordion>

  <Accordion title="Insufficient Permissions">
    When a token's purpose doesn't match any required purpose for an endpoint, `hasPermission` returns `false`, triggering a 403 Forbidden response from the API gateway.
  </Accordion>
</AccordionGroup>

## Data Flow

The permission check process follows this flow:

```mermaid theme={null}
graph TD
    A[Receive Token] --> B{Extract Purpose}
    B -->|Valid Purpose| C{Check Endpoint}
    B -->|Invalid Purpose| F[Deny Access]
    C -->|Endpoint Found| D{Match Purpose}
    C -->|Endpoint Not Found| F
    D -->|Purpose Matches| E[Grant Access]
    D -->|Purpose Mismatch| F
```

## Performance Considerations

The module is designed for optimal performance:

* Static `endpointPermissions` map allows for O(1) lookup time
* Purpose extraction uses efficient string splitting
* Caching of token purposes could be implemented for frequently used tokens

## Security Implementation

<Card title="Token Purpose Validation" icon="shield-check">
  The `isValidPurpose` function ensures that only predefined purposes are accepted, preventing arbitrary purpose injection.
</Card>

<Card title="Least Privilege Principle" icon="lock">
  Tokens are scoped to specific purposes, limiting potential damage from compromised credentials.
</Card>

<Card title="Super Admin Detection" icon="user-shield">
  The `isSuperAdmin` function allows for special handling of high-privilege tokens, enabling additional security measures or auditing.
</Card>

## Configuration

The module's behavior can be customized through the following:

<CodeGroup>
  ```typescript Endpoint Permissions theme={null}
  const endpointPermissions: Record<string, AdminTokenPurpose[]> = {
    "/api/keys": ["api"],
    "/api/config/search": ["api", "deployment"],
    // ... additional endpoints
  };
  ```

  ```typescript Valid Purposes theme={null}
  function isValidPurpose(purpose: string): purpose is AdminTokenPurpose {
    return ["api", "monitoring", "deployment", "backup", "maintenance"].includes(
      purpose
    );
  }
  ```
</CodeGroup>

<Note>
  Modifying these configurations should be done with caution and requires a thorough security review to ensure the integrity of the permission system.
</Note>
