Records Architecture decision

ADR-007

Per-User Encryption Keys with Crypto-Shredding for GDPR

Accepted Decided 2026-03-01 Source file

Context

GDPR's "right to erasure" requires that a user's data can be effectively deleted on request. In a chat application, a user's messages are spread across many streams and rooms. Finding and deleting every message is slow, error-prone, and may leave fragments in backups or replicas.

An alternative is crypto-shredding: encrypt each user's messages with a key unique to them, and delete the key when erasure is requested. The encrypted data becomes unreadable without the key, achieving the same practical effect as deletion.

Decision

Use per-user encryption with crypto-shredding:

  • Algorithm: New message bodies use a compact versioned envelope: XChaCha20-Poly1305 encrypts the body with the author's active message-body DEK epoch. Each per-user DEK is generated by Chatto, wrapped through the KMS boundary, stored as a protobuf UserDataEncryptionKey wrapped-key record in RUNTIME_STATE under an opaque content-key ref, and recorded for audit as a durable UserDEKGeneratedEvent containing only refs and wrapping metadata. Legacy bodies encrypted directly with the per-user ChaCha20-Poly1305 key remain readable.
  • AAD binding: New body-event-carried envelopes authenticate the message event context (message event ID, body event ID, room ID, author ID, message-body DEK epoch, and message-body event type) as Additional Authenticated Data for the body ciphertext so ciphertext cannot be replayed into a different message or body-event context without detection.
  • Attachment descriptions: Each attachment description is a separate XChaCha20-Poly1305 envelope in MessageBody. It uses the original author's active message-body DEK. Domain-separated AAD binds the room ID, canonical message event ID, body event ID, author ID, attachment asset ID, DEK epoch, and attachment-description purpose. A body edit decrypts descriptions only for the operation and encrypts them again for the replacement body event. Description plaintext is not stored in asset events, runtime state, snapshots, realtime event payloads, logs, or search indexes.
  • Durable user PII encryption: Durable user events encrypt login, display name, and verified email fields with the user's active user-PII DEK epoch. User and mentionable projections decrypt login/email values transiently while applying events to derive normalised in-memory lookup digests, then discard the plaintext; they retain encrypted envelopes and AAD context for read hydration. Display names are decrypted only while hydrating a read. No user-PII lookup digest is persisted in EVT, so crypto-shredding does not leave an additional enumerable representation behind. Message bodies and user PII use separate purpose-scoped DEKs, each with its own per-purpose epoch counter. Legacy KV user records are imported by emitting encrypted user events; if an older boot already wrote plaintext user EVT facts, the migration appends encrypted repair facts from the legacy KV source.
  • Per-user keys: Each user has their own KEK. New built-in KMS KEKs are stored as protobuf UserKeyEncryptionKey records behind opaque kek.* KMS key refs in the dedicated ENCRYPTION_KEYS KV bucket, while raw 32-byte kek.* records remain readable for compatibility with older exports. Raw user.* records are legacy direct-key compatibility only. App-owned wrapped DEK records live in RUNTIME_STATE under opaque dek.* content-key refs. DEK events record the content-key ref and the key ref used to wrap it.
  • Key isolation: The encryption key bucket is explicitly excluded from chatto backup. Backups include encrypted data plus app-owned wrapped DEK records, but not the KEKs needed to unwrap those DEKs.
  • Erasure = durable request + idempotent deletion + completion: Before destructive work starts, Chatto appends UserKeyShreddingRequestedEvent at the exact user-aggregate OCC tail. A concurrent user-key mutation conflicts and retries the request. Account deletion aborts if that durable request cannot be established. The request is the logical privacy boundary: user, authentication, content-key, mention, room timeline, thread, search, and realtime projections immediately fail closed, and lazy DEK generation refuses the user. The request path and shared chatto-user-key-shredding-v1 durable EVT consumer reconstruct the deletion set from the user's immutable UserDEKGeneratedEvent facts and surviving runtime DEK records. They shred every discovered wrapping key before deleting any DEK record, so a retry can rediscover current wrapping refs until the KEK phase succeeds. UserKeyShreddedEvent records physical completion and remains the logical boundary for histories written before the request event existed.
  • Message-owned assets are deleted explicitly: Attachments and derivative assets are not encrypted with the user's message key. Account deletion therefore records AssetDeletedEvents for message-owned asset graphs and removes their backing bytes separately from crypto-shredding. User avatar assets follow the same durable delete-event path during account deletion.
  • KMS boundary: KEK creation, content-key wrapping/unwrapping, and KEK shredding (createKey, wrapContentKey, unwrapContentKey, shredKey) go through the dedicated internal/kms interface keyed by opaque KMS refs rather than user IDs. DEK record create/load/shred is application-owned RUNTIME_STATE storage, keeping wrapped DEKs available locally and in normal data backups while still making individual DEK refs crypto-shreddable. The default KMS implementation is in-process and backed by ENCRYPTION_KEYS; it can be extracted to a standalone service for high-security deployments. Legacy direct-key body decrypt is the only remaining raw-KEK compatibility path.

Process cache for unwrapped DEKs (amended 2026-12-01)

Each server process keeps unwrapped DEKs in memory, and can use each one for 5 minutes after it read the key from the shared store. A cache hit does not extend this lifetime. The cache applies to all uses of DEKs: user PII, message bodies, attachment descriptions, and encrypted bot credentials.

Before this amendment, a process kept an unwrapped DEK only for one request. Each unwrap needs two reads of the shared store: the wrapped DEK record and the KEK. A read of N user profiles thus needed 2N reads for each request. On a server with 10,000 accounts, each name search took approximately 200 ms, and a client that loads the complete user directory caused 20,000 reads.

