AshVault (AshVault v0.2.0)

Copy Markdown View Source

Encrypted attributes for Ash resources.

defmodule MyApp.Accounts.User do
  use Ash.Resource, extensions: [AshVault]

  ash_vault do
    vault MyApp.Vault
    scope :tenant

    encrypt :email
    encrypt :ssn, encrypt_nil?: false

    decrypt_by_default [:email]
  end
end

Each encrypted attribute is replaced: the plaintext attribute entity is removed, a private encrypted_<name> :binary attribute takes its place in the data layer, and a calculation of the original name and type decrypts on read. There is no plaintext column, so no data layer can write one.

Writes go through an argument of the original name and type plus an AshVault.Changes.Encrypt change that encrypts in a before_action hook and scrubs the plaintext from changeset.arguments and changeset.params.

See AshVault.Dsl for the DSL, AshVault.Info for introspection, and AshVault.Serializer for the plaintext wire format.

Limitations

  • The decrypt calculation is filterable?: false, sortable?: false — randomized AEAD ciphertext supports neither. For equality searching, encrypt :email, searchable?: true adds a deterministic email_lookup HMAC column beside the ciphertext; see AshVault.Lookup and AshVault.Query. Ordering and prefix matching remain impossible, by construction.
  • Encrypted attributes on embedded resources require ash >= 3.26, which is when Ash.Type.Binary started handling its own base64 encoding.

Summary

Functions

Decrypt one stored value, returning {:ok, value} or {:error, %AshVault.Errors.*{}}.

Crypto-erase scope in vault: destroy every key version and tombstone the scope.

Encrypt value and write it to the backing attribute of field, scrubbing the plaintext from the changeset.

Encrypt one value for a field of a resource, returning the bytes to store.

The name of the backing ciphertext attribute for an encrypted field.

The backing ciphertext attribute, resolving a field's stored_as alias.

The name of the generated read action that finds rows by a searchable field's value.

The name of the deterministic lookup-token attribute for a searchable field.

Rotate the key for scope in vault, minting a new key version.

Remove a field's plaintext from changeset.arguments and changeset.params.

Every backing attribute a write of field must set: the ciphertext, plus the lookup token when the field is searchable?.

Functions

ash_vault(body)

(macro)

decrypt_value(vault, blob, context, type, constraints)

@spec decrypt_value(module(), binary(), AshVault.Context.t(), Ash.Type.t(), keyword()) ::
  {:ok, term()} | {:error, Exception.t()}

Decrypt one stored value, returning {:ok, value} or {:error, %AshVault.Errors.*{}}.

Never raises: crypto failures are values here, so the decrypt calculation can return them to Ash and a destroyed tenant comes out of Ash.read/2 as a clean AshVault.Errors.KeyDestroyed.

destroy_keys!(vault, scope, context \\ nil)

@spec destroy_keys!(module(), term(), AshVault.Context.t() | nil) :: :ok

Crypto-erase scope in vault: destroy every key version and tombstone the scope.

This is irreversible. Every value encrypted under scope becomes permanently unrecoverable, and later reads raise AshVault.Errors.KeyDestroyed.

encrypt_and_set(changeset, field, value, context)

@spec encrypt_and_set(Ash.Changeset.t(), atom(), term(), AshVault.Context.t()) ::
  Ash.Changeset.t()

Encrypt value and write it to the backing attribute of field, scrubbing the plaintext from the changeset.

Returns the changeset with the error added when encryption fails, so MissingScope, KeyDestroyed and ProviderUnavailable surface as ordinary Ash errors rather than a raise inside a before_action hook.

On an update, a backing attribute that must become nil (an explicit nil with encrypt_nil?: false, or its lookup token) is written as an unconditional NULL assignment. An attribute change would be dropped whenever the caller's in-memory record already holds nil (a stale record), leaving the stored ciphertext in place.

encrypt_value(resource, field, value, context)

@spec encrypt_value(module(), atom(), term(), AshVault.Context.t()) ::
  {:ok, binary() | nil} | {:error, Exception.t()}

Encrypt one value for a field of a resource, returning the bytes to store.

Returns {:ok, nil} for a nil value on a field configured encrypt_nil?: false — that is the "store SQL NULL" case.

encrypted_field_name(field)

@spec encrypted_field_name(atom()) :: atom()

The name of the backing ciphertext attribute for an encrypted field.

This is the single place the naming scheme lives; the transformer mints the atom at compile time and every runtime lookup goes through here.

encrypted_field_name(resource_or_dsl, field)

@spec encrypted_field_name(module() | Spark.Dsl.t(), atom()) :: atom()

The backing ciphertext attribute, resolving a field's stored_as alias.

lookup_action_name(field)

@spec lookup_action_name(atom()) :: atom()

The name of the generated read action that finds rows by a searchable field's value.

lookup_field_name(field)

@spec lookup_field_name(atom()) :: atom()

The name of the deterministic lookup-token attribute for a searchable field.

As with encrypted_field_name/1, this is the single place the naming scheme lives.

rotate_key!(vault, scope, context \\ nil, opts \\ [])

@spec rotate_key!(module(), term(), AshVault.Context.t() | nil, keyword()) ::
  {:ok, non_neg_integer()}

Rotate the key for scope in vault, minting a new key version.

Existing values keep decrypting with their original key version; new writes use the new one.

Rotation does not touch lookup tokens

A searchable field's <field>_lookup token is an HMAC under the provider's lookup key, which is a separate, non-rotating, per-scope secret (AshVault.KeyProvider.lookup_key/1). Rotating the data key leaves every stored token valid and every query still matching, which is the whole point: if rotation moved the tokens, existing rows would silently stop being findable and unique? would silently stop preventing duplicates.

Changing a lookup key is therefore a backfill, not a rotation — mix ash_vault.backfill --lookup — and there is deliberately no API for it here.

Rotating the :mac keyring

opts takes purpose: :mac to rotate the scope's MAC keyring instead of its data key. New tags are minted under the new version; tags minted under older versions keep verifying, because the old versions stay fetchable. Neither keyring's rotation moves the other. See Key purposes and MACs.

scrub_plaintext(changeset, field)

@spec scrub_plaintext(Ash.Changeset.t(), atom()) :: Ash.Changeset.t()

Remove a field's plaintext from changeset.arguments and changeset.params.

Without this the plaintext survives in the changeset — and therefore in inspect output, telemetry and error reports — long after it has been encrypted.

write_attributes(resource, field, value, context)

@spec write_attributes(module(), atom(), term(), AshVault.Context.t()) ::
  {:ok, %{required(atom()) => binary() | nil}} | {:error, Exception.t()}

Every backing attribute a write of field must set: the ciphertext, plus the lookup token when the field is searchable?.

Normalization happens once, here, and the same normalized value is both encrypted and hashed. Normalizing twice would be wrong for a custom normalize: MFA that is not idempotent, and encrypting the raw value while hashing the normalized one would make the stored plaintext and the stored token disagree about what the row holds.

One consequence worth knowing: with normalize: :downcase_trim, writing " Jake@Example.COM " stores — and later decrypts to — "jake@example.com". The normalization is lossy on the encrypted column too. That is deliberate; a token that did not match the value it sits beside would be worse.