TL;DR

  • OAuth tokens for external services were stored with one app-wide Fernet key. Fernet cannot bind a ciphertext to a context, so moving a ciphertext to another row still decrypts.
  • Each write now creates an AES-256-GCM data key and wraps it with a Cloud KMS key. Both encryptions carry AAD describing the row.
  • With providers that rotate refresh tokens, losing KMS after a refresh means the new tokens cannot be saved and the connection is lost. The data key is wrapped before the provider is asked to refresh.

Tokens for external services live in the database

Members can connect to external MCP servers with OAuth. The access token and refresh token are stored per workspace, connection, and member, and read back when an agent calls a tool.

Until now, one app-wide Fernet key encrypted them. The key came from an environment variable.

That design breaks in two situations.

  • A ciphertext moves to another row: Fernet does not check which row a ciphertext belongs to. If a bug or a manual SQL statement copies member A’s ciphertext into member B’s row, B’s connection calls the external service with A’s token.
  • Both the key and the database leak: with the environment variable and a database dump, every token is readable.

Options I considered

  • Keep Fernet and derive a key per row: deriving keys from the context with HKDF prevents row mix-ups. The root key still sits in an environment variable.
  • Encrypt directly with Cloud KMS: tokens are far below the KMS limit (64 KiB), so Encrypt with AAD would work. But KMS can only be called after the token exists. That becomes the refresh problem below.
  • Envelope encryption: encrypt the token with a locally generated data key and wrap only that key with KMS.

Google Cloud documentation recommends, for envelope encryption:

  • generate data keys locally
  • use a new data key for every write
  • use AES-256-GCM

I followed that. The key-encryption key never leaves KMS, and access to it is controlled with IAM.

Put the row’s context in the AAD

AES-GCM AAD is extra data that is not encrypted, but decryption fails if it changes. It records where the ciphertext is meant to be used.

def aad(self, kind):  # kind is "access" or "refresh"
    fields = ("token/v2", environment, self.workspace_id,
              self.connection_id, self.user_id, kind)
    return json.dumps(fields, separators=(",", ":")).encode()

The same AAD is used in two places:

  • when the data key encrypts the token (AES-GCM)
  • when KMS Encrypt wraps the data key (additionalAuthenticatedData)

On read, the AAD is rebuilt from the row being read. A ciphertext moved from another row makes KMS refuse to unwrap the data key, and reading stops there. Swapping the access and refresh tokens fails too, because the kind is part of the AAD.

The AAD is the tuple encoded as a JSON array. Plain string concatenation would let someone shift a separator and produce the same bytes from a different tuple.

The stored format is v2.<connection ID>.<wrapped data key>.<nonce and ciphertext>. Without the v2. prefix, the value is read as legacy Fernet. Where a KMS key is configured, each write replaces it with the new format.

When KMS is down right after the refresh token rotates

The OAuth security best current practice (RFC 9700) requires refresh tokens for public clients to be either sender-constrained or rotated. With rotation, every refresh returns a new refresh token and invalidates the old one. Plenty of providers rotate.

With the wrong order, this happens:

  1. Ask the provider to refresh and receive new tokens. The old refresh token is now invalid.
  2. Call KMS to encrypt them for storage. KMS is briefly unavailable.
  3. The new tokens cannot be saved. The database holds only the old, invalid refresh token.

The member has to connect again.

With envelope encryption, a data key can be created without knowing the token. So the data key is created and wrapped by KMS before the provider is called. If KMS is unavailable, the refresh request is never sent.

After the provider replies, only local AES-GCM is needed. A key service outage can no longer stop the save. The first authorization code exchange follows the same order.

Direct KMS encryption cannot be ordered this way, because KMS cannot be called until the token is known. This ordering is why envelope encryption fits even for small values.

Every read calls KMS

Each read unwraps the data key with KMS Decrypt. If KMS is unavailable, no token is returned. There is no data key cache, so every read costs one extra round trip to KMS.

In raw strength, Fernet and AES-GCM are both fine. The difference was whether a ciphertext knows where it belongs, and in which order the external key service is called.