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

# Authentication & Security

> Learn how to securely authenticate with the Perf API

# Authentication & Security

Learn how to securely authenticate with the Perf API and protect your integration.

## API Key Authentication

Perf uses API key authentication with Bearer tokens. All requests must include your API key in the `Authorization` header.

### Header Format

```
Authorization: Bearer YOUR_API_KEY
```

### Example Request

```bash theme={null}
curl https://api.withperf.pro/v1/chat \
  -H "Authorization: Bearer pk_live_abc123xyz..." \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "Hello"}]}'
```

## API Key Types

### Test Keys (`pk_test_...`)

* For development and testing
* Separate usage quotas from production
* No charges to your billing account
* Can be regenerated freely

### Production Keys (`pk_live_...`)

* For production environments
* Charges applied to your billing account
* Higher rate limits
* Should be rotated regularly for security

## Managing API Keys

### Creating Keys

1. Log in to [withperf.pro](https://withperf.pro)
2. Navigate to **Settings** → **API Keys**
3. Click **Generate New Key**
4. Provide a descriptive name (e.g., "Production Server", "Dev Environment")
5. Select key type (test or live)
6. Copy the key immediately - it won't be shown again

### Rotating Keys

We recommend rotating API keys every 90 days:

1. Generate a new key
2. Update your application configuration
3. Deploy the changes
4. Verify the new key works
5. Revoke the old key

### Revoking Keys

Immediately revoke a key if:

* It's been compromised
* An employee with access leaves
* You're retiring an application

To revoke:

1. Go to **Settings** → **API Keys**
2. Find the key in the list
3. Click **Revoke**
4. Confirm the action

Revoked keys are immediately invalidated.

## Security Best Practices

### 1. Never Expose Keys in Client-Side Code

**❌ Don't do this:**

```javascript theme={null}
// DANGER: API key exposed in browser
const response = await fetch('https://api.withperf.pro/v1/chat', {
  headers: {
    'Authorization': 'Bearer pk_live_abc123...' // Visible to users!
  }
});
```

**✅ Do this instead:**

```javascript theme={null}
// Make requests through your backend
const response = await fetch('/api/chat', {
  method: 'POST',
  body: JSON.stringify({ message: 'Hello' })
});
```

### 2. Use Environment Variables

Store API keys in environment variables, never in code:

```bash theme={null}
# .env file
PERF_API_KEY=pk_live_abc123xyz...
```

```python theme={null}
# Python
import os
api_key = os.environ.get('PERF_API_KEY')
```

```javascript theme={null}
// Node.js
const apiKey = process.env.PERF_API_KEY;
```

### 3. Restrict Key Permissions

When available, use scoped keys with minimal permissions:

* **Read-only keys**: For analytics dashboards
* **Write-only keys**: For logging systems
* **Admin keys**: For full account access (use sparingly)

### 4. Use Different Keys per Environment

Maintain separate keys for:

* Development
* Staging
* Production
* CI/CD pipelines

This allows you to:

* Track usage by environment
* Revoke specific keys without affecting others
* Apply different rate limits

### 5. Monitor Key Usage

Regularly review:

* Request volume per key
* Unusual access patterns
* Failed authentication attempts
* Geographic distribution

Access this data in **Settings** → **API Keys** → **Usage Analytics**.

### 6. Implement Server-Side Proxies

For frontend applications, create a backend proxy:

```javascript theme={null}
// Backend endpoint (Node.js/Express)
app.post('/api/chat', async (req, res) => {
  // Validate user session
  if (!req.session.userId) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // Apply rate limiting per user
  if (await isRateLimited(req.session.userId)) {
    return res.status(429).json({ error: 'Too many requests' });
  }

  // Call Perf API with server-side key
  const response = await fetch('https://api.withperf.pro/v1/chat', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.PERF_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      messages: req.body.messages,
      max_cost_per_call: 0.01 // Enforce budget
    })
  });

  const data = await response.json();
  res.json(data);
});
```

## Rate Limiting

Perf enforces rate limits to ensure fair usage and system stability.

### Current Limits

| Tier       | Requests/Minute | Requests/Month |
| ---------- | --------------- | -------------- |
| Free       | 60              | 1,000          |
| Pro        | 300             | 100,000        |
| Enterprise | Custom          | Custom         |

### Rate Limit Headers

Every response includes rate limit information:

```
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1672531200
```

### Handling Rate Limits

When you exceed limits, you'll receive a `429 Too Many Requests` response:

```json theme={null}
{
  "error": {
    "type": "rate_limit_exceeded",
    "message": "You have exceeded your rate limit",
    "retry_after": 30
  }
}
```

Implement exponential backoff:

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

def call_perf_with_retry(payload, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(url, json=payload, headers=headers)

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 60))
            wait_time = retry_after * (2 ** attempt)  # Exponential backoff
            time.sleep(wait_time)
            continue

        return response.json()

    raise Exception("Max retries exceeded")
```

## Data Handling

* **Encryption in Transit**: TLS 1.3 for all API requests
* **Prompts**: Processed in real-time, not stored permanently
* **Logs**: Metadata (model used, tokens, latency) is logged for analytics

## Incident Response

If you suspect a security breach:

1. **Immediately revoke** compromised API keys
2. **Review** audit logs for unauthorized access
3. **Contact** [security@withperf.pro](mailto:security@withperf.pro)
4. **Rotate** all potentially affected keys
5. **Monitor** for unusual activity

## Security Contact

Report security vulnerabilities to:

* **Email**: [security@withperf.pro](mailto:security@withperf.pro)
* **PGP Key**: Available at [withperf.pro/security.asc](https://withperf.pro/security.asc)

We have a responsible disclosure policy and provide:

* Acknowledgment within 24 hours
* Resolution timeframe within 30 days
* Recognition in our security hall of fame

## Next Steps

* [View API Reference](./api-reference/chat)
* [Read Best Practices](./resources/best-practices)
* [Explore Integration Examples](./integration-examples)
