// Engineering notes

Envelope encryption for OAuth tokens on Workers

Published · ·Last updated ·

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 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?

KeyEncryptsLives inLifetime
Data key (DEK), AES-256-GCMOne token record for one connectionThe same row, wrapped by the KEKReplaced on every write, including each refresh
Key-encryption key (KEK), AES-256-GCMData keys only, never tokensA Worker secret bound to one token-broker WorkerRotated on a schedule; old versions kept until no row references them

A fresh data key per write is not ceremony. NIST SP 800-38D, 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 lists AES-GCM for encryption, key import and key wrapping. Three parameters decide whether it's safe, all defined in MDN's 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?

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() 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?

OptionHow the Worker reads itScopeStatus
Workers secretenv.TOKEN_KEK_V2, a stringOne Worker; the value isn't shown again after it's setThe per-Worker default
Secrets Storeawait env.TOKEN_KEK.get() through a Secrets Store bindingAccount level; separate Admin and Deployer rolesOpen beta as of this note
External key management serviceA network call per unwrapHeld by that serviceAdds 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, 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 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?

ThreatProtected?Why
Leaked database backup or exportYesCiphertext and wrapped keys only; the KEK is never in the database
Injection that reads the tokens tableYes, unless the attacker also runs code in the brokerReading rows doesn't yield the KEK
Write access used to move a ciphertext to another tenant's rowDetectedThe associated data no longer matches, so decryption throws
Compromised code or dependency inside the brokerNoIt holds the KEK; keep its dependency list short
An account administrator who can deploy WorkersNoDeployed code can read bound secrets; limit who holds that role
Tokens written to logs, traces or error messagesNoEncryption 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: 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 and on our Cloudflare Workers stack page. For why the broker runs at the edge rather than in one region, see edge-native vs edge-deployed, and for the rest of the series, our engineering notes.

— DL

→

Related

+

More engineering notes

Have a system that can’t go dark?

Start a project →