# Gateway · BYOK credential routing (/docs/gateway/byok)



A tenant supplies their own provider key for one or more model
families, and the gateway routes that family's calls through it rather
than a platform-owned key. This page covers where the key lives between
calls and the middleware that resolves it at route time.

`@pleach/gateway/byok` ships the header-only
[fingerprint helper](/docs/gateway#byok-is-header-only). The
`@pleach/gateway/byok/*` subpaths (this page) ship storage and routing.

## `TenantCredentialStore` [#tenantcredentialstore]

Adapters implement this contract against a backing store.
`GatewayClient.route()` never reads it. Your host passes the store to
`createCredentialRoutingMiddleware` and calls the resolver it returns
before dispatch.

```typescript
import type { CredentialSlot } from "@pleach/gateway"

interface TenantCredential {
  readonly family: CredentialSlot
  readonly apiKey: string
  readonly baseURL?: string
  readonly metadata?: Record<string, unknown>
}

interface TenantCredentialStore {
  get(
    tenantId: string,
    family: CredentialSlot,
  ): Promise<TenantCredential | null>

  put(
    tenantId: string,
    family: CredentialSlot,
    credential: TenantCredential,
  ): Promise<void>

  list(tenantId: string): Promise<TenantCredential[]>
}
```

A tenant has one entry per provider family, keyed by
`(tenantId, family)`. The store treats `apiKey` as opaque.

`CredentialSlot` is a `ProviderFamily` or an aggregator slot. The only
aggregator slot today is `"openrouter"`, one key that routes many model
families. `CREDENTIAL_AGGREGATOR_SLOTS` lists the aggregator slots, and
`isCredentialAggregatorSlot()` tells the two kinds apart. The stored
column is still named `family`, so existing rows need no migration.

**Breaking for implementers.** A caller that passes a `ProviderFamily`
compiles unchanged. A `get`/`put`, resolver, writer or middleware typed
`(tenantId, family: ProviderFamily) => …` no longer satisfies the
contract: widen the parameter to `CredentialSlot`. Code that reads
`family` (also on `CredentialMissingError`) needs an `"openrouter"`
case, or a narrowing with `isCredentialAggregatorSlot()` first.

`get()` returns `null` when a credential is missing. The middleware
then uses the platform fallback, unless you set `onMissing: "throw"`
(see below).

## Reference adapters [#reference-adapters]

Three reference adapters ship on separate subpaths, so you only take
the optional peer dependency of the one you use.

### Postgres [#postgres]

```typescript
import { Pool } from "pg"
import { createAesGcmCredentialCipher } from "@pleach/gateway"
import { createPostgresCredentialStore } from "@pleach/gateway/byok/adapters/postgres"

const pool = new Pool({ connectionString: process.env.DATABASE_URL })
const cipher = createAesGcmCredentialCipher({ key: process.env.BYOK_KEK! })
const store = createPostgresCredentialStore({ pool, cipher })
```

The table ships in the `@pleach/gateway` schema tier. Apply it with the
schema CLI:

```bash
npx @pleach/core schema --apply --with @pleach/gateway
```

**Encryption at rest.** The Postgres store requires a
`CredentialCipher`; constructing it without one throws rather than
storing plaintext. Two ciphers ship from the `@pleach/gateway` root:

* `createAesGcmCredentialCipher({ key })` encrypts under one 32-byte
  key you supply (a `Buffer`, or a hex or base64 string).
* `createEnvelopeCredentialCipher({ kms })` uses your KMS client, so
  the master key never leaves the KMS.

Rows written before encryption was added stay readable. Re-`put()`ing
a credential encrypts it, and the schema stops new plaintext rows.

**`tableName` is validated at construction.** The adapter throws a
`TypeError` unless it matches `/^[A-Za-z_][A-Za-z0-9_]*$/`, before the
first query runs.

The adapter is uncached. If route-time latency matters, wrap it in a
short-TTL in-memory cache (60 seconds, for example).

### Redis [#redis]

```typescript
import Redis from "ioredis"
import { createRedisCredentialStore } from "@pleach/gateway/byok/adapters/redis"

const client = new Redis(process.env.REDIS_URL)
const store = createRedisCredentialStore({
  client,
  keyPrefix: "pleach:byok:prod",
})
```

Works with `ioredis` and `node-redis` v4+. Listing a tenant's
credentials doesn't scan the keyspace, so it works on managed Redis
(Upstash, ElastiCache cluster mode), which refuses `KEYS`.

Encryption at rest is the host's job: the adapter stores plain JSON.
Pair it with Redis TLS, ACLs and an encrypted volume, and don't run it
against an unencrypted Redis on a shared network.

### External secret manager [#external-secret-manager]

A vendor-neutral facade for AWS Secrets Manager, HashiCorp Vault, GCP
Secret Manager, Azure Key Vault, Doppler or 1Password Connect. You wrap
your SDK in a resolver callback.

```typescript
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager"
import { createExternalSecretManagerStore } from "@pleach/gateway/byok/adapters/external-secret-manager"

const sm = new SecretsManagerClient({ region: "us-east-1" })

const store = createExternalSecretManagerStore({
  resolver: async (tenantId, family) => {
    const SecretId = `pleach/byok/${tenantId}/${family}`
    try {
      const { SecretString } = await sm.send(new GetSecretValueCommand({ SecretId }))
      return SecretString ? JSON.parse(SecretString) : null
    } catch (err: any) {
      if (err.name === "ResourceNotFoundException") return null
      throw err
    }
  },
})
```

**`put` / `list` are optional.** If you omit the callback, calling
`put()` or `list()` throws `ExternalSecretManagerNotImplementedError`
instead of silently doing nothing.

**Caching is yours.** The adapter calls `resolver()` on every `get()`.
Cache it if your vendor charges per API call.

## `CredentialRoutingMiddleware` [#credentialroutingmiddleware]

The middleware is a resolver your host calls before it dispatches the
request. `GatewayClient.route()` doesn't call it. The resolver looks
up the tenant's credential for the resolved family. If found, it
returns `{ apiKey, baseURL, metadata, byokActive: true }` for the
routing layer to attach as headers. If not, it falls back to the
platform key and returns `byokActive: false`.

```typescript
import { createCredentialRoutingMiddleware } from "@pleach/gateway"
import { createPostgresCredentialStore } from "@pleach/gateway/byok/adapters/postgres"

// cipher: see the Postgres adapter above. The store throws a
// TypeError without one.
const store = createPostgresCredentialStore({ pool, cipher })

const resolve = createCredentialRoutingMiddleware({
  store,
  fallbackKey: process.env.PLATFORM_ANTHROPIC_KEY,
  onMissing: "fallback",
})

const { apiKey, baseURL, byokActive } = await resolve("tenant-acme", "anthropic")
```

### `onMissing` policy [#onmissing-policy]

```typescript
type OnMissingPolicy = "fallback" | "throw"
```

* `"fallback"` (default) uses the platform `fallbackKey`, so BYOK is
  opportunistic.
* `"throw"` throws `CredentialMissingError`, so tenants without a
  registered credential can't route. Use it when every call must be
  attributable to a tenant-owned key.

Without a `fallbackKey`, the policy is always `"throw"`, whatever
`onMissing` says:

```typescript
const resolve = createCredentialRoutingMiddleware({ store })
// No fallback: tenants without a credential get CredentialMissingError.
```

### `CredentialMissingError` [#credentialmissingerror]

```typescript
class CredentialMissingError extends Error {
  readonly tenantId: string
  readonly family: CredentialSlot
}
```

Surfaced to the host as a structured rejection. Handle it in your
tenant-onboarding flow ("you haven't registered a key for this
provider").

## Where governance lives [#where-governance-lives]

The middleware applies no policy. Governance gates (`allowedFamilies`,
plan-tier caps, per-tenant rate limits) live at the `GatewayClient`
layer and run before it. This layer only decides where the key for a
`(tenant, family)` pair comes from.

## Security posture [#security-posture]

* Encrypt stored credentials at rest: Postgres column encryption, Redis
  TLS plus ACL plus an encrypted volume, or an external secret manager.
  The gateway doesn't enforce this.
* Adapters must not log raw `apiKey` values. Logging the fingerprint
  from `fingerprintByokKey` is fine; logging the plain key is a
  security incident.
* The store returns the raw key for routing-time use only. The routing
  layer handles it header-only, per the
  [BYOK header-only contract](/docs/gateway#byok-is-header-only).

## Public surface [#public-surface]

* `TenantCredentialStore` contract and `CredentialRoutingMiddleware`
  factory, from `@pleach/gateway`.
* Postgres adapter: `@pleach/gateway/byok/adapters/postgres`.
* Redis adapter: `@pleach/gateway/byok/adapters/redis`.
* External secret manager facade:
  `@pleach/gateway/byok/adapters/external-secret-manager`.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Cost events" href="/docs/gateway/cost-events" description="Per-call cost emission with BYOK attribution (`byokActive`, `byokKeyHash`)." />

  <Card title="Migration from `@pleach/core`" href="/docs/gateway/migration-from-core" description="When to introduce the gateway and how the BYOK middleware fits an existing createPleachRuntime setup." />

  <Card title="`@pleach/gateway` overview" href="/docs/gateway" description="GatewayClient, cost events, family-strict cascade, transport seam." />
</Cards>
