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

# Rotation Strategies

> Learn how to rotate API keys, secrets, and routes for security. Zero-downtime rotation patterns included.

# Rotation Strategies

Regularly rotating credentials and configurations is critical for security. KnoxCall provides tools to rotate everything with minimal downtime.

## What Can Be Rotated?

KnoxCall supports rotating:

* **🔑 API Keys**: Create new keys, revoke old ones
* **🔐 Secrets**: Add new versions of encrypted credentials
* **🛣️ Routes**: Duplicate route configurations
* **🌍 Environments**: Clone environment overrides

Each rotation strategy has different impacts and use cases.

## Why Rotate?

### Security Best Practices

**Rotate when:**

* ✅ Credentials are compromised or suspected compromise
* ✅ Employee leaves or loses access
* ✅ Compliance requirements (e.g., 90-day rotation)
* ✅ Moving from development to production
* ✅ Deprecating old integration

**Benefits:**

* 🔒 Limit window of exposure from leaked credentials
* 📊 Audit trail of when credentials changed
* 🎯 Zero-trust architecture (regular rotation = no long-lived secrets)
* 🛡️ Compliance with security frameworks (SOC 2, ISO 27001)

## Rotation Strategy 1: API Keys

### What It Is

KnoxCall API keys authenticate requests:

```text theme={"dark"}
x-knoxcall-key: tk_abc123xyz789...
```

**Rotating API keys** = Create new key, revoke old key

### When to Rotate

**Rotate API keys when:**

* ✅ Every 90 days (security best practice)
* ✅ Key exposed (logs, screenshots, public repo)
* ✅ Employee departure
* ✅ Service migration (dev → prod)
* ✅ Suspect unauthorized access

**Benefits:**

* Limit blast radius of compromised keys
* Clear audit trail of which key made which requests
* Different keys per environment (dev/staging/prod)

### How to Rotate API Keys

#### Method 1: Create-Before-Revoke (Zero Downtime)

**Step 1: Create New Key**

