Architecture
Tenant data encryption
This document outlines the data-encryption architecture so module owners can wire it into MikroORM, custom-entity definitions, and the admin UI without breaking isomorphism. It follows the classic KMS + DEK split and keeps multi-tenant isolation as the primary constraint.
Goals
- Encrypt tenant-scoped data at rest using AES-GCM with per-tenant data-encryption keys (DEKs).
- Let admins choose which system and custom-entity fields are encrypted; store these maps in the database and cache them aggressively.
- Make encryption transparent to MikroORM reads/writes and CRUD factories while remaining opt-out when Vault/KMS is down.
- Keep auth workable when email is encrypted by storing an email hash alongside the ciphertext for lookup during login.
Components
- Env toggle –
TENANT_DATA_ENCRYPTION(defaults toyes). When false, encryption hooks no-op but validation still runs so the system can be toggled on later. - KMS service (DI) –
kmsServiceresolves tenant keys. Default backend: HashiCorp Vault (per-tenant secret path). Interface supports future providers.getTenantDek(tenantId)→ resolvestenant_key_<tenantId>from KMS; caches in-memory with TTL + background refresh.createTenantDek(tenantId)→ generates random 256-bit key, stores attenant_key_<tenantId>, returns material.isHealthy()→ signals whether the provider is reachable; encryption hooks log + warn when unhealthy.
- DEK cache – in-memory (per node) with LRU/TTL; optional Redis cache layer for multi-node coherence.
- Encryption helper – AES-GCM with random IV (12 bytes) and auth tag; payload format
base64(iv):base64(ciphertext):base64(tag):v1. Includesencrypt(value, dek)anddecrypt(payload, dek)plus deterministichashForLookup(value)(SHA-256 hex) for email lookups. - Encryption map registry – persisted configuration telling the runtime which entity fields are encrypted.
- Stored in DB as part of the Entities module (per tenant/org) so admins can target system entities and custom entities alike.
- Cached in the same cache layer as DEKs; invalidated when definitions change.
- MikroORM hooks – per-entity interceptor that:
- On
beforeCreate/beforeUpdate: finds mapped fields and replaces values with ciphertext (plus storing the clear-text hash where configured, e.g.,users.email_hash). - On
afterFind: decrypts mapped fields using the tenant DEK; falls back silently when encryption is disabled or KMS is unhealthy.
- On
- Auth adjustments –
userstable gainsemail_hash(indexed) so login can query by hash even whenemailis encrypted. - Tenant bootstrap – tenant creation flow generates and stores a DEK via
kmsService.createTenantDekwith thetenant_key_<tenantId>prefix. - Observability – warning rows (or audit logs) emitted when KMS is unavailable; set
TENANT_DATA_ENCRYPTION_DEBUG=yesto log map evaluation plus Vault KMS reads/writes. - Fallback path – if Vault is unhealthy, the runtime uses a derived-key KMS only when a dedicated data-encryption fallback secret is provided (
TENANT_DATA_ENCRYPTION_FALLBACK_KEY, then legacyTENANT_DATA_ENCRYPTION_KEY).AUTH_SECRETandNEXTAUTH_SECRETare never used for tenant data encryption. The dev default fallback is available only withALLOW_DERIVED_KMS_FALLBACK=true; otherwise missing KMS configuration becomes a noop KMS.
Environment variables
TENANT_DATA_ENCRYPTION– master toggle (yesby default). Disables hooks when set tonobut keeps validation in place.TENANT_DATA_ENCRYPTION_DEBUG–yesto surface map evaluation decisions, Vault cache hits/misses, and fallback selection in logs.VAULT_ADDR,VAULT_TOKEN– required for the HashiCorp Vault KMS provider.VAULT_KV_PATH– KV v2 mount for tenant keys; defaults tosecret/data.VAULT_REQUEST_TIMEOUT_MS,VAULT_RECOVERY_COOLDOWN_MS– request time limit and recovery interval after a transient failure. The defaults are 1,000 ms and 30,000 ms, respectively.- Fallback secrets (used when Vault is down or missing):
TENANT_DATA_ENCRYPTION_FALLBACK_KEY, then legacyTENANT_DATA_ENCRYPTION_KEY. Auth/session secrets are intentionally excluded. The built-in dev fallback requiresALLOW_DERIVED_KMS_FALLBACK=true; production without a dedicated fallback secret falls back to the noop KMS.
Application KMS drivers
Apps register KMS driver packages in src/providers/kms.ts (kmsDrivers), alongside the cache and queue registrations, and select one with OM_KMS_DRIVER=<id>. The host contract lives in @open-mercato/shared/lib/encryption/kms-driver (defineKmsDriver, defineKmsDriverRegistration). Both app templates ship the default @open-mercato/kms-driver-vault registration (open-mercato/vault).
- Selector unset (default) – nothing changes:
TENANT_DATA_ENCRYPTION,VAULT_*and the fallback secrets select Vault, the derived key or no encryption exactly as before. The legacy path uses the same extracted Vault client through theHashicorpVaultKmsServicecompatibility export. - Selector set – the web app, workers, scheduler, setup, key-consuming CLI commands and the encryption preflight resolve the registration, check its static
package.jsonmetadata (contract version, id, edition) before importing driver code, validate its settings, start it withinOM_KMS_DRIVER_STARTUP_TIMEOUT_MSand run its readiness probe. Any failure stops the process instead of falling back.createKmsService()and thekmsServiceDI key return the same initialized handle. - Explicit-driver safety – a selected driver returns
nullonly for a proven absent key. Timeouts, denied access or invalid keys throwKMS_UNAVAILABLE, so a protected write fails rather than landing as plaintext or under another key./api/healthzreports503while the selected driver's bounded readiness probe fails; the response shape is unchanged. - Editions – drivers declaring
edition: "enterprise"require Enterprise activation (OM_ENABLE_ENTERPRISE_MODULES). Theopen-mercato/id namespace is reserved for@open-mercato/*packages.
Packaging Vault changes no VAULT_* setting, key path or stored key, and requires no key rotation or database migration. The opt-in OpenBao package and the Enterprise cloud drivers follow the KMS driver specification as separate releases.
Data flow
Write path
- API/CRUD normalises payload, then MikroORM entity hooks run.
- Hook loads the encryption map for
(tenantId, entity)from cache; cache miss fetches from DB. - Hook resolves the tenant DEK from
kmsService(cached). - For each mapped field:
- Compute and set hash column if defined (e.g.,
email_hash). - Encrypt value via AES-GCM and replace the ORM field with ciphertext envelope.
- Compute and set hash column if defined (e.g.,
- ORM persists ciphertext; hashes remain plaintext for lookups and deduplication.
Read path
- MikroORM loads entities (ciphertext in encrypted columns).
- Hook uses map + tenant DEK to decrypt mapped fields.
- API/CRUD receives hydrated plaintext while the DB keeps ciphertext.
Use findWithDecryption, findOneWithDecryption, or findAndCountWithDecryption
from @open-mercato/shared/lib/encryption/find for encrypted entities, passing the
trusted caller's tenant and organization scope. A plain ORM read can rehydrate an
entity already present in the identity map with ciphertext without firing its
one-time onLoad hook again. The explicit helpers repeat decryption after the
read, so results do not depend on whether an earlier query populated the entity.
Keep the query's authorization filters: decryption does not grant record access.
Decryption is at-rest protection, not a read-side access control
An encryption map decides how a value is stored, never who may read it. Decryption runs automatically on load, so any caller authorised to read the record receives every mapped field in the clear. Restricting who may see a field is the job of an ACL feature on the route or page that exposes it; the map protects the value against database access, backups and dumps.
Decryption is bound to the caller's tenant
The decrypt scope is resolved by resolveDecryptScope
(@open-mercato/shared/lib/encryption/decryptScope), shared by BasicQueryEngine,
HybridQueryEngine and the ORM EncryptionSubscriber:
- The row's own
tenant_idis used only when the caller asserted none, or when it agrees with the tenant the caller asserted. - When the caller asserted a tenant and the row contradicts it, the row is refused: it is
returned untouched (ciphertext) and never decrypted with the foreign tenant's DEK. Both engines
emit one aggregated
warnper query naming the entity, the refusal count and the mismatching tenant ids — ids only, never field values. organization_idis deliberately not compared: organisations inside a tenant share the tenant DEK, so an org mismatch does not change which key is used.
The guard exists so a scoping bug anywhere else in the stack degrades to ciphertext rather than being amplified into a cross-tenant plaintext disclosure. A refusal always means something upstream returned a row it should not have — treat the warning as a bug report about that query, not about encryption.
Where the refusal cannot engage
The comparison needs both ids, so two shapes degrade instead of refusing. Neither produces cross-tenant plaintext, but neither emits the warning either — do not read a silent query as a verified one:
- No caller tenant. A
find*WithDecryptioncall that passes no scope gives the ORM path nothing to bind against, so the row's own tenant wins exactly as it did before this guard existed. Pass{ tenantId }to those helpers to get the binding. - No row tenant. A table without a
tenant_idcolumn has no row tenant, so the caller's own tenant is used — which is the strongest form of the binding, since a foreign row could then only be attempted with the caller's DEK. A narrowfieldsprojection does not land here: both query engines forcetenant_idinto the projection when the entity has an encryption map, then strip it back out of the response, so the decision is always made against the real row tenant. - Relations of a tenant-less parent. The ORM path walks loaded relations with the caller's
scope, but a relation reached through a parent that has no
tenant_idof its own (a join row such asUserRole) is not refused against it — such a row may legitimately link entities of several tenants. Entities hydrated by the samefind*WithDecryptionread are still bound individually, because the subscriber'sonLoadruns under the caller's scope. - Entities already in the identity map. An entity loaded and decrypted earlier in the same
EntityManagerby a read that asserted no tenant is returned as it is; the binding applies to the read that loads an entity, not to every later read that touches it.
On the ORM path the binding engages during hydration: find*WithDecryption runs em.find under
the caller's scope, so the subscriber's onLoad refuses a foreign-tenant entity before anything
else can decrypt it, and the refusals of one read are reported in a single warning.
A caller that does not want plaintext at all sets QueryOptions.decryptEncryptedFields: false,
which skips the DEK lookup entirely. It defaults to true, preserving existing behaviour.
Querying encrypted columns
Decryption happens on load, not on filter. A where clause is passed to the database as
written, so a plaintext predicate against an encrypted column is compared to ciphertext:
- It matches nothing, and it does not raise.
{ title: 'Renewal' },{ title: { $in: [...] } }andem.count()with such a filter return empty/zero rather than an error. Guard clauses and idempotency checks built this way silently no-op once encryption is enabled — and keep working in local dev withTENANT_DATA_ENCRYPTION=no, which is how the mistake survives review. - For exact lookups, declare a hash column. Add
hashFieldto the field's rule in the module's encryption map and filter on the hash (this is howusers.email_hashsupports login). - Otherwise read, then compare in memory.
findWithDecryption/findOneWithDecryption/findAndCountWithDecryption(@open-mercato/shared/lib/encryption/find) hydrate plaintext, so the comparison happens on decrypted values. Scope the query by tenant/organization first so the set stays bounded. - Sorting has the same limitation — see the encrypted-sort helpers in the
customersmodule for the established pattern.
Text search: $ilike never matches an encrypted column
This is the same failure as above, but it is worth calling out on its own because it is the one teams keep rediscovering (issue #5051). A hand-written substring search:
// Returns an empty page the moment `title` is added to an encryption map.
const rows = await findWithDecryption(em, MailMessage, { title: { $ilike: `%${term}%` } })
compares a plaintext pattern against ciphertext. There is no error and no partial result — just an empty page that looks exactly like "nothing matched", so the feature ships green and the regression surfaces months later in production.
Use the token index instead. search_tokens stores hashes of the plaintext, so it keeps
matching after encryption is enabled:
import { findEntityIdsBySearchTokens } from '@open-mercato/shared/lib/search/tokenLookup'
const match = await findEntityIdsBySearchTokens({
db: em.getKysely<any>(),
entityType: E.customers.customer_entity,
query: term,
fields: ['display_name', 'primary_email'],
scope: { tenantId, organizationId },
})
if (match.matched && match.ids.length) filters.$or.push({ id: { $in: match.ids } })
matched: false means the index was not consulted (blank query, OM_SEARCH_ENABLED=off, or a
term too short to tokenize) — not "nothing matched". Keep the caller's own predicate in that case.
Queries that go through the query engine get this routing automatically. Raw em.find and
Kysely list routes must wire it themselves; where that is not yet done, #2990 tracks the migration.
Both paths now warn instead of failing silently. Outside production, a $like / $ilike /
$re filter passed to the …WithDecryption helpers that targets a property registered in an
encryption map logs a warning naming the entity, the column and the remedy. The query engines log
the equivalent warning when their own ILIKE fallback would run against an encrypted column. The
check is limited to non-production because resolving the encryption map costs an uncached read;
it is a development aid, not a runtime guard, so a search that only breaks under a
production-only encryption map still needs a test.
Failure modes
- KMS unreachable – encryption layer logs a warning and (per requirements) continues without encryption; maps are still evaluated so we can re-enable later.
- Decryption error – returns masked values or null plus a warning log; never throws raw crypto errors to clients.
Encryption maps
- Stored in Entities module tables alongside custom entity metadata; schema:
entity_id,fields[],tenant_id,organization_id,is_active,created_at. - UI: extend Custom Entities editor to allow selecting system entities (e.g.,
users,sales.order,sales.quote,customer_addresses) and ticking which fields should be encrypted. - Defaults (seeded):
users.email, customer addresses (address fields), sales orders/quotes snapshot + personal data, customer notes, order/quote notes. - Each map entry also marks optional hash columns for deterministic lookup (e.g.,
users.email_hash). - Scope resolution – an organization-scoped read or write resolves the most specific map for
(entity, tenant, organization), falling back to the tenant-wide and then the global map. At the tenant-wide scope (organizationId = null) the field list is the union of the resolved map and every organization-scoped map of that entity/tenant, so a field any organization encrypts is treated as ciphertext everywhere.getEncryptedFieldNames,encryptEntityPayload, anddecryptEntityPayloadall resolve the same set — a field declared only on an organization map is therefore still encrypted on a tenant-wide write and decrypted on a tenant-wide read.
Key management
Custom entity document storage honors the effective custom field definition's encrypted flag before writing JSONB. Bare keys and cf:/cf_ aliases use the same field policy; arrays encrypt entries individually. Existing ciphertext is authenticated before reuse, and unavailable keys fail the document write. Custom-storage queries resolve each row's own tenant and organization, preserve field kinds during decryption, and evaluate encrypted comparisons and ordering before pagination. When OM_ENCRYPTED_SORT_MAX_ROWS is configured, queries that exceed it fail explicitly instead of returning partial matches.
mercato entities rotate-encryption-key includes these documents independently of ORM maps. Without an old key it backfills plaintext; with an old key it reseals decryptable ciphertext and retains values already encrypted with the current key. Dry runs do not provision keys, and writes compare the original document plus tenant/organization scope to detect concurrent edits. Historical plaintext documents require this backfill or a re-save; the upgrade does not rewrite them automatically.
- DEK generation – 32 random bytes, base64-encoded; stored under
tenant_key_<tenantId>in Vault. - Rotation – future addition: new version stored under suffix
tenant_key_<tenantId>_v2with dual-read, single-write strategy; current design keeps a single active DEK per tenant. - Caching – DEKs cached with TTL (e.g., 15 minutes) and proactive refresh on expiry; invalidated if KMS returns a new version.
- Derived-key fallback – when running without Vault and with a dedicated fallback secret, the derived KMS hashes the chosen secret to a root key and produces per-tenant DEKs with PBKDF2-SHA512 using the tenant id as salt, encoded base64. The key stays stable for a tenant while the secret is unchanged.
- Key mismatch fails the write, it never re-wraps – the encrypt path skips a value only when it genuinely decrypts under the current DEK, because a bare
<iv>:<ct>:<tag>:v1shape is forgeable (#2720). A value sealed under another of the tenant's read keys (the derived fallback key after a Vault outage, while that fallback secret is still configured) is opened and re-sealed under the current key by the same write. A value that is real ciphertext under a key that is not among the read keys — the previous DEK mid-rotation, or a fallback key that is no longer configured — fails that check too, and encrypting it again would nest one envelope inside another: unreadable by any normal decrypt, indistinguishable from correct ciphertext by inspection, and it would overwrite the lookup hash with a hash of ciphertext. Such a write now raisesTenantDataEncryptionErrorwith codeWRONG_KEYinstead (#5951). Operationally this means a write touching an affected record fails loudly until the rotation is completed (TENANT_DATA_ENCRYPTION_OLD_KEY+mercato entities rotate-encryption-key) or the DEK that sealed the data is restored — a deliberate trade of availability for integrity, since the alternative is silent, undetectable corruption. Forged values whose shape is not length-valid (the check is length-based, not content-based) are still encrypted as ordinary plaintext, so #2720 stays closed. - When no key ever opens it — manual intervention – a field can permanently fail the
WRONG_KEYcheck when the DEK that sealed it is genuinely gone (not just rotated), or when a value written before the field joined the encryption map happens to be shape-valid ciphertext-looking text that was never real ciphertext at all. Neither case has an automatic fix:TENANT_DATA_ENCRYPTION_OLD_KEYonly helps when the sealing key is still known, and re-running rotation against the same row repeats the same skip (see the CLI's closing summary, which lists every skippedentity.field row=<id>rather than only logging it inline). Resolve manually per row: (1) if the value is genuine ciphertext under a key you can still recover, decrypt it out-of-band and re-run rotation with that key; (2) if the key is unrecoverable, decide with the data owner whether the field can be cleared or must be treated as permanently lost; (3) if the value was never real ciphertext (a coincidentally shape-valid plaintext written before the column was encrypted), update it directly via SQL so the next write encrypts it normally. There is currently no CLI flag to reseal such a value automatically — this is intentional, since doing so silently would risk persisting attacker-chosen bytes as if they were verified ciphertext. - Lazy provisioning is a state change –
encryptEntityPayloadprovisions the tenant's DEK on first use, which writes real key material to Vault. Callers that only preview or check ("would this row be encrypted?") MUST pass{ createMissingDek: false }so KMS stays untouched; the payload then comes back unchanged, exactly as when KMS declines a key.getWriteDek(keyId)is the read-only probe for "does a key exist yet", andresolveEncryptionKeyId(entityId, keyScope, tenantId)derives the id a map's payloads are sealed under (system:<entityId>for system-scoped maps). The--dry-runmodes ofmercato entities rotate-encryption-keyandmercato entities backfill-system-encryptionuse this path, so they report the rows a real run would rewrite without creating a key (#5950).
Integration points to implement
- KMS service interface + Vault implementation registered in DI (packages/shared → packages/core DI).
- AES-GCM helper library (shared) plus deterministic hashing utility.
- New Entities module tables and CRUD/UI to manage encryption maps (including system-entity selection).
- MikroORM interceptor/wrapper to encrypt/decrypt on save/load using tenantId from auth context.
- Auth adjustments: add
email_hashcolumn, populate on write, query by hash during login. - Tenant bootstrap: generate + store DEK when
TENANT_DATA_ENCRYPTIONis enabled; warn otherwise. - Health/warning surfacing: warning record when Vault unavailable; telemetry hooks around map cache misses and KMS failures.
Turning encryption off
TENANT_DATA_ENCRYPTION=no is a supported state, but it only governs new writes. Rows already
encrypted stay ciphertext, and the decrypt-on-load hook that used to hide that is gone with the
toggle. On a database that has never encrypted anything, set the flag and restart. Otherwise the
order matters:
# 1. While encryption is still ON — this needs the DEK.
yarn mercato entities decrypt-database --tenant <uuid> --confirm <uuid> --dry-run
yarn mercato entities decrypt-database --tenant <uuid> --confirm <uuid> --confirm-offline-maintenance <uuid> --deactivate-maps
# 2. Only now flip the flag, and restart every replica (DEK and map caches are in-process).
# TENANT_DATA_ENCRYPTION=no
# 3. Rebuild the search/filter indexes.
yarn mercato query_index reindex --tenant <uuid>
# 4. Re-save every configured integration's credentials from the admin UI (see below).
Flipping the flag before step 1 is the mistake to avoid. Search tokens are hashes of plaintext — the indexer decrypts a document before tokenising it, which is what lets the token index survive encryption being switched on or off. With the toggle already off there is nothing to decrypt with, so a reindex would tokenise ciphertext. The write path detects the envelope by shape and preserves the existing tokens rather than replacing them, and logs a warning naming the affected fields, but those fields stay unsearchable until you decrypt and reindex properly.
That detection runs only while no DEK is reachable — disabled or unavailable below, the
states where shape is the only test available. A shape is forgeable, and in active mode the
indexer really did decrypt the document, so a value that still looks like an envelope there is
plaintext somebody typed and is indexed as such.
Three states, not two
Code that branches on encryption must distinguish an operator opt-out from a KMS outage. Use
resolveEncryptionMode(kms) from @open-mercato/shared/lib/encryption/kms:
| Mode | Meaning | Correct handling |
|---|---|---|
disabled | TENANT_DATA_ENCRYPTION=no | Plaintext is the intended outcome — degrade to it. |
active | Encryption on, DEK reachable | Encrypt. |
unavailable | Encryption on, no DEK reachable | Fail closed. Never write a secret in the clear. |
Do not branch on kmsService.isHealthy() alone. NoopKmsService.isHealthy() is deliberately
inverted — it reports healthy exactly when encryption is off, so that enabled && healthy
collapses correctly — which means a bare if (!kms.isHealthy()) reads the first and third rows as
the same condition.
What still needs a decrypted database
-
Integration credentials are stored in the clear under
disabled, but a blob sealed before the toggle was flipped cannot be opened by any key. Reads raiseCredentialsEncryptionUnavailableErrorwithreason: 'sealed-while-disabled'rather than handing an adapter a garbage secret.decrypt-databasedoes not fix this, and step 4 above is not optional: credentials carry a second, service-level envelope under__om_encrypted_credentials_blob_v1inside theintegration_credentials.credentialsvalue. The command decrypts the column that the encryption map covers; the envelope inside it survives. Every integration's credentials must be re-entered once after the flag flips. The admin credentials form loads as if nothing were configured (the route degrades on this reason specifically), and saving stores them in the clear. Until then the adapter itself fails loudly rather than running with a broken secret. -
Ephemeral session API key secrets (MCP / AI chat) are stored in the clear under
disabled. Sessions minted while encryption was on are unrecoverable afterwards; they expire within 30 minutes, so re-issuing the session key is the remedy.
Search precision is a separate switch
Disabling encryption does not by itself restore exact SQL ILIKE on list search. The token rewrite
is gated on OM_SEARCH_ENABLED (default true), not on the encryption toggle. To get exact
matching back on plaintext columns, set OM_SEARCH_USE_ILIKE_FOR_NON_ENCRYPTED_FIELDS=true — only
then does the encryption toggle feed into that decision. OM_SEARCH_ENABLED=false turns the token
machinery off entirely.
Operational notes
- Keep
TENANT_DATA_ENCRYPTION=yesby default. SetTENANT_DATA_ENCRYPTION=noonly for local dev or when KMS is down during incident response. - Run
yarn db:generateafter updating entities to align migrations with schema changes (email hash, map storage). - For multi-node setups, back the cache with Redis to avoid per-node misses when definitions change.
- Avoid encrypting fields used for joins or range queries; prefer hashing for equality lookups (e.g., email) and keep unencrypted derived columns only when strictly necessary.