Encryptor

CIHex.pm VersionHex DownloadsHex DocsLicense

Status: pre-1.0. This package is under active development ahead of its 1.0.0 release, expected within the next few weeks. Until then, public APIs, storage formats, and derivation constants may change between releases without a deprecation cycle. Pin an exact version and review the changelog before upgrading.

Ergonomic envelope encryption for Elixir - a vault module, pluggable key providers, and per-tenant keys - on the aws_encryption_sdk engine.

What this is

Application-level encryption in Elixir usually arrives as one of two things: a thin wrapper over :crypto that leaves key management to the caller, or a full ESDK client whose surface is shaped for the cryptography rather than for the application. Neither answers the questions a real application asks - which key does this tenant's data use, how does that key rotate without a migration, where does the key material actually come from. This package is the layer that answers them.

Raw-keyring usage pulls in no AWS, HTTP, or XML libraries; only KMS-backed providers bring that stack in.

The security model in brief

A three-level key hierarchy (ADR-0003):

LevelWhatWhere it lives
1, root keyone per deploymentyour secrets manager; never encrypts application data
2, tenant master keyone per tenant per version32 random bytes, wrapped by level 1, stored in your key store
3, data keyone per messagegenerated by the engine, wrapped by level 2, discarded

The properties that follow from it, and that this package enforces rather than documents:

Installation

def deps do
[
{:encryptor, "== 0.2.0"}
]
end

Pin an exact version and read the changelog before upgrading: per the stability notice above, public APIs, storage formats, and derivation constants may change between releases until 1.0.0. Do not depend on encryptor 0.1.0 - that version is a name reservation published before the implementation existed and holds no code; 0.2.0 is the first release that does.

Requires Elixir ~> 1.18.

Quickstart

A single-key vault, for an application encrypting its own columns. This is card processing: one payments application storing card data for its own use.

defmodule MyApp.Vault do
use Encryptor.Vault, otp_app: :my_app
@impl true
def init(config) do
key = Base.decode64!(System.fetch_env!("MY_APP_CARD_KEY"))
{:ok,
Keyword.put(config, :provider,
{Encryptor.Provider.Static,
key: key, namespace: "acme_payments", name: "card/v1"})}
end
end
# config/config.exs
config :my_app, MyApp.Vault,
context_profile: :single,
algorithm_suite_id: 0x0478,
required_context: ["table", "column"],
static_encryption_context: %{"app" => "acme_payments"},
cache: [max_age: 60]

Add MyApp.Vault to your supervision tree, then:

context = %{"table" => "payment_methods", "column" => "number"}
{:ok, ciphertext} = MyApp.Vault.encrypt(card_number, encryption_context: context)
{:ok, ^card_number} = MyApp.Vault.decrypt(ciphertext, encryption_context: context)

ciphertext is the complete self-describing ESDK message and nothing else. You store that one binary; there is no second column to keep in step with it. Encryptor.Message.describe/1 reads what it says about itself, without a key and without verifying it:

{:ok, info} = Encryptor.Message.describe(ciphertext)
info.encryption_context
#=> %{"app" => "acme_payments", "column" => "number", "table" => "payment_methods"}
info.committed?
#=> true
info.encrypted_data_keys
#=> [%{key_name: "card/v1", provider_id: "acme_payments"}]

Two refusals worth seeing, because they are the model working:

MyApp.Vault.encrypt(card_number, encryption_context: %{"table" => "payment_methods"})
#=> {:error, %Encryptor.Error{reason: {:missing_required_context_keys, ["column"]}}}
MyApp.Vault.decrypt(ciphertext, encryption_context: %{"table" => "t", "column" => "c"})
#=> {:error, %Encryptor.Error{reason: :decrypt_failed}}

Three configuration notes the quickstart above is making silently:

The getting-started guide continues from here into the per-tenant vault, the two root secrets a deployment provisions on day one, and why the context must carry nothing that varies per row.

What the package contains

