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

# Security

> Security best practices and authorization model for the Prisme.ai API

Prisme.ai takes security seriously and provides multiple layers of protection for your data and API interactions. This guide covers security best practices, authentication mechanisms, and authorization models to help you build secure applications with the Prisme.ai API.

## Authentication and Authorization

<Tabs>
  <Tab title="Authentication Methods">
    Prisme.ai offers several authentication methods:

    <CardGroup cols="3">
      <Card title="JWT Authentication" icon="key">
        * Used for web applications
        * Session-based authentication
        * Handled by api-gateway service
        * Issued after OIDC authentication or anonymous login
      </Card>

      <Card title="Access Tokens" icon="ticket">
        * Long-lived authentication
        * Used for integrations and scripts
        * Can be generated by authenticated users
        * UUID-based opaque tokens
      </Card>

      <Card title="API Keys" icon="lock">
        * Scoped to specific workspaces
        * Fine-grained permission control
        * Ideal for third-party integrations
        * Can be created with expiration dates
      </Card>
    </CardGroup>

    For detailed information on these authentication methods, see [Authentication](/api-reference/authentication).
  </Tab>

  <Tab title="Authorization Model">
    Prisme.ai implements a flexible permission system:

    <Accordion title="Defining Roles">
      The RBAC system consists of several key elements:

      * **Roles**: Sets of permissions that can be assigned to users
      * **Subjects**: Resources that can be acted upon (pages, files, events, etc.)
      * **Actions**: Operations that can be performed on subjects (read, create, update, etc.)
      * **Rules**: Define which roles can perform which actions on which subjects
      * **Conditions**: Optional criteria that further restrict when rules apply
    </Accordion>

    <Accordion title="Defining Roles">
      ```
      authorizations:
        roles:
          editor: {}  # Built-in role
          
          # Custom role for regular users
          user:
            auth:
              prismeai: {}  # Automatically assigned to all Prisme.ai users
              
          # Role for API access
          workspace:
            auth:
              apiKey: {}  # Can be used with API keys
      ```
    </Accordion>

    <Accordion title="Creating Rules">
      Define what each role can do with specific rules:

      ```
      rules:
        # Allow editors to read and update workspaces
        - role: editor
          action:
            - read
            - get_usage
            - aggregate_search
            - update
          subject: workspaces
          
        # Give editors full control over files
        - role: editor
          action: manage  # Shorthand for all permissions
          subject: files

      ```

      Each rule must include at least:

      * **action**: What can be done (a single action or list)
      * **subject**: What it can be done to (a single subject or list)

      Rules can optionally specify:

      * **role**: Which role this applies to (if omitted, applies to everyone)
      * **conditions**: Restrict the rule to specific cases
      * **inverted**: Set to `true` to make this a deny rule instead of allow
      * **reason**: Documentation string for the rule
    </Accordion>
  </Tab>
</Tabs>

## Network Security

<Steps>
  <Step title="TLS Encryption">
    All API communications should use TLS encryption (HTTPS):

    * Prisme.ai API endpoints only accept HTTPS connections
    * Self-hosted instances should be configured with valid TLS certificates
    * Minimum TLS version 1.2 is recommended
    * Client applications should validate server certificates

    <Warning>
      Never send sensitive data over unencrypted connections. Always verify you're using `https://` URLs for API calls.
    </Warning>
  </Step>

  <Step title="Microservices Architecture">
    Prisme.ai uses a secure microservices architecture:

    * The api-gateway is the only publicly exposed service
    * Backend microservices are in a private network
    * Internal services trust the `x-prismeai-user-id` header from the api-gateway
    * Service-to-service communication uses internal authentication
  </Step>

  <Step title="IP Restrictions">
    For self-hosted deployments, consider implementing IP restrictions:

    * Limit API access to specific IP ranges
    * Use VPNs or private networks for sensitive operations
    * Configure firewalls to restrict access to the api-gateway
    * Implement network policies in Kubernetes deployments

    ```yaml theme={null}
    # Example Kubernetes Network Policy
    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: api-gateway-policy
      namespace: prisme-system
    spec:
      podSelector:
        matchLabels:
          app: api-gateway
      ingress:
      - from:
        - ipBlock:
            cidr: 10.0.0.0/24
        ports:
        - protocol: TCP
          port: 443
    ```
  </Step>
</Steps>

## Data Security

