Skip to main content

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

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
  2. Navigate to SettingsAPI 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 SettingsAPI 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:
// 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:
// 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:
# .env file
PERF_API_KEY=pk_live_abc123xyz...
# Python
import os
api_key = os.environ.get('PERF_API_KEY')
// 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 SettingsAPI KeysUsage Analytics.

6. Implement Server-Side Proxies

For frontend applications, create a backend proxy:
// 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

TierRequests/MinuteRequests/Month
Free601,000
Pro300100,000
EnterpriseCustomCustom

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:
{
  "error": {
    "type": "rate_limit_exceeded",
    "message": "You have exceeded your rate limit",
    "retry_after": 30
  }
}
Implement exponential backoff:
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")

IP Allowlisting (Enterprise)

Enterprise customers can restrict API access to specific IP addresses:
  1. Navigate to SettingsSecurity
  2. Click IP Allowlist
  3. Add allowed IP addresses or CIDR ranges
  4. Save changes
Example allowlist:
203.0.113.0/24
198.51.100.42

Webhook Security

When receiving webhooks from Perf (for usage alerts, etc.), verify the signature:

Signature Verification

Perf signs webhook payloads with HMAC-SHA256:
import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(expected, signature)

# Usage
webhook_secret = os.environ.get('PERF_WEBHOOK_SECRET')
signature = request.headers.get('X-Perf-Signature')
is_valid = verify_webhook(request.body, signature, webhook_secret)

Compliance & Certifications

Current Certifications

  • SOC 2 Type II: Audited annually
  • GDPR Compliant: EU data protection standards
  • HIPAA Ready: For healthcare applications (Enterprise)
  • ISO 27001: Information security management

Data Handling

  • Encryption in Transit: TLS 1.3
  • Encryption at Rest: AES-256
  • Data Retention: Configurable (7-90 days)
  • Data Deletion: On-demand via API or dashboard

Regional Compliance

  • US: Data stored in US-East region
  • EU: Data stored in EU-West region (opt-in)
  • Data Residency: Enterprise customers can specify region

Audit Logs

Track all API activity in your audit log:
  1. Go to SettingsAudit Log
  2. Filter by:
    • Date range
    • API key
    • Event type (create, read, update, delete)
    • User
Export logs for compliance:
curl https://api.withperf.pro/v1/audit-logs?start_date=2024-01-01 \
  -H "Authorization: Bearer pk_live_abc123..." \
  -o audit-logs.json

Incident Response

If you suspect a security breach:
  1. Immediately revoke compromised API keys
  2. Review audit logs for unauthorized access
  3. Contact [email protected]
  4. Rotate all potentially affected keys
  5. Monitor for unusual activity

Security Contact

Report security vulnerabilities to: 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