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

# Security & Access Control

> Understand RBAC, authentication methods, and organization-based isolation in Jinba Toolbox

## Overview

Jinba Toolbox implements a multi-layered security model centered on **organization-based isolation**. Every resource -- toolsets, tools, versions, runs, API keys, and webhooks -- belongs to an organization and is protected by role-based access control (RBAC), authenticated sessions or API keys, and database-level tenant isolation.

## Authentication

Jinba Toolbox supports two authentication methods, each designed for a different access pattern:

<CardGroup cols={2}>
  <Card title="Session-Based (Web)" icon="browser">
    Used by the admin web console. Powered by **Better Auth** with session cookies.

    * Cookie-based session management
    * For human users managing toolsets
    * Full CRUD access to organization resources
  </Card>

  <Card title="API Key (Programmatic)" icon="key">
    Used by the SDK, AI agents, and external integrations. Passed as a Bearer token.

    * `Authorization: Bearer jtb_xxxxxxxxxxxx`
    * For automated and programmatic access
    * Scoped to a single organization
  </Card>
</CardGroup>

### API Key Management

API keys are scoped to an organization and track their issuer:

```
Organization
└── API Keys
    ├── production   (issued by: alice)   Last used: 2 hours ago
    ├── development  (issued by: bob)     Last used: 30 days ago
    └── ci-cd        (issued by: alice)   Last used: never
```

Key properties:

* **No expiration** by default -- keys remain valid until manually deleted.
* **Last-used timestamp** is recorded for each key.
* **Issuer tracking** -- the member who created the key is recorded.
* **Audit logging** -- key creation and deletion events are logged.

If the member who issued a key leaves the organization, the key remains active to avoid breaking integrations. The admin console displays a warning, and an Owner or Admin can take over or regenerate the key.

### API Key Endpoints

| Method | Endpoint                          | Description    |
| ------ | --------------------------------- | -------------- |
| GET    | `/v1/orgs/:orgId/api-keys`        | List API keys  |
| POST   | `/v1/orgs/:orgId/api-keys`        | Create API key |
| DELETE | `/v1/orgs/:orgId/api-keys/:keyId` | Delete API key |

## Role-Based Access Control (RBAC)

### Role Hierarchy

Jinba Toolbox defines roles at two levels:

```
Platform Level
└── super_admin          # Service-wide administration

Organization Level
├── Owner                # Organization owner (one per org)
├── Admin                # Organization administrator
└── Member               # Regular member
```

### Organization Roles

| Role       | Description                                                                                      |
| ---------- | ------------------------------------------------------------------------------------------------ |
| **Owner**  | Full control over the organization, including transfer and deletion. One Owner per organization. |
| **Admin**  | Can manage members, billing, and all organization resources. Cannot delete the organization.     |
| **Member** | Can create and manage toolsets and tools. Cannot manage other members or billing.                |

### Permission Matrix

| Resource              | Owner | Admin         | Member |
| --------------------- | ----- | ------------- | ------ |
| Organization settings | CRUD  | Read / Update | Read   |
| Delete organization   | Yes   | No            | No     |
| Member management     | CRUD  | CRUD          | Read   |
| Invite members        | Yes   | Yes           | No     |
| ToolSet / Tool        | CRUD  | CRUD          | CRUD   |
| API keys (own)        | CRUD  | CRUD          | CRUD   |
| API keys (others')    | CRUD  | CRUD          | No     |
| Purchase credits      | Yes   | Yes           | No     |
| View credit balance   | Yes   | Yes           | Read   |
| Audit logs            | Read  | Read          | No     |

### Role Rules

* Each organization has exactly **one Owner**.
* Ownership can be **transferred** to another member (the original owner becomes Admin).
* Only Owners and Admins can **invite** new members.
* Members can manage their own API keys but cannot see or delete keys created by others.

## Organization-Based Isolation

Every resource in Jinba Toolbox is scoped to an organization. The isolation is enforced at multiple layers:

### Application Layer

The API server validates that the authenticated user or API key belongs to the target organization before processing any request. This ensures that even if a database query is somehow misconfigured, the application layer blocks unauthorized access.

### Database Layer (Row Level Security)

PostgreSQL Row Level Security (RLS) provides an additional layer of tenant isolation at the database level:

```sql theme={null}
ALTER TABLE tool_set ENABLE ROW LEVEL SECURITY;

CREATE POLICY tool_set_tenant_isolation ON tool_set
  USING (organization_id = current_setting('app.current_org_id'));
```

**How it works:**

<Steps>
  <Step title="Request arrives">
    The API server authenticates the request and determines the organization ID.
  </Step>

  <Step title="Set session variable">
    Before executing any queries, the server sets the PostgreSQL session variable:

    ```sql theme={null}
    SET app.current_org_id = :orgId
    ```
  </Step>

  <Step title="RLS filters rows">
    PostgreSQL automatically filters all query results to only include rows belonging to the current organization.
  </Step>
</Steps>

**Tables protected by RLS:**

* `tool_set`
* `tool`
* `tool_set_version`
* `run`
* `apikey`
* `webhook`
* `audit_log`

This multi-layer approach (application + database) provides **defense in depth** -- even if a bug bypasses the application checks, the database itself prevents cross-tenant data access.

## Audit Logging

Significant actions within an organization are recorded in an audit log:

| Category | Events                                                       |
| -------- | ------------------------------------------------------------ |
| API Key  | Created, deleted                                             |
| Member   | Added, removed, role changed                                 |
| ToolSet  | Published, published version changed                         |
| Settings | Organization settings changed, webhook configuration changed |

Tool executions are tracked separately in the `runs` table with full input/output logging.

### Audit Log Data Model

```typescript theme={null}
interface AuditLog {
  id: string;
  orgId: string;
  userId: string;         // Who performed the action
  action: string;         // e.g., "member.added"
  targetType: string;     // e.g., "member"
  targetId: string;       // ID of the affected resource
  details: object;        // Change details
  ipAddress: string;
  createdAt: Date;
}
```

### Viewing Audit Logs

Audit logs are available to **Owner** and **Admin** roles in the web console at `/org/:orgId/settings/audit-log`. Logs are retained **indefinitely**.

## Sandbox Isolation

Tool execution occurs in isolated sandbox environments (E2B or Daytona). Each execution runs in a fresh or resumed sandbox instance with:

* **Process isolation** -- each sandbox is a separate container or VM.
* **Network isolation** -- sandboxes cannot access the API server's internal network.
* **Configurable environment variables** -- secrets are injected per toolset, not shared across toolsets.
* **Automatic cleanup** -- sandboxes are terminated after execution completes or times out.

## Best Practices

* **Use separate API keys** for different environments (production, staging, CI/CD) to limit blast radius if a key is compromised.
* **Audit API key usage** -- review the last-used timestamp regularly and delete keys that are no longer needed.
* **Assign the least-privilege role** -- use Member for developers who only need to create and edit tools.
* **Review audit logs** periodically to detect unexpected access patterns.
* **Do not share API keys** between organizations -- each key is scoped to a single organization.

## Related

* [REST API](/en/pages/toolbox/developer/api) -- Authentication details and endpoint reference
* [Webhooks](/en/pages/toolbox/developer/webhooks) -- Event notification security (signature verification)
* [Sandbox Providers](/en/pages/toolbox/advanced/sandbox) -- Execution environment isolation
