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

# Authentication

> Learn how to authenticate with the Buena.ai API using API keys

All Buena.ai API requests require authentication using user-specific API keys. Each key has granular permissions and tracks usage for security and billing purposes.

## API Key Format

Buena.ai supports two types of API keys for maximum flexibility and backward compatibility:

### User-Specific API Keys (Recommended)

Format: `bna_[hexadecimal]` where the hexadecimal string is 64 characters long:

```
bna_bxxxxxxxxxx
```

**Benefits:**

* **Automatic User Detection**: No need to specify user IDs in requests
* **Enhanced Security**: User-specific permissions and rate limiting
* **Better Tracking**: Automatic usage tracking and last-used timestamps
* **Granular Permissions**: Support for specific permission scopes

### Global API Keys (Legacy)

Format: Traditional API key format for backward compatibility:

```
abc12345-xyz789def456ghi123jkl
```

**Characteristics:**

* **Full Access**: All permissions (`*`)
* **Legacy Support**: Works with all existing endpoints
* **Requires User IDs**: Must specify user IDs in request parameters
* **Backward Compatible**: Maintains compatibility with v1 API patterns

## Authentication Header

Include your API key in the `x-api-key` header for all requests:

```bash theme={null}
curl -H "x-api-key: YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     "https://api.buena.ai/api/v2/health"
```

<Warning>
  Never expose your API key in client-side code, public repositories, or logs.
  Always use environment variables or secure secret management.
</Warning>

## Permission System

Each API key has specific permissions that control access to different endpoints. User-specific API keys support granular permissions, while global API keys have all permissions (`*`).

<CardGroup cols={2}>
  <Card title="User Permissions" icon="user">
    * `users:read` - Read user data and settings - `users:write` - Modify user
      data and settings
  </Card>

  <Card title="LinkedIn Permissions" icon="linkedin">
    * `linkedin:schedule` - Schedule LinkedIn actions - `linkedin:upload` -
      Upload prospect lists - `linkedin:read` - Read LinkedIn data -
      `linkedin:voice` - Send LinkedIn voice messages
  </Card>

  <Card title="Lead Permissions" icon="users">
    * `leads:read` - Read lead data - `leads:write` - Create/update leads -
      `leads:enrich` - Enrich lead data
  </Card>

  <Card title="Voice Permissions" icon="microphone">
    * `voice:create` - Create voice clones - `voice:read` - List voice clones -
      `voice:update` - Update voice settings - `voice:delete` - Delete voice
      clones - `voice:preview` - Generate voice previews
  </Card>

  <Card title="Job Permissions" icon="clock">
    * `jobs:read` - Read job data and status - `jobs:update` - Modify job
      messages
  </Card>
</CardGroup>

### Common Permission Sets

<AccordionGroup>
  <Accordion title="Read-Only Access">
    Perfect for analytics and monitoring: `["users:read", "linkedin:read",
            "leads:read", "jobs:read"]`
  </Accordion>

  <Accordion title="LinkedIn Automation">
    For LinkedIn automation workflows: `["users:read", "linkedin:schedule",
            "linkedin:read", "jobs:read"]`
  </Accordion>

  <Accordion title="Lead Management">
    For CRM integration and lead processing: `["users:read", "leads:read",
            "leads:write", "leads:enrich"]`
  </Accordion>

  <Accordion title="Full Integration">
    For comprehensive platform integration: `["users:read", "users:write",
            "linkedin:schedule", "linkedin:read", "leads:read", "leads:write",
            "leads:enrich", "jobs:read"]`
  </Accordion>
</AccordionGroup>

### Permission Requirements by Endpoint

| Endpoint                                | Permission Required |
| --------------------------------------- | ------------------- |
| `POST /linkedin/scheduleLinkedInAction` | `linkedin:schedule` |
| `POST /linkedin/uploadProspects`        | `linkedin:upload`   |
| `GET /leads`                            | `leads:read`        |
| `POST /leads`                           | `leads:write`       |
| `POST /enrich`                          | `leads:enrich`      |
| `GET /users/jobs`                       | `users:read`        |
| `GET /health`, `GET /info`              | None                |

## Creating API Keys

### Via Dashboard

