Open MercatoDocsSearch docsAPI reference

User guide

Encryption setup

Set up key storage and choose which fields need encryption before enabling it. Check how search and existing records behave under the configuration you deploy.

Use tenant data encryption to protect sensitive columns with per-tenant DEKs, keep deterministic hashes for lookups, and let admins choose which fields stay encrypted.

Warning · Encryption maps are at-rest protection, not a read-side access control

Declaring a field in an encryption map controls how the value is stored, not who may read it. It does not restrict who can see the plaintext through an authorised query path: any caller allowed to read the record at all receives every mapped field in the clear, because decryption happens automatically on load. Marking a GDPR-relevant column encrypted protects it against database access, backups and dumps – it is not a substitute for an ACL feature on the route or page that exposes the record.

To restrict who reads a field, gate the surface that returns it with an ACL feature (requireFeatures in page metadata, or a feature check in the API route). To have a specific query skip decryption entirely, see Declining decryption per query.

Environment switches

Note: changing encryption maps or toggling the Encrypted flag on a custom field only applies to data written after the change; previously stored values stay as they were unless you re-save or migrate them.

Vector search embeddings (important)

When using the vector module (vector search / embeddings), be aware that embeddings are stored unencrypted (for example, in Postgres pgvector the raw vector is stored in vector_search.embedding). Even though the source text is decrypted only transiently to compute the embedding and result metadata is encrypted by default, embeddings can still indirectly encode information about the underlying text.

In practice, reconstructing the original text from embeddings is difficult, but treat embeddings as sensitive data:

Vault setup (KMS)

  1. Enable KV v2 and pick a mount, e.g. secret/:
    • vault secrets enable -path=secret kv-v2
  2. Export envs for the backend:
    • VAULT_ADDR=https://vault.example.com
    • VAULT_TOKEN=<token>
    • VAULT_KV_PATH=secret/data
    • TENANT_DATA_ENCRYPTION=yes
  3. Start the app; DEKs are created per tenant at secret/data/tenant_key_<tenantId>.
  4. To pre-create a key manually (optional): vault kv put secret/tenant_key_<tenantId> key=$(openssl rand -base64 32).

Define encryption maps in code

import type { ModuleEncryptionMap } from '@open-mercato/shared/modules/encryption'

export const defaultEncryptionMaps: ModuleEncryptionMap[] = [
  {
    entityId: 'customers:customer_address',
    fields: [
      { field: 'postal_code' },
      { field: 'email', hashField: 'email_hash' }, // add hash when lookups must stay deterministic
    ],
  },
]

Adding a map to a module that is already deployed

defaultEncryptionMaps only reaches tenants created after the change. Nothing re-seeds existing tenants: not yarn db:migrate, not the start scripts. Without a backfill, every existing tenant keeps writing the new field as plaintext, silently.

When you add a map, or a field to an existing map, in a module that may already run somewhere, ship a migration in the same module that backfills it:

import { Migration } from '@mikro-orm/migrations'
import { buildEncryptionMapBackfillSql } from '@open-mercato/shared/lib/encryption/migration-backfill'

export class Migration20260929120000 extends Migration {
  override async up(): Promise<void> {
    this.addSql(buildEncryptionMapBackfillSql({
      entityId: 'customers:customer_address',
      fields: [{ field: 'postal_code' }],
    }))
  }

  override async down(): Promise<void> {}
}

The helper inserts the map for every existing tenant/organization that already has active encryption maps, and appends missing fields to maps that already exist. Tenants with encryption disabled are skipped. It is idempotent and leaves fields added by admins untouched. The entity id and fields are written literally, not imported from encryption.ts, so the migration keeps meaning the same thing later. Keep down() empty: deleting by entity_id would also remove maps seeded at tenant creation or edited in the UI, and switch encryption off for that entity.

yarn db:generate warns when the connected database has tenants missing a declared field and no migration backfills it. Set OM_ENCRYPTION_BACKFILL_CHECK=off to silence it.

Rows written before the backfill ran stay plaintext. Encrypt them with yarn mercato entities rotate-encryption-key --tenant <tenantId> (without --old-key it only encrypts plaintext values), or by re-saving the records.

Declining decryption per query

Decryption is bound to the tenant the caller asserted, not to the tenant stored on the row: the query engines refuse to decrypt a row whose tenant_id contradicts QueryOptions.tenantId, return it as ciphertext, and log one aggregated warning naming the mismatching tenant ids. A scoping mistake elsewhere therefore degrades to ciphertext instead of disclosing another tenant's plaintext.

