Architecture
Field encryption starts with a map of the properties to protect. Follow a field through the tenant key, the ORM write and the authorized read.
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.
TENANT_DATA_ENCRYPTION (defaults to yes). When false, encryption hooks no-op but validation still runs so the system can be toggled on later.kmsService resolves tenant keys. Default backend: HashiCorp Vault (per-tenant secret path). Interface supports future providers.
getTenantDek(tenantId) → resolves tenant_key_<tenantId> from KMS; caches in-memory with TTL + background refresh.createTenantDek(tenantId) → generates random 256-bit key, stores at tenant_key_<tenantId>, returns material.isHealthy() → signals whether the provider is reachable; encryption hooks log + warn when unhealthy.base64(iv):base64(ciphertext):base64(tag):v1. Includes encrypt(value, dek) and decrypt(payload, dek) plus deterministic hashForLookup(value) (SHA-256 hex) for email lookups.beforeCreate/beforeUpdate: finds mapped fields and replaces values with ciphertext (plus storing the clear-text hash where configured, e.g., users.email_hash).afterFind: decrypts mapped fields using the tenant DEK; falls back silently when encryption is disabled or KMS is unhealthy.users table gains email_hash (indexed) so login can query by hash even when email is encrypted.kmsService.createTenantDek with the tenant_key_<tenantId> prefix.TENANT_DATA_ENCRYPTION_DEBUG=yes to log map evaluation plus Vault KMS reads/writes.TENANT_DATA_ENCRYPTION_FALLBACK_KEY, then legacy TENANT_DATA_ENCRYPTION_KEY). AUTH_SECRET and NEXTAUTH_SECRET are never used for tenant data encryption. The dev default fallback is available only with ALLOW_DERIVED_KMS_FALLBACK=true; otherwise missing KMS configuration becomes a noop KMS.TENANT_DATA_ENCRYPTION – master toggle (yes by default). Disables hooks when set to no but keeps validation in place.TENANT_DATA_ENCRYPTION_DEBUG – yes to 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 to secret/data.TENANT_DATA_ENCRYPTION_FALLBACK_KEY, then legacy TENANT_DATA_ENCRYPTION_KEY. Auth/session secrets are intentionally excluded. The built-in dev fallback requires ALLOW_DERIVED_KMS_FALLBACK=true; production without a dedicated fallback secret falls back to the noop KMS.flowchart TD
subgraph Request
API["API/CRUD handler"]
ORM["MikroORM entity manager"]
end
subgraph Services
MAP["Encryption map cache"]
KMS["KMS service (Vault default)"]
end
DB[(PostgreSQL)]
VAULT[(Vault)]
API --> ORM
ORM -- needs map & DEK --> MAP
MAP -- miss --> DB
MAP -- tenantId --> KMS
KMS --> VAULT
ORM --> DB
DB --> ORM
ORM --> API
classDef focus fill:#e0f29c,stroke:#34402d,color:#172011,stroke-width:2px
class ORM focus
(tenantId, entity) from cache; cache miss fetches from DB.kmsService (cached).email_hash).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.
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.
The decrypt scope is resolved by resolveDecryptScope
(@open-mercato/shared/lib/encryption/decryptScope), shared by BasicQueryEngine,
HybridQueryEngine and the ORM EncryptionSubscriber:
tenant_id is used only when the caller asserted none, or when it agrees with
the tenant the caller asserted.warn per query naming the entity, the refusal count and the mismatching
tenant ids – ids only, never field values.organization_id is 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.
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:
find*WithDecryption call 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.tenant_id column 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 narrow fields projection does not land here: both query
engines force tenant_id into 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.tenant_id of its own (a join row
such as UserRole) is not refused against it – such a row may legitimately link entities of
several tenants. Entities hydrated by the same find*WithDecryption read are still bound
individually, because the subscriber's onLoad runs under the caller's scope.EntityManager by 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.
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:
{ title: 'Renewal' }, { title: { $in: [...] } }
and em.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 with TENANT_DATA_ENCRYPTION=no, which is how the mistake survives review.hashField to the field's rule in the module's
encryption map and filter on the hash (this is how users.email_hash supports login).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.customers module for the
established pattern.$ilike never matches an encrypted columnThis 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.
entity_id, fields[], tenant_id, organization_id, is_active, created_at.users, sales.order, sales.quote, customer_addresses) and ticking which fields should be encrypted.users.email, customer addresses (address fields), sales orders/quotes snapshot + personal data, customer notes, order/quote notes.users.email_hash).(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, and decryptEntityPayload all 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.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.
tenant_key_<tenantId> in Vault.tenant_key_<tenantId>_v2 with dual-read, single-write strategy; current design keeps a single active DEK per tenant.<iv>:<ct>:<tag>:v1 shape is forgeable (#2720). A value that is real ciphertext under a different key – the previous DEK mid-rotation, or the derived fallback key after a Vault outage – 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 raises TenantDataEncryptionError with code WRONG_KEY instead (#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.WRONG_KEY check 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_KEY only 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 skipped entity.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.encryptEntityPayload provisions 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. getDek(keyId) is the read-only probe for "does a key exist yet", and resolveEncryptionKeyId(entityId, keyScope, tenantId) derives the id a map's payloads are sealed under (system:<entityId> for system-scoped maps). The --dry-run modes of mercato entities rotate-encryption-key and mercato entities backfill-system-encryption use this path, so they report the rows a real run would rewrite without creating a key (#5950).email_hash column, populate on write, query by hash during login.TENANT_DATA_ENCRYPTION is enabled; warn otherwise.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.
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.
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 raise
CredentialsEncryptionUnavailableError with reason: 'sealed-while-disabled' rather than
handing an adapter a garbage secret.
decrypt-database does not fix this, and step 4 above is not optional: credentials carry a
second, service-level envelope under __om_encrypted_credentials_blob_v1 inside the
integration_credentials.credentials value. 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.
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.
TENANT_DATA_ENCRYPTION=yes by default. Set TENANT_DATA_ENCRYPTION=no only for local dev or when KMS is down during incident response.yarn db:generate after updating entities to align migrations with schema changes (email hash, map storage).Previous: Configuration decision guide · Next: Platform roadmap and release status