<CardGroup cols="2">
  <Card title="Data Encryption" icon="lock">
    * All data in transit is encrypted using TLS
    * Sensitive data at rest is encrypted
    * Encryption keys are rotated regularly
    * JWT signing keys are automatically rotated
  </Card>

  <Card title="Secret Management" icon="key">
    * API keys and secrets are securely stored
    * Passwords are hashed with strong algorithms
    * Workspace secrets are encrypted at rest
    * Environment variables for sensitive configuration
  </Card>

  <Card title="Data Isolation" icon="database">
    * Multi-tenant architecture with data isolation
    * Workspace-level data segregation
    * Database-level access controls
    * Row-level security where appropriate
  </Card>

  <Card title="Audit Logging" icon="list-check">
    * Authentication events are logged
    * API access is recorded
    * Permission changes are tracked
    * Security-relevant actions are audited
  </Card>
</CardGroup>

## JWT Security

<Accordion title="JWT Signing and Rotation">
  The api-gateway signs JWTs using JSON Web Keys (JWKs) that are automatically rotated:

  * JWKs are stored in the api-gateway database
  * Keys are rotated based on the `JWKS_ROTATION_DAYS` setting (default: 30 days)
  * When a JWK is rotated, it remains available for verifying existing JWTs
  * Rotated JWKs are removed after `ACCESS_TOKENS_MAX_AGE` (default: 30 days)
  * Key rotation happens during api-gateway startup

  <Warning>
    If a signing JWT has leaked, it must be manually deleted from the database before restarting the api-gateway and runtime services.
  </Warning>
</Accordion>

<Accordion title="JWT Configuration">
  Environment variables for JWT configuration:

  | Variable                | Description                    | Default Value     |
  | ----------------------- | ------------------------------ | ----------------- |
  | `JWKS_ROTATION_DAYS`    | Rotation period in days        | 30                |
  | `JWKS_KTY`              | JWK Algorithm family           | RSA               |
  | `JWKS_ALG`              | JWK signature algorithm        | RS256             |
  | `JWKS_SIZE`             | JWK size                       | 2048              |
  | `ACCESS_TOKENS_MAX_AGE` | JWT expiration time in seconds | 2592000 (30 days) |

  Public keys are available at `https://api.studio.prisme.ai/oidc/jwks` for JWT verification.
</Accordion>

## Security Best Practices