The amendment separates three things.

Logical revocation. The content-key projection of a process records each user whose keys have a shredding request or a completed shredding. A snapshot restore keeps this record. The DEK resolver asks the projection before it reads a cache and again before it returns a key. For such a user it returns no key, from a cache or from the shared store, also while the physical keys still exist. Thus a caller that holds key coordinates from before the request, such as a detached profile snapshot, gets no key after the process applied the request. A key that the resolver returned before that time stays with its caller for that one operation. This rule is stricter than the behavior before the amendment, where such a caller could unwrap the key until the physical deletion.

Cache usability. A process that has not yet applied the shredding request does not know of the revocation. It can use a cached key for a maximum of 5 minutes after it unwrapped the key. After that time, it reads the shared store again and fails closed when the keys are deleted. Before the amendment, such a process failed closed at the physical deletion. A failed unwrap is not stored, so each later read tries the shared store again.

Memory retention. When the projection applies a shredding fact, the process overwrites and removes that user's keys in the cache. The process that deletes the physical keys does the same. A background component removes expired keys one time each minute, so the bytes of an expired key stay in memory for a maximum of one more minute. A caller gets a copy of a key, which the cache does not control.

The cache holds a maximum of 200,000 keys. When it is full, new keys are not stored until a removal makes space, and reads use the shared store.

The lifetime is a constant and not a configuration setting. A deployment that moves the KMS to a separate service must account for it: the KMS does not see the reads that the cache answers.

Consequences

  • KMS read consistency: Built-in KMS key reads and existence checks use jetstreamutil.KeyValue.GetAnyReplica. Any replica can answer a read, so KEK reads stay fast. The KMS reads a missing key again through the stream leader. Thus a follower that lags cannot hide a key that an earlier write created. This replaces the earlier bounded retries after 10, 25, and 50 ms. Reads never recreate keys. A successful read can still come from a follower that has not applied a later deletion. See issue #2438 and ADR-056.

  • Fast, recoverable erasure: The durable request tombstones projected content before irreversible deletion. Its user aggregate provides a narrow immutable index of DEK coordinates, while KEK-first deletion preserves surviving runtime DEK records until their current wrapping refs have been shredded. This lets at-least-once workers safely resume after any partial attempt without copying storage coordinates into the request event. Shredding the user's DEK refs or wrapping-key refs renders their encrypted message bodies and durable PII unreadable. Individual message deletion can also securely delete the body payload event, removing ciphertext while preserving public post/edit/retract facts.

  • Rollout requires a homogeneous writer fleet: Binaries predating UserKeyShreddingRequestedEvent do not recognise its immediate fail-closed boundary and still use the older delete-before-event command. Operators must finish upgrading all request-serving replicas before allowing account deletion on the new version, and must not roll back to an older binary after new request facts have been written.

  • Backup safety: Since KEKs are excluded from backups, restoring a normal backup does not restore the ability to read deleted users' messages. Wrapped DEK records are backed up in RUNTIME_STATE, but are unusable without their KEK.

  • Attachment cleanup is separate from crypto-shredding: Binary assets need explicit delete events and storage cleanup because key deletion alone does not affect stored bytes or signed asset locators. Projections stop resolving deleted assets before backing bytes are removed.

  • Content indexing is an explicit privileged cache: Encrypted message bodies are not directly searchable. An optional full-text provider may decrypt them into a local, rebuildable derived index, but that index becomes privileged plaintext-derived data outside the crypto-shredded event payload. It must be excluded from normal backups, remove retracted and shredded content, and rebuild into fresh storage when deletion guarantees require eliminating residual index segments. Disabling or deleting the index must not affect reconstruction of domain state from EVT.

  • Key loss is permanent: If the KMS loses a user's key (outside of intentional deletion), their messages are gone. The KV bucket must be treated as critical data.

  • Per-message overhead: Legacy bodies carry one nonce and Poly1305 tag. V2 message bodies carry a body nonce, Poly1305 tag, compact content_key_epoch payload field referencing the author's message-body DEK, and for body-event-carried bodies the body_event_id used for AAD binding. Wrapped per-user DEK material is stored once per user, purpose, and epoch in app-owned RUNTIME_STATE storage; EVT keeps only the auditable content-key ref and wrapping-key ref.

  • Description overhead follows described attachments: Each non-empty attachment description carries its own nonce, authentication tag, envelope metadata, and ciphertext. Because the body-event ID is authenticated, every replacement MessageBodyEvent must encrypt all retained descriptions again. Author-key shredding and secure deletion then cover the descriptions through the same lifecycle as message text.

  • Durable PII is crypto-shreddable: New login, display name, and verified-email event payloads become unrecoverable after the user's KEK is destroyed. In-memory projections retain ciphertext and lookup digests rather than decrypted values, and remove user-owned lookup entries when the shred event is applied. Cold projection replay skips encrypted PII whose lookup digest can no longer be derived after key destruction.

  • Future extensibility: The KMS interface, wrapping-key refs, and wrapping metadata on DEK events can be adapted to external key management (HashiCorp Vault, AWS KMS, HSM) without moving wrapped DEK storage into the external KMS API. If we later add per-message DEKs in a separate key store that is excluded from data backups and has acceptable index/retention characteristics, individual message deletion can shred that per-message DEK instead of securely deleting the MessageBodyEvent payload. That future shape would keep encrypted body payload events immutable while still making deleted bodies unrecoverable, bringing the design closer to strict event-sourcing practice.

Records that name this record

Esc