> ## 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.

# Creating Secrets

> Step-by-step guide to creating and managing encrypted secrets in KnoxCall. Learn about string secrets, OAuth2, and best practices.

# Creating Secrets

Learn how to create and manage encrypted secrets for API keys, passwords, and tokens.

***

## What You'll Learn

* How to create string secrets (API keys, passwords)
* How to create OAuth2 secrets (auto-refreshing tokens)
* Naming conventions and best practices
* Secret versioning and rotation

***

## Creating a String Secret

String secrets are the most common type - used for API keys, passwords, tokens, and any sensitive text value.

### Step 1: Navigate to Secrets

1. Click **Secrets** in the sidebar
2. The Secrets page shows a **two-level hierarchy**: collections at the top level, secrets within each collection. Click a collection to see its secrets. Secrets not assigned to a collection appear under **Uncollected**.
3. Click **Add Secret** (at the top level or within a collection)

### Step 2: Choose Secret Type

Select **String Secret**

*For OAuth2 tokens, see [OAuth2 Secrets](#creating-oauth2-secrets) below.*

### Step 3: Enter Secret Details

#### Secret Name (Required)

The name you'll use to reference this secret in routes.

**Format:** lowercase with underscores

**Good examples:**

```text theme={"dark"}
stripe_prod_key
sendgrid_api_key
database_password
github_webhook_secret
twilio_auth_token
printnode_api_key
```

**Bad examples:**

```text theme={"dark"}
secret1              (not descriptive)
StripeKey            (use lowercase)
stripe-key           (use underscores, not hyphens)
key                  (too generic)
```

**Why naming matters:**
You'll reference secrets in templates like this:

```text theme={"dark"}
{{secret:stripe_prod_key}}
```

Clear names make your configurations self-documenting.

#### Secret Value (Required)

The actual sensitive value to encrypt and store.

**Examples:**

```text theme={"dark"}
API keys:      sk_live_abc123xyz789...
Passwords:     MySecureP@ssw0rd!2024
Tokens:        eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
URLs:          postgres://user:pass@host:5432/db
Webhook secrets: whsec_abc123xyz789...
```

**Important:**

* Copy from source carefully (no extra spaces!)
* Value is encrypted immediately after saving
* You won't be able to view plaintext again

### Step 4: Save

Click **Create Secret**

✅ **Done!** Your secret is now:

* Encrypted with AES-256-GCM
* Stored securely
* Ready to use in routes

⚠️ **Important:** The plaintext value is now gone from the UI. If you need to reference it later, you'll need to get it from the original source.

***

## Creating OAuth2 Secrets

OAuth2 secrets are special - they **automatically refresh** access tokens when they expire.

### When to Use OAuth2 Secrets

Use OAuth2 for services that require token refresh:

* ✅ Google APIs (Gmail, Drive, Sheets)
* ✅ Microsoft Graph (Office 365, OneDrive)
* ✅ Shopify
* ✅ HubSpot
* ✅ Salesforce
* ✅ Slack

### Step 1: Choose OAuth2 Secret Type

When creating secret, select **OAuth2 Secret**

### Step 2: Fill in OAuth2 Details

#### Secret Name

```text theme={"dark"}
google_oauth_token
shopify_access_token
hubspot_oauth_creds
```

#### OAuth2 Configuration

**Client ID:**

```text theme={"dark"}
123456789.apps.googleusercontent.com
```

*From your OAuth app settings*

**Client Secret:**

```text theme={"dark"}
GOCSPX-abc123xyz789...
```

*From your OAuth app settings*

**Provider:**

```text theme={"dark"}
google
```

*One of the supported OAuth2 providers (e.g. `google`, `microsoft`)*

**Scopes (optional):**

```text theme={"dark"}
https://www.googleapis.com/auth/gmail.readonly
```

*Defaults to the provider's default scopes if omitted*

**Auth URL / Token URL (optional):**

```text theme={"dark"}
https://oauth2.googleapis.com/token
```

*Override the provider's authorize/token endpoints; defaults are filled in for you*

<Note>
  You do **not** paste in an access token, refresh token, or expiry at creation time. KnoxCall stores only your OAuth app's `client_id`/`client_secret` (or an `mtls_certificate_id`) plus the endpoint config. The secret is created with `connection_status: "not_connected"`, and the response includes a minted `redirect_uri`.
</Note>

### Step 3: Save and Connect

Click **Create Secret**. The response includes a `redirect_uri` on the fixed `oauth.knoxcall.com/callback` host.

✅ **Complete the OAuth flow** to obtain tokens. Visit the authorization URL, approve access at the provider, and the provider redirects back to the minted `redirect_uri`. KnoxCall then exchanges the code for tokens and flips `connection_status` to connected. Once connected, KnoxCall will:

* Monitor token expiry
* Refresh before expiration using the stored refresh token
* Update the access token automatically
* Log refresh events

***

## Secret Naming Conventions

### Pattern: `{service}_{environment}_{type}`

**Examples:**

#### By Service

```text theme={"dark"}
stripe_prod_key
stripe_staging_key
sendgrid_prod_api_key
twilio_dev_token
```

#### By Environment

```text theme={"dark"}
database_prod_password
database_staging_password
database_dev_password
```

#### By Purpose

```text theme={"dark"}
webhook_secret_github
webhook_secret_shopify
api_key_printnode
api_key_openai
```

### Multiple Secrets for Same Service

When you need different keys for different purposes:

```text theme={"dark"}
stripe_prod_live_key          (live transactions)
stripe_prod_restricted_key    (read-only)
stripe_test_key               (testing)
```

***

## Environment-Specific Secrets

Create separate secrets for each environment:

### Production Secrets

```text theme={"dark"}
Name: stripe_prod_key
Value: sk_live_abc123...
Description: Stripe production - live transactions
Tags: production, payment, critical
```

### Staging Secrets

```text theme={"dark"}
Name: stripe_staging_key
Value: sk_test_xyz789...
Description: Stripe staging - test mode
Tags: staging, payment
```

### Development Secrets

```text theme={"dark"}
Name: stripe_dev_key
Value: sk_test_dev123...
Description: Stripe development - local testing
Tags: development, payment
```

**Then use in route overrides:**

```text theme={"dark"}
Production environment:
  Header: Authorization: Bearer {{secret:stripe_prod_key}}

Staging environment:
  Header: Authorization: Bearer {{secret:stripe_staging_key}}

Development environment:
  Header: Authorization: Bearer {{secret:stripe_dev_key}}
```

***

## Best Practices

### ✅ Do

**1. Use descriptive names**

```text theme={"dark"}
✅ stripe_prod_live_key
❌ key1
```

**2. Document with descriptions**

```text theme={"dark"}
✅ "Stripe production API key - rotate every 90 days - expires Mar 2025"
❌ (no description)
```

**3. Separate by environment**

```text theme={"dark"}
✅ stripe_prod_key, stripe_staging_key, stripe_dev_key
❌ stripe_key (used everywhere)
```

**4. Tag appropriately**

```text theme={"dark"}
✅ Tags: production, payment, critical
❌ (no tags)
```

**5. Version for rotation**

```text theme={"dark"}
Secret v1: stripe_prod_key (old)
Secret v2: stripe_prod_key (new, rotated)
```

**6. Use OAuth2 type when applicable**

```text theme={"dark"}
✅ OAuth2 secret for Google APIs (auto-refresh)
❌ String secret that expires (manual update needed)
```

### ❌ Don't

**1. Don't commit secrets to git**

```text theme={"dark"}
❌ .env file in repository
✅ Store in KnoxCall secrets
```

**2. Don't reuse across environments**

```text theme={"dark"}
❌ Same key for prod and dev
✅ Separate keys per environment
```

**3. Don't use generic names**

```text theme={"dark"}
❌ api_key, secret, password
✅ stripe_prod_key, database_prod_password
```

**4. Don't skip descriptions**

```text theme={"dark"}
❌ No description
✅ "Production database - rotate quarterly - last rotated Jan 2025"
```

**5. Don't expose test keys in production**

```text theme={"dark"}
❌ stripe_test_key in production environment
✅ stripe_prod_key in production
```

***

## Secret Security

### How Secrets Are Stored

1. **Encryption:** AES-256-GCM (military-grade)
2. **Envelope encryption:** Each secret has unique encryption key
3. **Master key:** Stored separately, never exposed
4. **Integrity:** SHA-256 checksum verification

### Who Can Access Secrets

**View encrypted secrets:**

* All team members with access

**View plaintext values:**

* **Nobody** - not even admins!
* Plaintext only visible when:
  * Initially created (one-time viewing)
  * Decrypted server-side during requests
  * Never shown in logs or UI

**Use secrets in routes:**

* Anyone with route edit permissions

### Secret Transmission

When requests use secrets:

1. Client makes request to KnoxCall
2. KnoxCall loads route config
3. Sees `{{secret:stripe_key}}` template
4. Decrypts secret **server-side**
5. Injects into request to backend
6. Client never sees plaintext!

***

## Common Use Cases

### 1. Payment APIs

**Stripe:**

```text theme={"dark"}
Name: stripe_prod_key
Value: sk_live_abc123xyz789...
Description: Stripe production secret key
```

**Usage in route:**

```json theme={"dark"}
{
  "Authorization": "Bearer {{secret:stripe_prod_key}}"
}
```

### 2. Email Services

**SendGrid:**

```text theme={"dark"}
Name: sendgrid_api_key
Value: SG.abc123xyz789...
Description: SendGrid API key for transactional emails
```

**Usage:**

```json theme={"dark"}
{
  "Authorization": "Bearer {{secret:sendgrid_api_key}}"
}
```

### 3. SMS Services

**Twilio:**

```text theme={"dark"}
Name: twilio_auth_token
Value: abc123xyz789...
Description: Twilio auth token for SMS
```

**Usage:**

```json theme={"dark"}
{
  "Authorization": "Basic {{secret:twilio_auth_token}}"
}
```

### 4. Database Credentials

**PostgreSQL:**

```text theme={"dark"}
Name: database_prod_url
Value: postgres://user:pass@host:5432/db
Description: Production database connection string
```

**Usage in body:**

```json theme={"dark"}
{
  "connection_string": "{{secret:database_prod_url}}"
}
```

### 5. Webhook Secrets

**GitHub:**

```text theme={"dark"}
Name: github_webhook_secret
Value: whsec_abc123...
Description: GitHub webhook verification secret
```

**Usage:**

```json theme={"dark"}
{
  "X-Hub-Signature": "{{secret:github_webhook_secret}}"
}
```

### 6. Printing Services

**PrintNode:**

```text theme={"dark"}
Name: printnode_api_key
Value: abc123xyz789...
Description: PrintNode API key for cloud printing
```

**Usage:**

```json theme={"dark"}
{
  "Authorization": "Basic {{secret:printnode_api_key}}"
}
```

***

## Secret Versioning

KnoxCall tracks secret versions for safe rotation.

### Creating a New Version

When rotating a secret:

1. Go to **Secrets**
2. Click on secret name
3. Click **Add New Version**
4. Enter new value
5. Save

**What happens:**

* New version becomes active immediately
* Old version preserved (for rollback)
* All routes using secret now use new value
* Zero downtime!

### Viewing Version History

1. Click secret name
2. Go to **Version History** tab
3. See all versions with timestamps
4. Can rollback if needed

***

## Troubleshooting

### Secret Not Found in Templates

**Error:** `Secret 'stripe_key' not found`

**Causes:**

* Typo in secret name
* Secret was deleted
* Wrong syntax in template

**Solution:**

1. Check secret exists: **Resources** → **Secrets**
2. Verify spelling matches exactly
3. Check template syntax: `{{secret:name}}`

### Cannot View Secret Value

**Symptom:** Want to see what the value is.

**Cause:** Plaintext never shown after creation (security feature).

**Solution:**

* Get value from original source
* Or create new version with known value

### Secret Not Injecting

**Symptom:** Backend receives literal `{{secret:stripe_key}}` text.

**Causes:**

* Template syntax error
* Secret doesn't exist
* Injection disabled

**Debug:**

1. Check logs - what was actually sent?
2. Verify template syntax is correct
3. Test secret exists and name matches
4. Verify inject headers is enabled on route

***

## Quick Reference

| Task                     | Steps                                     |
| ------------------------ | ----------------------------------------- |
| **Create string secret** | Resources → Secrets → Add Secret → String |
| **Create OAuth2 secret** | Resources → Secrets → Add Secret → OAuth2 |
| **Rotate secret**        | Click secret → Add New Version            |
| **View versions**        | Click secret → Version History            |
| **Delete secret**        | Click secret → Delete (⚠️ permanent)      |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Using Secrets" icon="wand-magic-sparkles" href="/essentials/secrets/using-secrets">
    How to inject secrets into routes
  </Card>

  <Card title="Secrets Overview" icon="shield" href="/essentials/secrets/secrets-overview">
    Complete secrets guide
  </Card>

  <Card title="OAuth2 Flow" icon="key" href="/security/oauth2-flow">
    Set up OAuth2 auto-refresh
  </Card>

  <Card title="Rotation Strategies" icon="rotate" href="/security/rotation-strategies">
    Best practices for rotating secrets
  </Card>
</CardGroup>

***

<Warning>
  **Security Reminder:** Never commit secrets to git, share via email, or hardcode in applications. Always use KnoxCall's encrypted secret storage.
</Warning>
