Gateway · BYOK credential routing
Per-tenant BYOK credential storage and routing — TenantCredentialStore contract, Postgres / Redis / external-secret-manager adapters, and CredentialRoutingMiddleware.
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. The
@pleach/gateway/byok/* subpaths (this page) ship storage and routing.
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.
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
Three reference adapters ship on separate subpaths, so you only take the optional peer dependency of the one you use.
Postgres
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:
npx @pleach/core schema --apply --with @pleach/gatewayEncryption 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 (aBuffer, 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
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
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.
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
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.
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
type OnMissingPolicy = "fallback" | "throw""fallback"(default) uses the platformfallbackKey, so BYOK is opportunistic."throw"throwsCredentialMissingError, 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:
const resolve = createCredentialRoutingMiddleware({ store })
// No fallback: tenants without a credential get CredentialMissingError.CredentialMissingError
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
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
- 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
apiKeyvalues. Logging the fingerprint fromfingerprintByokKeyis 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.
Public surface
TenantCredentialStorecontract andCredentialRoutingMiddlewarefactory, 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
Cost events
Per-call cost emission with BYOK attribution (`byokActive`, `byokKeyHash`).
Migration from `@pleach/core`
When to introduce the gateway and how the BYOK middleware fits an existing createPleachRuntime setup.
`@pleach/gateway` overview
GatewayClient, cost events, family-strict cascade, transport seam.
@pleach/mcp
The `@pleach/mcp` package — Model Context Protocol server for `@pleach/core` runtimes over stdio, SSE, Streamable HTTP, or WebSocket, with fail-closed multi-tenant routing.
Gateway · Rate limiting
Rate-limit contract and the in-process reference adapter — RateLimiter interface, fixed-window InMemoryLimiter, and what you provide for multi-node deployments.