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

# Role-Based Access Control

> Implement security and access management for Builder applications with RBAC

Role-Based Access Control (RBAC) is the security model used in Prisme.ai to manage who can access, modify, and use different parts of your workspace. It ensures that users only have the permissions they need while protecting sensitive information and functionality.

## RBAC Fundamentals

<Tabs>
  <Tab title="Core Concepts">
    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

    These components work together to create a flexible yet secure access control system.
  </Tab>

  <Tab title="Authorization Structure">
    RBAC configuration is defined in YAML format and consists of two main sections:

    ```yaml theme={null}
    authorizations:
      # Define roles
      roles:
        editor: {}
        custom_role: {}
        
      # Define access rules
      rules:
        - role: editor
          action: read
          subject: pages
    ```

    You can access and edit this configuration through your workspace settings.
  </Tab>

  <Tab title="Default Roles">
    Prisme.ai includes several built-in roles:

    * **Owner**: Created automatically for workspace creator, has full access
    * **Editor**: Can create and modify content but limited administrative access
    * **Custom Roles**: Additional roles you define for specific needs

    <Info>
      The Owner role is special and cannot be modified or deleted. It is automatically assigned to workspace creators and administrators.
    </Info>
  </Tab>
</Tabs>

## Managing Roles and Rules

<Steps>
  <Step title="Accessing RBAC Settings">
    To view and edit your workspace's access control configuration:

    1. Go to your workspace
    2. Navigate to **Settings > Advanced > Manage Roles**
    3. Edit the YAML configuration
    4. Save your changes

    <Warning>
      Changes to RBAC settings take effect immediately. Be careful not to lock yourself out!
    </Warning>
  </Step>

  <Step title="Defining Roles">
    Create custom roles to fit your organization's needs:

    ```yaml theme={null}
    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
    ```

    <Info>
      The `auth` section allows you to automatically assign roles based on authentication providers.
    </Info>
  </Step>

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

    ```yaml theme={null}
    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. If omitted (or an empty object), the rule will apply to every instance of specified **subject**
    * **inverted**: Set to `true` to make this a deny rule instead of allow
    * **reason**: Documentation string for the rule
  </Step>

  <Step title="Adding Conditions">
    Restrict rules to specific situations with conditions:

    ```yaml theme={null}
    # Allow access only to pages with a "public" label
    - action: read
      subject: pages
      conditions:
        labels:
          $in:
            - public

    # Deny editor access to API key events
    - role: editor
      inverted: true
      action: read
      subject: events
      conditions:
        type:
          $regex: ^apikeys\.*$
    ```

    Conditions use a [subset of MongoDB query syntax](https://casl.js.org/v4/en/guide/conditions-in-depth#supported-operators) for powerful filtering.
  </Step>
</Steps>

## Common RBAC Patterns

<AccordionGroup>
  <Accordion title="Public Access">
    Control what unauthenticated users can access:

    ```yaml theme={null}
    # Allow anyone to read pages with "public" label
    - action: read
      subject: pages
      conditions:
        labels:
          $in:
            - public
            
    # Allow anyone to create events (for automations)
    - action: create
      subject: events
      conditions:
        source.serviceTopic: topic:runtime:emit
      reason: Anyone can create any events
    ```

    <Info>
      Rules without a `role` specified apply to everyone, including unauthenticated users.
    </Info>
  </Accordion>

  <Accordion title="Role-Based Access">
    Define what each role can do:

    ```yaml theme={null}
    # User role can read all pages
    - role: user
      action:
        - read
      subject: pages

    # Editor role can read and update pages
    - role: editor
      action:
        - read
        - update
      subject: pages
    ```

    This approach creates a clear hierarchy of access permissions.
  </Accordion>

  <Accordion title="API Key Permissions">
    Configure permissions for API access:

    ```yaml theme={null}
    # Define workspace role for API access
    roles:
      workspace:
        auth:
          apiKey: {}
          
    # Grant specific permissions to this role
    rules:
      - role: workspace
        action:
          - read
          - manage_permissions
        subject:
          - workspaces
          - events
          - pages
          - files
    ```

    This allows creating an internal workspace API key with specific permissions.\
    The api key value can't be directly accessed, but instead can be injected in `fetch` instruction :

    ```yaml theme={null}
      - fetch:
          url: '...'
          prismeaiApiKey:
            name: workspace
    ```
  </Accordion>

  <Accordion title="Automatic assignment">
    Automatically assign roles based on SSO provider & auth data :

    ```yaml theme={null}
    roles:
      # Assign user role to all Prisme.ai & yourOwnSso authenticated users
      user:
        auth:
          prismeai: {}
          yourOwnSso: {}
          
      # Assign admin role to users from a specific email domain
      admin:
        auth:
          prismeai:
            conditions:
              authData.email:
                $regex: ^.*@mycompany.com$
    ```

    This reduces manual user management by leveraging authentication information.
  </Accordion>
</AccordionGroup>

## Subjects and Actions

RBAC controls access to various resource types through subject and action combinations:

<AccordionGroup>
  <Accordion title="Workspaces" icon="building">
    **Subject :** `workspaces`

    **Actions :**

    * `read` : allows reading the workspace configuration
    * `update` : allows updating the workspace configuration
    * `delete` : allows deleting the workspace
    * `manage_security` :  allows updating security configuration
    * `manage_permissions` : allows sharing / unsharing
    * `aggregate_search` : allows using /search API
    * `get_usage` : allows using /usage API
    * `manage_repositories` : allows managing repositories settings
    * `manage` : allows all above actions
  </Accordion>

  <Accordion title="Pages" icon="file">
    **Subject :** `pages`

    **Actions :**

    * `create` : allows creating a page
    * `read` : allows reading pages
    * `update` : allows updating pages
    * `delete` : allows deleting pages
    * `manage` : allows all above actions
  </Accordion>

  <Accordion title="Files" icon="image">
    **Subject :** `files`

    **Actions :**

    * `create` : allows uploading a file
    * `read` : allows reading files
    * `update` : allows updating files
    * `delete` : allows deleting files
    * `manage` : allows all above actions
  </Accordion>

  <Accordion title="Events" icon="bell">
    **Subject :** `events`

    **Actions :**

    * `create` : allows emitting an event
    * `read` : allows reading events
    * `manage` : allows all above actions
  </Accordion>

  <Accordion title="Automations" icon="gears">
    **Subject :** `automations`

    **Actions :**

    * `create` : allows creating an automation
    * `read` : allows reading automations
    * `update` : allows updating automations
    * `delete` : allows deleting automations
    * `execute` : allows executing automations
    * `manage` : allows all above actions
  </Accordion>

  <Accordion title="Secrets" icon="key">
    **Subject :** `secrets`

    **Actions :**

    * `create` : allows creating secrets
    * `read` : allows reading secrets
    * `update` : allows updating secrets
    * `delete` : allows deleting secrets
    * `manage` : allows all above actions
  </Accordion>

  <Accordion title="Apps" icon="rocket">
    **Subject :** `apps`

    **Actions :**

    * `create` : allows publishing an app
    * `read` : allows viewing/installing apps
    * `update` : allows updating apps
    * `delete` : allows deleting apps
    * `manage` : allows all above actions
  </Accordion>
</AccordionGroup>

## Securing Automations

By default, anyone can execute any automation that has an event or endpoint trigger. To restrict access to sensitive automations:

<Steps>
  <Step title="Define Authorization Action">
    In your automation, specify an authorization requirement:

    ```yaml theme={null}
    slug: getAnalytics
    name: "Admin Page: Init Analytics"
    description: "Restricted automation for admin use only"
    when:
      events:
        - initAnalytics
    do:
      - emit:
          event: updateAnalytics
          payload:
            data: [...]
    authorizations:
      action: admin  # This is the authorization key
    ```

    The `authorizations.action` field specifies a permission key for this automation.
  </Step>

  <Step title="Create Permission Rule">
    Define who can execute automations with this authorization key:

    ```yaml theme={null}
    # Allow admin role to execute automations with "admin" authorization
    - role: admin
      action: execute
      subject: automations
      conditions:
        authorizations.action:
          $in:
            - admin
    ```

    This restricts execution only to users with the specified role.
  </Step>

  <Step title="Test the Restriction">
    Verify that:

    * Users with the admin role can execute the automation
    * Users without the admin role receive an authorization error
    * The automation cannot be called indirectly by other automations without permission
  </Step>
</Steps>

## Using API Keys

<Accordion title="External API Keys">
  API keys allow programmatic access to your workspace with specific permissions :

  1. Use Prismeai APIs to generate an api key :

  ```bash theme={null}
  curl --location 'https://api.studio.prisme.ai/v2/workspaces/<WORKSPACE_ID>/security/apiKeys' \
  --header 'Authorization: Bearer <JWT>' \
  --header 'Content-Type: application/json' \
  --data '{
    "name": "api key name",
    "rules": [
        {
            "action": "create",
            "subject": "files"
        },
        {
            "action": ["create", "update", "read"],
            "subject": "pages",
            "conditions": {
                "labels": {
                    "$in": ["internal"]
                }
            }
        }        
    ]
  }'  
  ```

  2. Include the received apikey in `x-prismeai-api-key` header :

  ```javascript theme={null}
  fetch('https://api.studio.prisme.ai/v2/events', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-prismeai-api-key': 'your-api-key'
    },
    body: JSON.stringify({ type: 'custom-event', payload: { data: 'value' } })
  });
  ```

  <Warning>
    Keep API keys secure. They grant access based on their associated role without requiring user authentication.
  </Warning>
</Accordion>

<Accordion title="Workspace API Keys">
  For internal API calls from automations, you can define built-in API keys:

  ```yaml theme={null}
  roles:
    workspace:
      auth:
        apiKey: {}
        
  rules:
    - role: workspace
      action:
        - read
        - aggregate_search
      subject:
        - workspaces
        - events
  ```

  This creates an internal API key that automations can use:

  ```yaml theme={null}
  - Prismeai API.searchEvents:
      query:
        type: user-login
      prismeaiApiKey:
        name: workspace
      output: events
  ```

  <Info>
    Workspace API keys are not visible in the UI and are specifically for internal use.
  </Info>
</Accordion>

## Example RBAC Configuration

Here's a complete example of a typical RBAC configuration:

<Accordion title="Full RBAC Example">
  ```yaml theme={null}
  authorizations:
    roles:
      editor: {}
      user:
        auth:
          prismeai: {}
      workspace:
        auth:
          apiKey: {}
    rules:
      # Public access rules
      - action: read
        subject: pages
        conditions:
          labels:
            $in:
              - public
              
      # Workspace API key permissions
      - role: workspace
        action:
          - read
          - manage_permissions
        subject:
          - workspaces
          - events
          - pages
          - files
      - role: workspace
        action:
          - update
        subject:
          - files
          
      # User role permissions
      - role: user
        action:
          - read
        subject: pages
        
      # Editor role permissions
      - role: editor
        action:
          - read
          - get_usage
          - aggregate_search
          - update
        subject: workspaces
      - role: editor
        action: manage
        subject: files
      - role: editor
        action:
          - read
          - update
        subject: pages
      - role: editor
        action:
          - read
          - update
        subject: apps
      - role: editor
        action:
          - read
          - create
        subject: events
          
      # Editor role restrictions
      - role: editor
        inverted: true
        action: read
        subject: events
        conditions:
          type:
            $regex: ^apikeys\.*$
            
      # Public event access
      - action: create
        subject: events
        reason: Anyone can create any events
        conditions:
          source.serviceTopic: topic:runtime:emit
      - action: read
        subject: events
        conditions:
          source.serviceTopic: topic:runtime:emit
          source.sessionId: '{{session.id}}'
        reason: Anyone can read any events from its own session
        
      # Public file upload
      - action: create
        subject: files
        conditions:
          mimetype:
            $regex: ^(.*)$
        reason: Anyone can upload any file
  ```
</Accordion>

## Security Best Practices

<CardGroup cols={2}>
  <Card title="Principle of Least Privilege" icon="shield-check">
    <p>Give users only the permissions they actually need:</p>

    <ul>
      <li>Start with minimal permissions and add as required</li>
      <li>Use specific conditions to limit rule scope</li>
      <li>Avoid "manage" permission when more specific actions suffice</li>
      <li>Regularly review and prune unnecessary permissions</li>
    </ul>
  </Card>

  <Card title="Secure Public Access" icon="users">
    <p>Carefully control what unauthenticated users can do:</p>

    <ul>
      <li>Use explicit conditions on public rules</li>
      <li>Limit event creation to specific event types</li>
      <li>Be cautious with file upload permissions</li>
      <li>Restrict user session events appropriately</li>
    </ul>
  </Card>

  <Card title="Protect Sensitive Automations" icon="lock">
    <p>Secure automations that access sensitive data:</p>

    <ul>
      <li>Add authorization requirements to important automations</li>
      <li>Create specific roles for administrative functions</li>
      <li>Avoid sensitive data exposure through events</li>
      <li>Test automations with different user roles</li>
    </ul>
  </Card>

  <Card title="Manage API Access" icon="key">
    <p>Control programmatic access carefully:</p>

    <ul>
      <li>Create API keys with minimal required permissions</li>
      <li>Rotate API keys regularly</li>
      <li>Monitor API key usage for unusual patterns</li>
      <li>Delete unused API keys promptly</li>
    </ul>
  </Card>
</CardGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Access Denied Unexpectedly">
    When users encounter permission errors they shouldn't:

    **Check these common issues:**

    * Verify the user has the correct role assignment
    * Look for inverted rules (deny rules) that might be applying
    * Check if conditions on rules are unintentionally restrictive
    * Ensure the rule order places more specific rules after general ones

    **Example fix:**

    ```yaml theme={null}
    # Add a more permissive rule for this specific case
    - role: user
      action: read
      subject: pages
      conditions:
        category: reports
    ```
  </Accordion>

  <Accordion title="Too Much Access">
    When users have permissions they shouldn't have:

    **Check these common issues:**

    * Look for overly broad rules without conditions
    * Check if the user has multiple roles granting cumulative permissions
    * Verify automatic role assignment isn't giving unintended access
    * Ensure public rules (no role specified) aren't too permissive

    **Example fix:**

    ```yaml theme={null}
    # Add a specific deny rule
    - role: user
      inverted: true
      action: read
      subject: pages
      conditions:
        category: admin
        
    # Or make existing rules more specific
    - role: user
      action: read
      subject: pages
      conditions:
        category: 
          $ne: admin
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Automations" icon="gears" href="/products/ai-builder/automations">
    Explore automations and their security model
  </Card>
</CardGroup>