<Steps>
  <Step title="Secure Token Handling">
    Handle authentication tokens securely:

    * Store tokens in secure HTTP-only cookies or secure storage
    * Never expose tokens in URLs or client-side code
    * Implement token refresh mechanisms
    * Set appropriate token expiration times
    * Revoke tokens when no longer needed

    <Info>
      For web applications, consider using the authorization code flow with PKCE for enhanced security.
    </Info>
  </Step>

  <Step title="Implement Least Privilege">
    Follow the principle of least privilege:

    * Use API keys with minimal required permissions
    * Create role-specific tokens for different operations
    * Regularly audit and revoke unused access
    * Use workspace-scoped tokens instead of global ones

    ```javascript theme={null}
    // Example of creating a minimally privileged API key
    const response = await fetch('https://api.studio.prisme.ai/v2/workspaces/ws-123/apiKeys', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userToken}`
      },
      body: JSON.stringify({
        name: 'Read-only Document Access',
        permissions: [
          {type: 'workspace', id: 'ws-123', action: 'read'},
          {type: 'document', id: '*', action: 'read'}
        ],
        expiresIn: 7 * 24 * 60 * 60 // 7 days
      })
    });
    ```
  </Step>

  <Step title="Input Validation">
    Always validate input data:

    * Validate data types and formats
    * Sanitize inputs to prevent injection attacks
    * Use schema validation for request bodies
    * Implement proper error handling for invalid inputs

    ```javascript theme={null}
    // Example of input validation
    function validateWorkspaceId(workspaceId) {
      // Check for correct format (example: ws-123456)
      if (!/^ws-[a-zA-Z0-9]{6,}$/.test(workspaceId)) {
        throw new Error('Invalid workspace ID format');
      }
      return workspaceId;
    }
    ```
  </Step>

  <Step title="Secure Automation Development">
    When developing automations and integrations:

    * Avoid storing sensitive data in automation code
    * Use workspace secrets for credentials and tokens
    * Implement proper error handling and logging
    * Validate outputs from untrusted sources
    * Limit HTTP request capabilities to necessary endpoints

    ```yaml theme={null}
    # Example of using workspace secrets in automation
    do:
      - fetch:
          method: POST
          url: ${secrets.API_ENDPOINT}
          headers:
            Authorization: Bearer ${secrets.API_TOKEN}
          body:
            data: ${input.data}
    ```
  </Step>

  <Step title="Regular Security Review">
    Implement a regular security review process:

    * Audit API keys and access tokens
    * Review user permissions and roles
    * Check for unused integrations
    * Monitor for suspicious activity
    * Update client libraries and dependencies
  </Step>
</Steps>

## Self-Hosted Security Considerations

<Tabs>
  <Tab title="Infrastructure Security">
    For self-hosted Prisme.ai deployments:

    <CardGroup cols="2">
      <Card title="Kubernetes Security" icon="shield">
        * Enable Pod Security Policies
        * Implement network policies
        * Use [securityContext](/self-hosting/kubernetes/helm#security-context-configuration) settings
        * Keep Kubernetes version updated
      </Card>

      <Card title="Container Security" icon="cube">
        * Use minimal base images
        * Scan containers for vulnerabilities
        * Apply principle of least privilege
        * Don't run containers as root
      </Card>

      <Card title="Secret Management" icon="key">
        * Use Kubernetes secrets or external vault
        * Implement secrets encryption at rest
        * Rotate secrets regularly
        * Limit secret access to necessary pods
      </Card>

      <Card title="Database Security" icon="database">
        * Enable authentication and encryption
        * Implement network isolation
        * Apply least privilege for database users
        * Regular backup and recovery testing
      </Card>
    </CardGroup>
  </Tab>

  <Tab title="Authentication Integration">
    Options for integrating with enterprise authentication:

    <CardGroup cols="2">
      <Card title="OIDC Integration" icon="fingerprint">
        Connect Prisme.ai to your OIDC provider:

        * Configure OIDC client settings
        * Map identity provider groups to roles
        * Enable single sign-on
      </Card>

      <Card title="SAML Integration" icon="id-card">
        Connect to enterprise SAML providers:

        * Configure SAML service provider settings
        * Set up attribute mapping
        * Implement JIT provisioning
      </Card>
    </CardGroup>

    Example OIDC configuration:

    ```yaml theme={null}
    providers:
      <ProviderName>:
        type: oidc
        config:
          client_id: "your client id"
          client_secret: "your client secret"
          authorization_endpoint: "idp authorization_endpoint"
          token_endpoint: "idp token_endpoint"
          jwks_uri: "idp public certificates endpoint"
          scopes: "openid email profile"
    ```
  </Tab>
</Tabs>

## Security Monitoring and Incident Response

<Steps>
  <Step title="Security Monitoring">
    Implement monitoring for security events:

    * Authentication failures and successes
    * Permission changes
    * API key creation and usage
    * Rate limit violations
    * Unusual access patterns

    For self-hosted deployments, integrate with your SIEM system for centralized monitoring.
  </Step>

  <Step title="Logging">
    Configure comprehensive logging:

    ```yaml theme={null}
    # Example logging configuration
    - emit:
       event: 
       payload: 
         level: info
         securityEvents: true
         accessLogs: true
         authenticationEvents: true
         format: json
         outputs:
           - type: stdout
           - type: elasticsearch
             config:
               url: https://elasticsearch:9200
               index: prisme-logs
    ```

    <Warning>
      Ensure logs don't contain sensitive information like tokens, passwords, or personal data.
    </Warning>
  </Step>

  <Step title="Incident Response">
    Prepare for security incidents:

    * Document incident response procedures
    * Define roles and responsibilities
    * Test response plans periodically
    * Establish communication channels
    * Implement post-incident reviews
  </Step>
</Steps>

## Compliance and Auditing

<CardGroup cols="2">
  <Card title="Audit Logs" icon="clipboard-list">
    Prisme.ai maintains audit logs for compliance purposes:

    * User access and actions
    * Administrative changes
    * Authentication events
    * Data access patterns

    Access audit logs through the API or admin console.
  </Card>

  <Card title="Compliance Support" icon="check-circle">
    Prisme.ai helps meet various compliance requirements:

    * Data residency options
    * Data retention controls
    * Access control documentation
    * Security assessment support
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols="3">
  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Learn more about authentication methods
  </Card>

  <Card title="Rate Limits" icon="gauge-high" href="/api-reference/rate-limits">
    Understand API usage limits
  </Card>

  <Card title="Versioning" icon="code-branch" href="/api-reference/versioning">
    Learn about API versioning strategy
  </Card>
</CardGroup>
