# Envelope encryption for OAuth tokens on Workers

URL: https://eoxlabs.dev/engineering/envelope-encryption-oauth-tokens
Last updated: 2026-11-26
Published: 2026-11-26
Publisher: EOXLABS (https://eoxlabs.dev)

Section: [Engineering notes](https://eoxlabs.dev/engineering)

EOXLABS stores third-party OAuth tokens with envelope encryption. Each token is encrypted under its own AES-GCM data key, and that data key is encrypted under a key-encryption key held as a Worker secret. A leaked database yields only ciphertext, a ciphertext moved to another tenant's row fails to decrypt, and rotation rewraps keys, not tokens.

## Why do OAuth tokens need more than encryption at rest?

A refresh token for a customer's mail, calendar or accounting system is a standing credential into a system you don't control. [RFC 6749, section 10.4](https://www.rfc-editor.org/rfc/rfc6749#section-10.4) says refresh tokens "MUST be kept confidential in transit and storage".

Disk-level encryption doesn't meet that bar on its own. It protects the storage medium, and it's transparent to queries, so anyone who can run a `SELECT`, read a backup export or exploit an injection flaw sees plaintext. Application-level encryption makes the database hold only ciphertext, and moves the question to who holds the key.

## How are the keys split?

| Key | Encrypts | Lives in | Lifetime |
|---|---|---|---|
| Data key (DEK), AES-256-GCM | One token record for one connection | The same row, wrapped by the KEK | Replaced on every write, including each refresh |
| Key-encryption key (KEK), AES-256-GCM | Data keys only, never tokens | A Worker secret bound to one token-broker Worker | Rotated on a schedule; old versions kept until no row references them |

A fresh data key per write is not ceremony. [NIST SP 800-38D](https://csrc.nist.gov/pubs/sp/800/38/d/final), section 8.3, limits a key used with random 96-bit IVs to 2^32 encryptions. A per-write DEK encrypts once. The KEK is used once per token write, so we track wraps per KEK version and rotate well before the limit.

## How do you use AES-GCM correctly in WebCrypto?

Workers implement the WebCrypto API, and Cloudflare's [Web Crypto reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) lists AES-GCM for encryption, key import and key wrapping. Three parameters decide whether it's safe, all defined in [MDN's AesGcmParams](https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams):

- **`iv`**: 12 random bytes from `crypto.getRandomValues`, new for every operation. MDN is blunt: never reuse an IV with the same key. Appendix A of NIST SP 800-38D explains why: a repeated IV likely lets an adversary recover the authentication subkey and forge ciphertexts.
- **`additionalData`**: authenticated but not encrypted. Decryption throws unless the same bytes are supplied. We bind the tenant ID, provider and connection ID, encoded as a JSON array so no delimiter can be smuggled inside an ID.
- **`tagLength`**: defaults to 128 bits. We leave it there.

## What does the code look like?

```ts
const te = new TextEncoder();
const gcm = (iv: Uint8Array, aad: Uint8Array) => ({ name: "AES-GCM", iv, additionalData: aad });

export type Sealed = {
  v: 1; kekId: string; iv: Uint8Array; ct: ArrayBuffer; dekIv: Uint8Array; wrappedDek: ArrayBuffer;
};

export const context = (tenantId: string, provider: string, connectionId: string) =>
  te.encode(JSON.stringify(["oauth-token/v1", tenantId, provider, connectionId]));

export async function loadKek(base64: string): Promise<CryptoKey> {
  const raw = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
  return crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]);
}

export async function seal(token: string, kekId: string, kek: CryptoKey, aad: Uint8Array): Promise<Sealed> {
  const dekBytes = crypto.getRandomValues(new Uint8Array(32));
  const dek = await crypto.subtle.importKey("raw", dekBytes, "AES-GCM", false, ["encrypt"]);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const dekIv = crypto.getRandomValues(new Uint8Array(12));
  const ct = await crypto.subtle.encrypt(gcm(iv, aad), dek, te.encode(token));
  const wrappedDek = await crypto.subtle.encrypt(gcm(dekIv, aad), kek, dekBytes);
  dekBytes.fill(0); // best effort; JavaScript makes no promises about copies
  return { v: 1, kekId, iv, ct, dekIv, wrappedDek };
}

export async function open(s: Sealed, keks: Map<string, CryptoKey>, aad: Uint8Array): Promise<string> {
  const kek = keks.get(s.kekId);
  if (!kek) throw new Error(`unknown KEK version ${s.kekId}`);
  const dekBytes = await crypto.subtle.decrypt(gcm(s.dekIv, aad), kek, s.wrappedDek);
  const dek = await crypto.subtle.importKey("raw", dekBytes, "AES-GCM", false, ["decrypt"]);
  return new TextDecoder().decode(await crypto.subtle.decrypt(gcm(s.iv, aad), dek, s.ct));
}
```

The DEK is wrapped with a plain AES-GCM `encrypt` call. [`SubtleCrypto.wrapKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/wrapKey) with AES-GCM parameters does the same job and requires an extractable DEK. We chose `encrypt` so the same `gcm()` helper and the same associated data cover both layers, which keeps a swapped wrapped key as detectable as a swapped token.

## Where should the key-encryption key live?

| Option | How the Worker reads it | Scope | Status |
|---|---|---|---|
| [Workers secret](https://developers.cloudflare.com/workers/configuration/secrets/) | `env.TOKEN_KEK_V2`, a string | One Worker; the value isn't shown again after it's set | The per-Worker default |
| [Secrets Store](https://developers.cloudflare.com/secrets-store/integrations/workers/) | `await env.TOKEN_KEK.get()` through a Secrets Store binding | Account level; separate Admin and Deployer roles | [Open beta](https://developers.cloudflare.com/secrets-store/) as of this note |
| External key management service | A network call per unwrap | Held by that service | Adds latency and a dependency to every token read |

We default to a Workers secret bound to exactly one Worker, the token broker. Other Workers reach it through a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/), which Cloudflare documents as callable without a publicly reachable URL. The broker exposes `getAccessToken(tenantId, connectionId)` and nothing that returns a refresh token. Fewer Workers holding the KEK means fewer deploys that can leak it.

Secrets Store suits a KEK that several Workers genuinely need, and its role split separates who creates a secret from who binds it. We'd move to it once it leaves beta and the design calls for sharing.

## How do you rotate the KEK without re-encrypting every token?

Every row stores its `kekId`. Rotation runs in four steps:

1. Add `TOKEN_KEK_V3` as a new secret and deploy with both versions loaded.
2. Switch new writes to V3. Reads still find V2 through the `kekId`.
3. Rewrap: for each V2 row, decrypt the 32-byte DEK with V2 and encrypt it under V3 with a fresh IV and the same associated data. The token ciphertext and its IV don't change. A sweep scheduled with [Durable Object alarms](https://eoxlabs.dev/engineering/durable-object-alarms) does this in small batches, and reads rewrap opportunistically.
4. Delete V2 once a count of rows with `kekId = 'v2'` returns zero.

Data keys rotate themselves, because every token refresh writes a new DEK.

Rotation is not incident response. If a KEK leaks, an attacker with that KEK and an old database snapshot can still unwrap old DEKs. A suspected leak means revoking tokens at each provider and asking users to reconnect, not only rotating.

## What does this protect against, and what doesn't it?

| Threat | Protected? | Why |
|---|---|---|
| Leaked database backup or export | Yes | Ciphertext and wrapped keys only; the KEK is never in the database |
| Injection that reads the tokens table | Yes, unless the attacker also runs code in the broker | Reading rows doesn't yield the KEK |
| Write access used to move a ciphertext to another tenant's row | Detected | The associated data no longer matches, so decryption throws |
| Compromised code or dependency inside the broker | No | It holds the KEK; keep its dependency list short |
| An account administrator who can deploy Workers | No | Deployed code can read bound secrets; limit who holds that role |
| Tokens written to logs, traces or error messages | No | Encryption at rest can't help; redact at the source |

## What would we do differently?

We'd version the envelope from the first row: the `v` field and the `oauth-token/v1` label cost nothing and make a future format change routine.

We'd serialize refreshes per connection from the start. Some authorization servers apply refresh token rotation, described in [RFC 9700, section 4.14](https://www.rfc-editor.org/rfc/rfc9700#section-4.14): each refresh returns a new refresh token and invalidates the previous one. Two Workers refreshing the same connection at once means one presents an invalidated token, and the authorization server may then revoke the active one. Routing refresh through one Durable Object per connection gives the in-flight refresh one home: concurrent callers await the same promise instead of starting a second refresh. The object's single thread alone isn't enough, because other requests can enter while the provider call is awaited.

We'd resist caching unwrapped data keys per tenant to save two AES operations. It widens what one memory disclosure exposes and complicates rotation, for a cost that is small next to the provider call that usually follows.

The surrounding practice is covered under [security and resilience](https://eoxlabs.dev/capabilities/security-resilience) and on our [Cloudflare Workers stack page](https://eoxlabs.dev/stack/cloudflare-workers). For why the broker runs at the edge rather than in one region, see [edge-native vs edge-deployed](https://eoxlabs.dev/engineering/edge-native-vs-edge-deployed), and for the rest of the series, our [engineering notes](https://eoxlabs.dev/engineering).

— DL

## Related

- [Security and Resilience](https://eoxlabs.dev/capabilities/security-resilience): Zero trust access, envelope encryption with rotatable keys, backups locked against deletion, and recovery rehearsed in advance: how EOXLABS designs systems to withstand a breach.
- [Cloudflare Workers](https://eoxlabs.dev/stack/cloudflare-workers): Cloudflare Workers is the request layer of EOXLABS systems, and this page covers how EOXLABS structures a Worker, the limits behind each design choice, and where a Worker is the wrong tool.
- [Durable Object alarms instead of background jobs](https://eoxlabs.dev/engineering/durable-object-alarms): Replacing process-model background jobs with Durable Object alarms, with verified semantics, a TypeScript scheduler that runs many jobs on one alarm, idempotency rules and a decision list.
- [Edge-native vs edge-deployed](https://eoxlabs.dev/engineering/edge-native-vs-edge-deployed): What separates an edge-native system from one that only runs its handlers at the edge, with a comparison table and the architecture smells that give an edge-deployed system away.
- [Envelope Encryption](https://eoxlabs.dev/glossary/envelope-encryption): Envelope encryption protects data with a per-item data key, then wraps that data key with a separate key encryption key, so a stolen database yields only ciphertext and wrapped keys.

## More engineering notes

- [Why sub-50 ms is a defensible edge claim and sub-2 ms is not](https://eoxlabs.dev/engineering/sub-50ms-edge-latency)
- [Designing backups that survive ransomware](https://eoxlabs.dev/engineering/ransomware-resilient-backups)
- [Migrating a monolith to the edge without downtime](https://eoxlabs.dev/engineering/monolith-to-edge-migration)