1. Log into your [Buena.ai dashboard](https://app.buena.ai)
2. Navigate to Settings → API Keys
3. Click "Create New Key"
4. Set permissions and expiration
5. Copy and store the key securely

### Via API

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.buena.ai/api/v2/keys" \
    -H "x-api-key: YOUR_EXISTING_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Production Integration",
      "permissions": ["linkedin:schedule", "leads:read", "leads:write"],
      "expiresInDays": 365
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.buena.ai/api/v2/keys", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_EXISTING_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name: "Production Integration",
      permissions: ["linkedin:schedule", "leads:read", "leads:write"],
      expiresInDays: 365,
    }),
  });
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.buena.ai/api/v2/keys',
      headers={
          'x-api-key': 'YOUR_EXISTING_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'name': 'Production Integration',
          'permissions': ['linkedin:schedule', 'leads:read', 'leads:write'],
          'expiresInDays': 365
      }
  )
  ```
</CodeGroup>

## Managing API Keys

### List Keys

```bash theme={null}
curl -H "x-api-key: YOUR_API_KEY" \
     "https://api.buena.ai/api/v2/keys"
```

### Update Key

```bash theme={null}
curl -X PUT "https://api.buena.ai/api/v2/keys/{keyId}" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Key Name",
    "permissions": ["linkedin:read", "leads:read"]
  }'
```

### Regenerate Key

```bash theme={null}
curl -X POST "https://api.buena.ai/api/v2/keys/{keyId}/regenerate" \
  -H "x-api-key: YOUR_API_KEY"
```

### Delete Key

```bash theme={null}
curl -X DELETE "https://api.buena.ai/api/v2/keys/{keyId}" \
  -H "x-api-key: YOUR_API_KEY"
```

## Best Practices

<AccordionGroup>
  <Accordion title="Environment Variables">
    Store API keys in environment variables, never in code:

    ```bash theme={null}
    export BUENA_API_KEY="your-api-key-here"
    ```

    ```javascript theme={null}
    const apiKey = process.env.BUENA_API_KEY;
    ```
  </Accordion>

  <Accordion title="Key Rotation">
    * Rotate keys every 90 days - Use different keys for different environments -
      Monitor key usage regularly - Deactivate unused keys immediately
  </Accordion>

  <Accordion title="Principle of Least Privilege">
    Only grant the minimum permissions needed: - **Read-only operations**: Use
    `leads:read`, `linkedin:read` - **Automation scripts**: Add
    `linkedin:schedule`, `linkedin:upload` - **Full integration**: Include
    `leads:write`, `leads:enrich`
  </Accordion>

  <Accordion title="Error Handling">
    Always check for authentication errors:

    ```javascript theme={null}
    if (response.status === 401) {
      console.error('Invalid API key');
    } else if (response.status === 403) {
      console.error('Insufficient permissions');
    }
    ```
  </Accordion>
</AccordionGroup>

## Authentication Errors

### 401 Unauthorized

```json theme={null}
{
  "error": true,
  "code": "UNAUTHORIZED",
  "message": "Invalid API key",
  "version": "2.0"
}
```

**Causes:**

* Missing `x-api-key` header
* Invalid API key format
* Expired API key
* Deactivated API key

### 403 Forbidden

```json theme={null}
{
  "error": true,
  "code": "PERMISSION_DENIED",
  "message": "Insufficient permissions",
  "version": "2.0",
  "permissionHelp": {
    "required": "linkedin:schedule",
    "available": ["linkedin:read"],
    "documentation": "https://docs.buena.ai/authentication"
  }
}
```

**Causes:**

* API key lacks required permission
* Attempting to access restricted endpoint
* Rate limit exceeded

## Testing Authentication

Use the health endpoint to verify your authentication:

<CodeGroup>
  ```bash cURL theme={null}
  curl -H "x-api-key: YOUR_API_KEY" \
       "https://api.buena.ai/api/v2/health"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.buena.ai/api/v2/health", {
    headers: { "x-api-key": "YOUR_API_KEY" },
  });

  if (response.ok) {
    console.log("Authentication successful!");
  } else {
    console.error("Authentication failed:", response.status);
  }
  ```
</CodeGroup>

Successful response:

```json theme={null}
{
  "version": "2.0",
  "status": "healthy",
  "authentication": "user",
  "user": {
    "id": "user_abc123",
    "email": "john@company.com",
    "role": "Premium"
  },
  "apiKey": {
    "name": "My Integration Key",
    "permissions": ["linkedin:schedule", "leads:read"],
    "usageCount": 42
  }
}
```