1. Navigate to **Settings** → **Tenant** tab
2. Scroll to **API Keys** section
3. Click **Create API Key**
4. Name it (e.g., "Production Key 2025 Q1")
5. **Copy the key immediately** (you'll only see it once!)

Example key: `tk_def456ghi789jkl012mno345pqr567stu890`

**Step 2: Update One Client**

Deploy new key to **one client** first (canary):

```javascript theme={"dark"}
// Old key
const API_KEY = "tk_abc123xyz789...";

// New key
const API_KEY = "tk_def456ghi789...";
```

Restart that client and monitor logs.

**Step 3: Verify**

Check **Logs** page - requests should show new key ID:

```text theme={"dark"}
Key ID: key_def456... ✓
```

If errors occur, revert and investigate.

**Step 4: Update Remaining Clients**

Roll out new key to all clients:

* Production servers
* Staging servers
* Development environments
* CI/CD pipelines

**Step 5: Monitor Grace Period**

Wait 24-48 hours. Check logs to ensure old key isn't being used:

```sql theme={"dark"}
-- Check if old key still in use
SELECT COUNT(*) FROM api_logs
WHERE key_id = 'key_abc123...'
AND timestamp > NOW() - INTERVAL '1 day';
```

If count is 0, old key is unused.

**Step 6: Revoke Old Key**

1. Navigate to **Settings** → **Tenant** tab → **API Keys**
2. Find old key: `tk_abc123...`
3. Click **Revoke**
4. Confirm

Old key stops working immediately.

<Tip>
  **Pro tip**: Create multiple keys for different environments. If one is compromised, you only revoke that one instead of breaking all environments.
</Tip>

#### Method 2: Blue-Green Key Rotation

Use two keys in rotation:

**Setup:**

* **Blue Key**: `tk_blue_abc123...` (currently active)
* **Green Key**: `tk_green_def456...` (standby)

**Rotation cycle:**

```text theme={"dark"}
Week 1: Blue active, create new Green
Week 2: Switch to Green, revoke old Blue
Week 3: Green active, create new Blue
Week 4: Switch to Blue, revoke old Green
...cycle continues
```

**Benefits:**

* Always have backup key ready
* Predictable rotation schedule
* Easy to automate

**Implementation:**

```javascript theme={"dark"}
const KEYS = {
  blue: process.env.KNOXCALL_BLUE_KEY,
  green: process.env.KNOXCALL_GREEN_KEY,
  active: process.env.KNOXCALL_ACTIVE_KEY // "blue" or "green"
};

const currentKey = KEYS[KEYS.active];
```

### API Key Rotation Schedule

Recommended rotation frequencies:

| Environment                  | Rotation Frequency       | Reason                          |
| ---------------------------- | ------------------------ | ------------------------------- |
| **Production**               | Every 90 days            | Compliance, security            |
| **Staging**                  | Every 180 days           | Lower risk, less traffic        |
| **Development**              | Annually                 | Minimal risk                    |
| **CI/CD**                    | Every 90 days            | Automated, can't leak via human |
| **Third-party integrations** | When integration changes | Control scope                   |

## Rotation Strategy 2: Secrets

### What It Is

Secrets (API keys, passwords, tokens) stored in KnoxCall support **versioning**.

**Example:**

```text theme={"dark"}
Secret: stripe-api-key
- v1: sk_live_old123... (created Jan 1)
- v2: sk_live_new789... (created Mar 15) ← active version
```

**Rotating secrets** = Add new version, which becomes active immediately

### When to Rotate

**Rotate secrets when:**

* ✅ Secret exposed or leaked
* ✅ Third-party service rotates their keys (e.g., Stripe rotates automatically)
* ✅ Regular compliance schedule (90 days)
* ✅ Employee with access leaves
* ✅ Moving from test to production

**Benefits:**

* Zero-downtime rotation (new version immediately active)
* Version history for rollback
* Audit trail of when secrets changed

### How to Rotate Secrets

#### Step 1: Generate New Secret (Third-Party)

First, generate the new credential in the external service:

**Stripe example:**

1. Log in to Stripe Dashboard
2. Navigate to **Developers** → **API keys**
3. Click **Create secret key**
4. Name it: "KnoxCall Production Key 2025"
5. **Copy the key**: `sk_live_new789xyz456abc123def789ghi012jkl`

**Do NOT revoke old key yet!**

#### Step 2: Add New Version in KnoxCall

1. Navigate to **Secrets**
2. Click the secret (e.g., "stripe-prod-key")
3. Click **Add New Version**
4. Paste new secret value:
   ```text theme={"dark"}
   sk_live_new789xyz456abc123def789ghi012jkl
   ```
5. Click **Save**

**What happens:**

* New version (v2) becomes active immediately
* All routes using `{{secret:stripe-prod-key}}` now use v2
* Old version (v1) preserved for rollback

#### Step 3: Test

Immediately test routes that use this secret:

1. Navigate to **Routes** → Find routes using this secret
2. Click **Test Route**
3. Send test request
4. Verify backend receives new secret (check backend logs)

If errors occur:

1. Navigate to **Secrets** → secret detail
2. Click **Rollback to v1**
3. Investigate issue

#### Step 4: Monitor

Watch logs for 15-30 minutes:

```text theme={"dark"}
✓ Route: stripe-payments - Success (200)
✓ Route: stripe-refunds - Success (200)
✓ Route: stripe-customers - Success (200)
```

If all successful, rotation is complete!

#### Step 5: Revoke Old Secret (Third-Party)

After 24-48 hours of successful usage:

1. Log in to third-party service (Stripe)
2. Revoke old key: `sk_live_old123...`
3. Confirm

Old key no longer works, even if someone has it.

<Note>
  **Grace period**: Keep old secret active in third-party service for 24-48 hours. This gives time to catch any missed integrations before revoking.
</Note>

### Secret Rotation Patterns

#### Pattern 1: Immediate Rotation (Security Incident)

**Scenario:** Secret leaked publicly (e.g., committed to GitHub)

**Steps:**

1. Add new version in KnoxCall (0-downtime)
2. Test immediately (\< 5 minutes)
3. Revoke old secret in third-party **immediately** (don't wait)

**Downtime:** \~5 minutes (time to test)

#### Pattern 2: Scheduled Rotation (Compliance)

**Scenario:** Quarterly 90-day rotation policy

**Steps:**

1. Schedule rotation date (e.g., first Monday of quarter)
2. Generate new credentials 1 day before
3. Add new version in KnoxCall
4. Monitor for 48 hours
5. Revoke old credentials

**Downtime:** 0 minutes

#### Pattern 3: Rolling Window Rotation

**Scenario:** Multiple secrets to rotate

**Strategy:** Stagger rotations over days/weeks

**Example schedule:**

```text theme={"dark"}
Week 1: Rotate Stripe key
Week 2: Rotate SendGrid key
Week 3: Rotate Twilio key
Week 4: Rotate database password
```

**Benefits:**

* Spread risk (don't rotate everything at once)
* Easier to identify issues
* Less overwhelming for team

### Secret Rotation Checklist

Before rotating a secret:

* [ ] **Identify all routes** using the secret
* [ ] **Generate new credential** in third-party service
* [ ] **Add new version** in KnoxCall
* [ ] **Test all affected routes** (Route Tester)
* [ ] **Monitor logs** for 15-30 minutes
* [ ] **Document rotation** (when, why, who)
* [ ] **Schedule revocation** of old secret (24-48 hours)
* [ ] **Verify old secret revoked** in third-party service

## Rotation Strategy 3: Routes

### What It Is

**Duplicating a route** creates a copy with the same configuration.

**Use cases:**

* 🔄 Create v2 of API while keeping v1 alive
* 🌍 Duplicate production route for staging
* 🧪 Test configuration changes without affecting live route
* 📦 Clone route to different tenant

### How to Duplicate Routes

#### Method: Duplicate via UI

Currently, routes can be duplicated by creating a new route and manually copying configuration.

**Steps:**

1. Navigate to **Routes** → Click route to duplicate
2. Note all configuration:
   * Target URL
   * Headers
   * Body injection
   * Secrets used
   * Assigned clients
3. Click **Create Route**
4. Enter new route name (e.g., `stripe-payments-v2`)
5. Fill in same configuration
6. Save

#### Method: Duplicate via API

Coming soon: API endpoint for route duplication.

### Route Migration Pattern

**Scenario:** Migrating API from v1 to v2

**Steps:**

**1. Duplicate route:**

```text theme={"dark"}
Old: stripe-payments (points to api.stripe.com/v1)
New: stripe-payments-v2 (points to api.stripe.com/v2)
```

**2. Test new route:**

* Assign test clients only
* Send test requests
* Verify responses

**3. Gradual migration:**

```javascript theme={"dark"}
// Use route based on client
const route = client.useV2 ? "stripe-payments-v2" : "stripe-payments";

fetch(`https://x9y8z7w6.DunderMifflin.knoxcall.com/charges`, {
  headers: {
    "x-knoxcall-route": route
  }
});
```

**4. Monitor both routes:**

* V1 requests declining
* V2 requests increasing

**5. Deprecate v1:**
When v1 requests = 0 for 7 days:

* Disable v1 route
* Monitor for errors
* Delete v1 route after 30 days

## Rotation Strategy 4: Environments

### What It Is

**Environment duplication** copies environment override configuration.

**Use cases:**

* 📋 Clone production config to create new environment
* 🧪 Test environment changes before deploying
* 🌍 Create region-specific environments (US, EU)

### How to Duplicate Environments

**Step 1: Navigate to Route**

1. Go to **Routes** → Click route
2. Switch to **Environments** tab

**Step 2: Duplicate Environment**

1. Select environment to copy (e.g., "production")
2. Click **⋯** (more options)
3. Select **Duplicate Environment**
4. Enter new environment name: `production-eu`
5. Click **Duplicate**

**What's copied:**

* ✅ Target URL override
* ✅ Header injection overrides
* ✅ Body injection overrides
* ✅ Rate limit overrides
* ✅ Signature settings overrides

**What's NOT copied:**

* ❌ Assigned clients (you assign separately)

**Step 3: Modify Duplicated Environment**

Update the new environment for your needs:

```text theme={"dark"}
production-eu:
- Target URL: https://api-eu.service.com (changed)
- Headers: (copied from production)
- Secrets: (same as production)
```

**Step 4: Assign Clients**

Assign clients to new environment:

1. Go to **Clients** tab
2. Select `production-eu`
3. Assign appropriate clients (e.g., EU servers)

### Environment Migration Pattern

**Scenario:** Migrating to new backend infrastructure

**Steps:**

**1. Duplicate environment:**

```text theme={"dark"}
production → production-new-infra
```

**2. Update target URL:**

```text theme={"dark"}
Old: https://legacy-api.example.com
New: https://new-infra-api.example.com
```

**3. Assign canary client:**

Assign 1 client to test:

```text theme={"dark"}
Client: production-server-01
Environment: production-new-infra
```

**4. Send requests with environment header:**

```bash theme={"dark"}
curl -X GET "https://x9y8z7w6.DunderMifflin.knoxcall.com/api/users" \
  -H "x-knoxcall-key: YOUR_KEY" \
  -H "x-knoxcall-route: users" \
  -H "x-knoxcall-environment: production-new-infra"
```

**5. Monitor:**

* Check logs for errors
* Compare response times
* Verify data integrity

**6. Gradual rollout:**

Assign more clients over days/weeks:

```text theme={"dark"}
Week 1: 1 client (1%)
Week 2: 10 clients (10%)
Week 3: 50 clients (50%)
Week 4: All clients (100%)
```

**7. Make default:**

Once all clients migrated:

1. Update base route configuration to point to new infra
2. Delete `production-new-infra` environment (no longer needed)

## Best Practices

### 1. Document Rotation Events

**Keep a rotation log:**

| Date       | Asset           | Old Value        | New Value         | Reason                    | By    |
| ---------- | --------------- | ---------------- | ----------------- | ------------------------- | ----- |
| 2025-01-15 | stripe-prod-key | sk\_live\_old... | sk\_live\_new\... | Scheduled 90-day rotation | John  |
| 2025-02-01 | API Key (prod)  | tk\_abc...       | tk\_def...        | Key leaked in logs        | Sarah |

**Benefits:**

* Audit compliance
* Troubleshooting
* Team awareness

### 2. Test Before Revoking

**Always:**
✅ Add new credential
✅ Test thoroughly
✅ Monitor for 24-48 hours
✅ Then revoke old credential

**Never:**
❌ Revoke old credential immediately
❌ Skip testing
❌ Assume it works

### 3. Use Grace Periods

After adding new credential, keep old one active:

* **Low risk**: 24 hours
* **Medium risk**: 48 hours
* **High risk (leaked)**: 1 hour minimum

Allows time to catch missed integrations.

### 4. Automate Where Possible

**Automatable:**

* Scheduled secret rotation (every 90 days)
* API key rotation (every 90 days)
* Monitoring for rotation events

**Not automatable (require human judgment):**

* Route duplication (business logic)

### 5. Use Separate Keys Per Environment

**Good:**

```text theme={"dark"}
API Keys:
- Production Key A (prod servers)
- Production Key B (prod CI/CD)
- Staging Key (staging servers)
- Development Key (dev laptops)
```

**Bad:**

```text theme={"dark"}
API Keys:
- One key for everything ❌
```

If one key is compromised, you only revoke that one.

## Rotation Frequency Recommendations

| Asset                      | Frequency      | Notes                      |
| -------------------------- | -------------- | -------------------------- |
| **API Keys (prod)**        | Every 90 days  | Compliance standard        |
| **API Keys (staging)**     | Every 180 days | Lower risk                 |
| **Secrets (payment APIs)** | Every 90 days  | High sensitivity           |
| **Secrets (internal)**     | Every 180 days | Lower sensitivity          |
| **Routes**                 | As needed      | For versioning             |
| **Environments**           | As needed      | For infrastructure changes |

## Troubleshooting

### Issue: "Rotation caused downtime"

**Cause:** Revoked old credential before new one was deployed everywhere

**Prevention:**

1. Always deploy new credential first
2. Monitor for 24-48 hours
3. Then revoke old

### Issue: "Can't find which routes use a secret"

**Solution:**

1. Navigate to **Secrets** → Click secret
2. View **Used By Routes** section
3. Lists all routes using this secret

### Issue: "Rotated secret but old one still being used"

**Cause:** Route has method-specific config using old secret

**Check:**

1. Route → **Method Configs** tab
2. Check each HTTP method
3. Some methods might override with old secret

**Fix:** Update method-specific configs

### Issue: "Rolled subdomain but clients still using old URL"

**Cause:** Hardcoded URLs, not environment variables

**Prevention:**

```javascript theme={"dark"}
// ❌ Don't hardcode
const url = "https://a1b2c3d4.DunderMifflin.knoxcall.com";

// ✅ Use environment variable
const url = process.env.KNOXCALL_BASE_URL;
```

## Related Features

* **Secret Versioning**: Manage multiple versions of secrets
* **API Key Management**: Create and revoke keys
* **Environment tab**: Per-environment configuration
* **Audit Logs**: Track all configuration changes

## Next Steps

<CardGroup cols={2}>
  <Card title="Secret Management" icon="key" href="/getting-started/first-secret">
    Learn about secret versioning
  </Card>

  <Card title="Audit Logs" icon="clipboard-list" href="/monitoring/audit-logs">
    Track rotation events
  </Card>

  <Card title="API Keys" icon="shield-halved" href="/getting-started/quick-start-guide">
    Manage authentication keys
  </Card>

  <Card title="Environments" icon="layer-group" href="/getting-started/first-environment">
    Configure environment overrides
  </Card>
</CardGroup>

***

<CardGroup cols={2}>
  <Card title="📊 Statistics" icon="chart-line">
    * **Level**: intermediate to advanced
    * **Time**: 20 minutes
  </Card>

  <Card title="🏷️ Tags" icon="tags">
    `security`, `rotation`, `compliance`, `credentials`, `zero-downtime`
  </Card>
</CardGroup>