ModuleWhat it is
Encryptor.VaultThe surface: the use macro, the supervision tree, the five-layer config resolution and its freeze, encrypt/2, decrypt/2, rekey/2, derive/2, bang variants, config/0, started?/0
Encryptor.ProviderThe key-provider behaviour: a provider resolves a selector to key descriptors, and the vault alone turns descriptors into a keyring
Encryptor.Provider.Static / .FunctionThe two shipped adapters - keys held in configuration, and keys resolved by a function
Encryptor.Provider.ConformanceThe behaviour's test suite, use-able against your own adapter: state, buildable descriptors, candidate ordering, distinct names, stability, unknown selectors
Encryptor.EnvelopeThe level 1 to level 2 relationship: provision/3, unwrap/2, rewrap/2, tenant_ref/2
Encryptor.KdfHKDF-SHA256: label/1, derive_subkey/3, expand/3, extract/2, salted_subkey/5
Encryptor.KeyThe closed set of key descriptors, with Aes and Kms
Encryptor.Messagedescribe/1 and its Info struct
Encryptor.ErrorThe one error struct and its closed reason vocabulary

The materials cache is bounded by a recycler that drops the whole table on an interval (:recycle_after, defaulting to 20 * max_age), because the engine's LocalCache has no capacity limit and cannot be substituted through the cache behaviour (upstream #95). Every entry is re-fetchable derived material, so the worst outcome of a recycle is a cold miss.

Derived subkeys

derive/2 on your vault module (Encryptor.Vault.derive/3 underneath) hands a downstream library purpose-separated bytes from a tenant's key material without handing over the material:

{:ok, index_key} = MyApp.TenantVault.derive("blind-index", key: merchant_id, info: "email")
PRK = HKDF-Extract(:derivation_salt, key material)
purpose_key = HKDF-Expand(PRK, "encryptor/v1/<purpose>", 32)
derived = HKDF-Expand(purpose_key, info, length)

The salt is the vault's :derivation_salt and a caller cannot supply or override it, so two deployments provisioned from the same tenant key material derive unrelated subkeys. A vault configured without one starts normally and fails this call with {:missing_config, [:derivation_salt]}.

This surface hides the key material from the caller; it does not create a search-only capability. A component that can derive a tenant's index key holds that tenant's master key and can therefore also decrypt.

Rotating :derivation_salt is a full reindex. Every value ever derived under the old salt changes, so every stored blind index, and anything else built from a derived subkey, must be recomputed from plaintext. Treat the salt as pinned for the life of the deployment.

Not yet

Documentation

Decision records

Every cryptographic choice here is an ADR decision. A key-derivation scheme, an encryption-context field, a ciphertext layout, or an algorithm suite chosen inline in an implementation is a defect even when the choice happens to be a good one, because the record is what makes it reviewable.

RecordDecidesStatus
ADR-0001The vault layer: one host-owned module that wraps the engine completely, what it supervises, how it is configured, how its cache is bounded, and its error vocabularyaccepted
ADR-0002The key-provider behaviour: a provider resolves a selector to a key descriptor, and only the vault turns a descriptor into a keyringaccepted
ADR-0003The per-tenant envelope: a tenant key is 32 random bytes wrapped into an ordinary message, and the host stores the wrappingaccepted, amended
ADR-0004The encryption-context convention: the canonical keys, who supplies each, and how a vault enforces themaccepted, amended
ADR-0005Rotation and crypto-shred: three independent lifecycles, four operator procedures, and the one step that cannot be undoneaccepted
ADR-0006Telemetry: a closed event set whose metadata is an allow-list, and nothing key-shaped is ever in itproposed

The index, including the citation grammar for cross-repo references, is docs/adr/README.md.

The family

PackageOwns
encryptor (here)The vault surface, the key-provider behaviour, the envelope and key-derivation scheme, the encryption-context convention, the rotation model
encryptor_ectoThe Ecto types, the schema conventions, the wrapped-key storage and its migration, the re-encryption migrator

The split is deliberate and it is a boundary, not a layering convenience: no function in this package takes a repo, a query, a table, or a batch size, and this package defines no storage schema at all.

Engine notes

The design is written against aws_encryption_sdk v1.0.0 as published, with module paths cited so every claim can be re-checked. Two upstream issues are open and this package works around both until they move:

Contributing

The full quality gate is mix quality; the inner loop is mix quality --profile loop. The gate must be green before any commit, and the format stage runs in check mode, so run mix format yourself first.

Read the decision records before writing code here. Until a contract is fixed by an accepted record, it is open - and stopping to ask is the correct move.

License

Apache-2.0 - see LICENSE.