Agora

You're viewing the docs for Crypto 0.x. The latest is 1.x (rc). Go to the 1.x (rc) docs

Per-subject encryption

One key per person, values encrypted in your app with cached data keys, encrypted Lucid columns, backfill and crypto-shredding.

Give each subject (a researcher, a user, a customer) its own key on the crypto server, and encrypt their data in your app. Reads and writes need no network call once the subject's data key is cached, and deleting the subject's key makes all of their data unrecoverable.

  • Subject key: an aes256-gcm key on the crypto server, named subject_<type>_<id>, deletable.
  • Data key: a random AES-256 key that encrypts the values. Your database stores it only wrapped by the subject key (table crypto_data_keys).
  • Cache: unwrapped data keys stay in memory for a while, so steady-state traffic stays local.

It works the same in every topology: standalone (local development, tests), control plane, tenant.

Configure

config/crypto.ts
import { defineConfig } from '@adonis-agora/crypto'

export default defineConfig({
  topology: 'tenant',
  tenant: { url: env.get('CRYPTO_URL'), partition: 'research', token: env.get('CRYPTO_TOKEN') },
  subjects: {
    createKeys: 'explicit',                      // see "Token scope"
    cache: { maxEntries: 1000, ttlMs: 300_000 }, // the defaults
  },
})

Type your subjects. A bare id is only an id: researcher 7 and project 7 would share the key subject_7, and forgetting one would destroy the other's data. Give every encrypted column a namespace (subject_researcher_7), or pass { type, id }. Bare ids are refused by default (requireType: true). With requireType: false (one kind of subject only), a bare string id containing _ is still refused, so it can never name a typed subject's key.

OptionDefault
prefixsubject_key name is ${prefix}${type}_${id} (or ${prefix}${id}); must match ^[a-z][a-z0-9_-]{0,62}$
requireTypetruerefuse bare ids: every subject is { type, id } or comes from a column namespace
keyName—(id, type) => string, full control over the key name
createKeyslazylazy creates a subject's key on its first write; explicit requires subjects.create(id) first
cache{ maxEntries: 1000, ttlMs: 300000 }false asks the crypto server on every operation
storedataKeyStores.lucid()where wrapped data keys live; dataKeyStores.lucid({ connection, schema }) or dataKeyStores.memory()

The crypto_data_keys table is created at boot. To manage it yourself, pass dataKeyStores.lucid({ autoCreateSchema: false }) and create:

CREATE TABLE crypto_data_keys (
  id varchar(32) PRIMARY KEY,
  key_name varchar(64) NOT NULL,
  wrapped text NOT NULL,
  created_at varchar(32) NOT NULL,
  retired_at varchar(32) NULL
);
CREATE INDEX crypto_data_keys_key_name ON crypto_data_keys (key_name, created_at);

Token scope

In the key-name segment, a capability can name a prefix (subject_* matches subject_42, never orders); other segments do not take prefixes. The web app's token needs only:

crypto:datakey:subject_*  crypto:encrypt:subject_*  crypto:decrypt:subject_*

With createKeys: 'lazy' it also needs crypto:keys:manage:subject_* and crypto:keys:read:subject_* (create on first write). Least privilege is createKeys: 'explicit': create subject keys (crypto.subjects.create({ type, id })) and forget them (crypto:subjects:forget) from a separate operations token that holds crypto:keys:manage:subject_*, crypto:keys:read:subject_* and crypto:rewrap:subject_*, so the token serving web requests can never delete a key. The crypto server must run this version for prefix capabilities to be honoured.

Encrypted columns

app/models/note.ts
import { BaseModel, column } from '@adonisjs/lucid/orm'
import { encrypted } from '@adonis-agora/crypto'

export default class Note extends BaseModel {
  static selfAssignPrimaryKey = true

  @column({ isPrimary: true })
  declare id: string

  @column()
  declare researcherId: number

  @encrypted({ subject: (note: Note) => note.researcherId, namespace: 'researcher' })
  declare body: string