The comparison needs a tenant on both sides. An ORM read through find*WithDecryption that passes no scope has no caller tenant to bind against and keeps the pre-guard behaviour – pass { tenantId } to get the binding. See Decryption is bound to the caller's tenant for the full set of limits.

A query that does not need plaintext at all can decline it outright with QueryOptions.decryptEncryptedFields: false. The declined query performs no DEK lookup:

const res = await queryEngine.query('customers:customer_entity', {
  tenantId: auth.tenantId,
  fields: ['id', 'display_name'],
  decryptEncryptedFields: false, // display_name comes back as stored ciphertext
  page: { page: 1, pageSize: 50 },
})

The same switch is available declaratively on a CRUD list route:

makeCrudRoute({
  list: {
    entityId: E.customers.customer_entity,
    decryptEncryptedFields: false,
  },
})

It defaults to true – today's behaviour – so existing callers are unaffected, and it is an opt-in to declining plaintext, not an access control.

Sorting on an encrypted field is unavailable on a declined query, because there is no plaintext to sort by: the sort falls through to SQL ORDER BY over ciphertext, which produces a meaningless order. The engines log one warning when a declined query sorts on an encrypted field – sort on a plaintext column instead, or drop the flag for that query.

Manage maps in the UI

Open Configuration → Encryption. Pick an entity, toggle Encryption enabled for this entity, and choose which fields are encrypted plus optional hash columns.

Encryption map editor

Notes:

Encrypt custom fields

When defining a custom field, check Encrypted to store its values with the tenant DEK. Works for text, multiline, integer, float, boolean, select, and relation kinds.

Custom entity records also encrypt these fields inside custom_entities_storage.doc, with no need to enable EAV compatibility writes. Authorized record queries decrypt values using each record's tenant and organization; multi-value fields retain their array shape. If a protected document cannot be encrypted, its write fails before persistence.

Previously stored plaintext documents remain readable. Re-save them, or run the entities backfill below, to encrypt their protected values. Updating a document also encrypts protected legacy values retained by a partial update.

Encrypted custom field toggle

Key rotation and backfills

Use the CLI to encrypt plaintext rows or rotate a previous fallback key to the current KMS/fallback.

Auth users:

yarn mercato auth rotate-encryption-key
yarn mercato auth rotate-encryption-key --old-key <previous_fallback_key>
yarn mercato auth rotate-encryption-key --tenant <tenantId> --org <organizationId>

Entities with encryption maps and custom entity documents with encrypted fields:

# Encrypt existing plaintext rows:
yarn mercato entities rotate-encryption-key

# Rotate from a previous key after your secret manager injects TENANT_DATA_ENCRYPTION_OLD_KEY:
yarn mercato entities rotate-encryption-key --tenant <tenantId> --org <organizationId>

Notes:

Rotating the lookup hash pepper

Version. This procedure requires the post-v0.10.0 implementation of LOOKUP_HASH_OLD_PEPPER and entities rehash-lookups. On v0.10.0 keep the existing pepper. Upgrading all instances to a version with rotation support comes before changing it.

The lookup pepper keys the hashes used for exact matches such as sign-in by email. Its current value comes from LOOKUP_HASH_PEPPER, then TENANT_DATA_ENCRYPTION_FALLBACK_KEY, then TENANT_DATA_ENCRYPTION_KEY. LOOKUP_HASH_OLD_PEPPER adds a read candidate during rotation. New writes use the current pepper.

  1. Deploy the version that supports LOOKUP_HASH_OLD_PEPPER while keeping the current pepper in use. Generate a new independent pepper and configure both values through your secret manager.

  2. For a rolling cutover, first set LOOKUP_HASH_OLD_PEPPER to the new value while keeping the old value active for writes. Once all app and worker instances have picked up both candidates, pause writes that assign lookup hashes while switching LOOKUP_HASH_PEPPER to the new value and LOOKUP_HASH_OLD_PEPPER to the previous effective pepper. Resume those writes when all writers use the new pepper. This avoids concurrent creates inserting the same value under different hashes. If the previous hashes were unkeyed, leave LOOKUP_HASH_OLD_PEPPER unset after the cutover.

  3. Once every writer is using the new pepper, preview and run the rehash for each tenant. Run the tenantless sweep as well to cover records such as pending onboarding requests.

    yarn mercato entities rehash-lookups --tenant <tenantId> --dry-run
    yarn mercato entities rehash-lookups --tenant <tenantId>
    yarn mercato entities rehash-lookups --tenantless --dry-run
    yarn mercato entities rehash-lookups --tenantless
    
  4. Re-run the previews and check that they report zero rows to update. Verify email sign-in and remove LOOKUP_HASH_OLD_PEPPER from every instance.

