Open MercatoDocsSearch docsAPI reference

Architecture

Tenant data encryption

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.

Goals

Components

Environment variables

Data flow

Request, encryption map, key service and database
The entity manager consults the field map. The key service obtains the tenant key from Vault.
Diagram source
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

Write path

  1. API/CRUD normalises payload, then MikroORM entity hooks run.
  2. Hook loads the encryption map for (tenantId, entity) from cache; cache miss fetches from DB.
  3. Hook resolves the tenant DEK from kmsService (cached).
  4. 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.
  5. ORM persists ciphertext; hashes remain plaintext for lookups and deduplication.

Read path

  1. MikroORM loads entities (ciphertext in encrypted columns).
  2. Hook uses map + tenant DEK to decrypt mapped fields.
  3. 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 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:

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:

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

Encryption maps

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.

Integration points to implement

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:

ModeMeaningCorrect handling
disabledTENANT_DATA_ENCRYPTION=noPlaintext is the intended outcome – degrade to it.
activeEncryption on, DEK reachableEncrypt.
unavailableEncryption on, no DEK reachableFail 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

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

Previous: Configuration decision guide · Next: Platform roadmap and release status