  @encrypted({ subject: (note: Note) => note.researcherId, namespace: 'researcher', json: true })
  declare answers: Record<string, unknown>
}
const note = await Note.create({ id: randomUUID(), researcherId: 7, body: 'field notes', answers })
const again = await Note.findOrFail(note.id)
again.body // 'field notes'
  • Values are encrypted in model.save() / Model.create() and decrypted after find, first, all, query results, pagination and preloads.
  • The database column must be text. json: true stores any JSON value as encrypted text.
  • Each ciphertext is bound to its table, column and row id: copied to another row or column, it does not open. The row id must be known before the insert (a UUID). For auto-increment ids, pass row: (note) => note.someStableUniqueColumn, or row: false to bind table and column only.
  • A value that does not decrypt throws a SubjectKeyError; the ciphertext is never returned as data. For listings that may contain forgotten subjects, onUndecryptable: 'null' turns a value whose subject was forgotten into null and lists the attribute in model.$extras.agoraUndecryptable. Tampered or injected values (invalid) still throw unless you opt in with onUndecryptable: { null: ['forgotten', 'invalid'] }; alert on them with onUndecryptableError: (model, attribute, error) => …. An unreachable crypto server still throws. A nulled attribute cannot be saved back as null (that would destroy the stored value): set a real value, or clear the column with a query-builder update.
  • Changing the subject (researcherId) or the row binding re-encrypts the row's values on save. The row must be loaded with all its encrypted columns: moving a row loaded with select('id', 'researcher_id') throws, because the unloaded values would stay sealed for the old owner (and forgetting the old owner would destroy the new owner's data).

Writes that skip the model hooks do not encrypt:

  • Model.query().update({...}), db.from(...).insert/update and raw SQL write what you give them, plaintext included. saveQuietly() throws instead of writing.
  • Model.query().update({ researcher_id }) moves a row without re-sealing its values.

Guard every encrypted column with a CHECK constraint (see the last migration step): the database then refuses plaintext, values sealed for another subject than the row's, and values on a row with no subject, whatever wrote them. The prefix comparison is exact (case-sensitive) in every dialect.

Also:

  • where('body', ...): ciphertext is randomized, so encrypted columns cannot be searched or indexed.
  • .pojo() and raw queries return the stored ciphertext.
  • With row: false, select the subject column whenever you read the encrypted one.

Transactions

A cold subject (data key not cached) needs the crypto_data_keys table on another connection. On SQLite (one connection) that waits for the open transaction until the pool times out; on Postgres and MySQL it takes a second pooled connection. That includes Lucid's implicit transactions: updateOrCreate, updateOrCreateMany, fetchOrCreateMany and lockForUpdate. Warm the subject first:

await crypto.subjects.warm({ type: 'researcher', id: researcherId })
await db.transaction(async (trx) => { /* ... */ })

Migrating an existing column

  1. Change the column type to text if needed (Postgres: ALTER TABLE notes ALTER COLUMN answers TYPE text USING answers::text).

  2. Deploy the model with legacyPlaintext: true: rows that are still plaintext are read as they are, every save encrypts. A value carrying another of the library's tags (agora:ct1:, agora:v1:, agora:pk1:, agora:sig1:, or agora:se1: in another case) is never treated as plaintext; text that merely starts with "Agora:" is. A function limits it per row, and onLegacyRead lets you log every read; agora:doctor warns while any column has it on.

    @encrypted({
      subject: (note: Note) => note.researcherId,
      namespace: 'researcher',
      legacyPlaintext: (note: Note) => note.createdAt < MIGRATION_STARTED_AT,
      onLegacyRead: (note, attribute) => logger.warn({ id: note.id, attribute }, 'plaintext read'),
    })
    declare body: string

    On Postgres you can already refuse new plaintext writes (existing rows are not checked yet):

    import { addEncryptedColumnCheck } from '@adonis-agora/crypto'
    
    this.schema.raw(addEncryptedColumnCheck({
      table: 'research.notes', // schema-qualified (or `schema: 'research'`): no search_path
      column: 'body', subjectColumn: 'researcher_id', namespace: 'researcher',
      using: crypto.subjects, // its prefix; refuses a custom `keyName` it cannot express in SQL
      notValid: true,
    }))
  3. Encrypt the rest:

    node ace crypto:subjects:backfill '#models/note' --batch-size 500
  4. Remove legacyPlaintext, and enforce the constraint on every row:

    ALTER TABLE notes VALIDATE CONSTRAINT notes_body_encrypted;  -- Postgres, after notValid

    On MySQL use addEncryptedColumnCheck({ ..., dialect: 'mysql' }) now. On SQLite put encryptedColumnCheck({ column, subjectColumn, dialect: 'sqlite' }) in the CREATE TABLE. From then on the database refuses any value that is not sealed for the row's subject.

The backfill walks the table by primary key, one batch at a time, and:

  • encrypts plaintext values;
  • reports a value sealed for another subject than its row's as moved and leaves it alone; with --adopt-moved it re-seals it for the row's subject, only when row binding proves the value belongs to that row (with row: false it refuses);
  • refuses a column that is not stored as text (json/jsonb: change its type first) and a value carrying another of the library's tags (see step 2);
  • skips values that are already encrypted (a rerun is safe);
  • updates each value only if it is still what it read, so a concurrent write is never overwritten (counted as a conflict; run it again);
  • does not touch updated_at.