The command uses the existing data-encryption keys to read encrypted sources and updates their existing hash columns in batches. It verifies each stored digest against a mapped source and the configured peppers, including legacy unkeyed digests. A preview reads the same rows without writing hashes or provisioning keys. If a source cannot be decrypted or verified, or a concurrent edit changes a row, resolve the error and re-run the same scope. Keep the previous pepper configured until every scope is complete. Coordinate any changes to encryption maps separately from the rehash.

Backfilling system-scoped records

Some records exist before any tenant does – a self-service onboarding request is created while the person filling the form still has no workspace. Those entities are encrypted under a system-scoped map (keyScope: 'system') declared in module code rather than under a per-tenant map in the database, so rotate-encryption-key never sees them: it walks the encryption_maps table and skips every row without a tenant.

Use backfill-system-encryption to encrypt rows of that kind that were written before the map existed:

# Preview only (no writes) — always start here
yarn mercato entities backfill-system-encryption --dry-run

# Encrypt every system-scoped entity
yarn mercato entities backfill-system-encryption

# Restrict the run to one entity
yarn mercato entities backfill-system-encryption --entity onboarding:onboarding_request

# Tune the page size for a large table (default 500)
yarn mercato entities backfill-system-encryption --batch-size 1000

Notes:

Decrypting data (removing encryption)

Use decrypt-database to write all encrypted fields back to plaintext for a tenant. This is irreversible – take a full backup first.

# Preview only (no writes)
yarn mercato entities decrypt-database --tenant <tenantId> --confirm <tenantId> --dry-run

# Check encryption status and sampled payload estimate
yarn mercato entities decrypt-database --tenant <tenantId> --check

# Full decryption
yarn mercato entities decrypt-database --tenant <tenantId> --confirm <tenantId>

# Full decryption + deactivate encryption maps
yarn mercato entities decrypt-database --tenant <tenantId> --confirm <tenantId> --confirm-offline-maintenance <tenantId> --deactivate-maps

After a successful run:

  1. Set TENANT_DATA_ENCRYPTION=false in your environment / secrets.
  2. Restart all application replicas to flush in-process encryption caches.
  3. Run yarn mercato query_index reindex --tenant <tenantId> to rebuild search indexes.
  4. Run --check again to confirm no encrypted values remain.

The --confirm <tenantUuid> flag is a required safety gate – it must exactly match --tenant to prevent accidental cross-tenant runs. See the decrypt-database CLI reference for the full option list, error codes, and troubleshooting.

Malformed ciphertext makes the command exit non-zero. When --deactivate-maps is present, the maps remain active until every selected field decrypts successfully; investigate the reported rows and re-run before disabling encryption.

--check writes nothing, so it always completes its sweep: an entity whose tenant DEK is unreachable is reported and skipped rather than ending the inspection, and the command then exits non-zero to mark the check incomplete. Treat the printed counts as covering only the entities it could reach.

Debugging

Running without Vault

If you don’t want to depend on Vault, set a fallback secret and the runtime will derive tenant keys from it:

When Vault is down or not configured, a warning banner appears and shows which env var supplied the derived key. Avoid short/shared secrets – treat this like any other encryption root and store it securely.

Offline policy retirement

decrypt-database --deactivate-maps requires --confirm-offline-maintenance <tenantUuid> in addition to --confirm. Stop every application, worker and integration process that can write to this database before confirming. Restart every replica after the operation before resuming writes, so cached encryption policies cannot produce new ciphertext after retirement. The CLI cannot verify that external processes have stopped; the tenant confirmation is an explicit operator attestation, not an online-maintenance mode.

The command discovers fallback-map organization scopes from actual table rows, including organizations with no map row. An organization-only operation includes the tenant-wide fallback for reads but never retires that fallback. Retirement locks the policy and selected data tables, refreshes policies and performs a final ciphertext sweep in the same transaction before retiring exact map IDs. Locking may block other SQL writers; schedule a maintenance window. Row updates also compare the old column values and fail instead of overwriting a concurrent change. If a conflict or residual ciphertext is reported, retain the active policies and retry after stopping writers.

Previous: Manage dictionaries · Next: Manage feature toggles