It prints a cursor after each batch; --from <cursor> resumes there. --dry-run counts without writing (use it to audit a table for plaintext); --column body limits it to some columns. A value it cannot process stops the run; --skip-errors lists invalid or forgotten values (id, column, error code, never the value) and goes on. An outage or a refused token always stops it.

From code:

import { backfillEncryptedColumns } from '@adonis-agora/crypto'

const result = await backfillEncryptedColumns(Note, { batchSize: 500, after: lastCursor, onError: 'skip' })
// { rows, encrypted, reencrypted, moved, adopted, unchanged, conflicts, failed, failures, cursor }

Encrypting values directly

import crypto from '@adonis-agora/crypto/services/main'

const owner = { type: 'researcher', id: researcher.id }
const sealed = await crypto.subjects.encrypt(owner, text, { aad: `report:${report.id}` })
const text = await crypto.subjects.decrypt(sealed, { subject: owner, aad: `report:${report.id}` })

const payload = await crypto.subjects.encryptJson(owner, { answers })
const { answers } = await crypto.subjects.decryptJson(payload, { subject: owner })

aad binds the ciphertext to a context: the same string must reach decrypt. decrypt checks the value belongs to subject; anySubject: true skips that check, for when the aad already binds the owner.

Forgetting a subject

await crypto.forgetSubject({ type: 'researcher', id: researcher.id })
node ace crypto:subjects:forget 7 --type researcher --force

The subject's key is deleted on the crypto server, and its wrapped data keys and cached data keys are dropped here. From then on the subject's data cannot be opened from your database or its backups. Reads fail with forgotten, and so does any new write for that subject. A subject that never stored anything is forgotten too.

The guarantee is bounded by the crypto server's own storage: a backup of the crypto server taken before the deletion still holds the subject key (sealed with the server's root key). Keep those backups short-lived, or rotate the root key, if forgetting has to cover them too.

Rows of a forgotten subject stay in your tables as unreadable values: delete them, set them to null, or read them with onUndecryptable: 'null'.

Other processes that already cached one of the subject's data keys keep it until the cache TTL ends. To cut that window, call crypto.subjects.evict({ type, id }) on every process, for example from your event bus.

Rotation

  • Subject keys: rotate them on the crypto server (crypto:keys:rotate), then rewrap the stored data keys. The data itself does not change.

    node ace crypto:subjects:rewrap-keys
  • Data keys: crypto.subjects.rotateDataKey(id) starts a new data key for that subject's writes. Old values keep opening. In this process a write waits for the rotation; other processes keep writing with the old data key until their cache entry expires, so wait ttlMs before re-encrypting:

    node ace crypto:subjects:backfill '#models/note' --rotate

    A data key uses random 96-bit IVs, which is safe for about 2³² encryptions. One subject writing that much is unusual, but rotate a subject's data key well before (yearly, or every few million writes) if it might.

Cache and outages

SituationResult
Subject's data key cachedworks with no network call, even if the crypto server is down
Not cached, crypto server upone call to unwrap (or create) the data key, then cached
Not cached, crypto server downSubjectKeyError with code unavailable; nothing is read or written

There is no plaintext fallback. The trade-off: an unwrapped data key stays in this process' memory for up to ttlMs (default 5 minutes), and is overwritten with zeros when it leaves the cache. Lower ttlMs to shorten that window; it costs more calls to the crypto server.

Errors

Every failure is a SubjectKeyError with a code:

CodeMeaning
unavailablethe crypto server could not be reached and the data key was not cached
forgottenthe subject was forgotten
invalidnot a subject ciphertext, tampered, moved to another row/column/subject, or a misconfigured model
deniedthe token lacks a capability
sealedan encrypted attribute was read on a model loaded without its hooks

decryptJson and the encrypted columns never put the plaintext in an error message. | failed | anything else the crypto server reported |

import { SubjectKeyError } from '@adonis-agora/crypto'

try {
  await Note.findOrFail(id)
} catch (error) {
  if (error instanceof SubjectKeyError && error.code === 'unavailable') {
    return response.serviceUnavailable()
  }
  throw error
}

Format

agora:se1:<subject key>:<data key id>:<base64url(iv ‖ ciphertext ‖ tag)>

AES-256-GCM with a random 96-bit IV. The authenticated data covers the format version, the subject key, the data key id and the aad (for columns: table, column and row id).

Tests

import { memorySubjectKeys } from '@adonis-agora/crypto/testing'

const { subjects } = memorySubjectKeys()
const sealed = await subjects.encrypt({ type: 'researcher', id: 1 }, 'x')

Or boot the app with subjects: { store: dataKeyStores.memory() } and a standalone memory store.

On this page

Partner

Your product as the official integration for Crypto, right here.

Become a partner →