AshVault.Vault behaviour (AshVault v0.2.0)

Copy Markdown View Source

Defines a vault: the bundle of key provider, cipher, envelope, scope and rotation policy that an application encrypts with.

defmodule MyApp.Vault do
  use AshVault.Vault, key_provider: MyApp.KeyProvider
end

MyApp.Vault.encrypt!("secret", %AshVault.Context{
  resource: MyApp.User,
  field: :ssn,
  ash_context: %{tenant: "acme"}
})

Options

The generated module is a thin set of delegations to AshVault.Vault.Runtime.

MACs

Besides encrypting, a vault authenticates: mac!/2 returns {key_version, tag} under the scope's :mac keyring, verify_mac!/4 checks one, and rotate!(scope, purpose: :mac) rotates that keyring without touching the data keys. destroy!/1 revokes every tag the scope ever issued, because it destroys the :mac keyring with everything else.

{version, tag} = MyApp.Vault.mac!("payload", ctx)
:ok = MyApp.Vault.verify_mac!("payload", version, tag, ctx)

The :mac keyring needs a provider that serves it (AshVault.KeyProvider.purposes/0). Every provider AshVault ships does. With an explicit mac: option, a provider that is already compiled and does not is a compile error here; without one, a vault over such a provider still compiles — it never MACs until asked to — and mac!/2 raises AshVault.Errors.PurposeUnsupported.

Caching keys

A key cache weakens crypto-erasure from immediate to eventual-within-a-TTL for any erasure that does not go through this vault, so it is opt-in:

# safe defaults: 30s TTL, 1024 entries, the pure-Elixir ETS backend
use AshVault.Vault, key_provider: MyApp.Keys, cache: true

# tuned
use AshVault.Vault,
  key_provider: MyApp.Keys,
  cache: [ttl: :timer.seconds(10), max_entries: 4_096,
          backend: AshVaultRustler.KeyCache]

# the wrapper itself, when a cached provider needs to be named and shared
use AshVault.Vault,
  key_provider: {AshVault.KeyProviders.Cached,
                 provider: AshVault.KeyProviders.OpenBao, ttl: 10_000}

All three forms desugar to the same thing: a module named MyApp.Vault.CachedKeyProvider, generated here, implementing AshVault.KeyProvider and wrapping yours. __ash_vault__(:key_provider) reports that wrapper, and it must be added to your supervision tree because it owns the cache:

children = [MyApp.Vault.CachedKeyProvider]

:backend selects the cache implementation. The default, AshVault.KeyCaches.ETS, is pure Elixir and needs nothing installed, but cannot zero key material on eviction — it drops a reference and the garbage collector decides the rest. AshVaultRustler.KeyCache keeps the authoritative copy outside the BEAM heap and zeroes it on Drop. cache: true never requires the NIF.

Read AshVault.KeyProviders.Cached before enabling this. The short version: the TTL is the maximum time a destroyed tenant stays decryptable when the erasure happened out of band, and erasures routed through this vault are evicted synchronously on every connected node before destroy!/1 returns.

Caching AshVault.KeyProviders.Memory is refused with a warning — it is already an in-memory map, so a cache in front of it is a second copy and a second eviction path for no benefit.

Starting and setting up the key provider

Providers differ in what they need before they can serve a key — AshVault.KeyProviders.Local wants a supervised process and an initialised key root, AshVault.KeyProviders.OpenBao wants no process and a mounted KV engine, AshVault.KeyProviders.Memory wants a process and nothing else — and a host application should not have to know which. The vault does, so it answers for its provider:

# lib/my_app/application.ex
children = [MyApp.Repo] ++ MyApp.Vault.child_specs()

# a deploy step, a release command, or `mix my_app.setup`
:ok = MyApp.Vault.setup()

child_specs/0 includes the generated CachedKeyProvider when cache: is set, and the provider underneath it when that one is supervised too, innermost first. setup/0 returns :ok for a provider that needs none. Neither is a case you write.

Both rest on optional AshVault.KeyProvider callbacks — AshVault.KeyProvider.child_spec/1 and AshVault.KeyProvider.setup/0 — so a third-party provider that defines neither keeps working unchanged and simply contributes nothing.

Where provider configuration lives

Key provider configuration is per provider module, and may be written under your own OTP application:

config :my_app, AshVault.KeyProviders.OpenBao, address: "http://127.0.0.1:8200"

use AshVault.Vault records the OTP application this vault module is compiled into and registers it when the module loads, which is what lets AshVault.KeyProvider.config/1 find that key. Pass otp_app: to name a different one. The original form, config :ash_vault, AshVault.KeyProviders.OpenBao, ..., still works and is the base the host application's config is merged over.

One vault per application

A vault is resolved at compile time, deliberately: it is what makes verify_key_sizes!/2 possible at all, and it keeps the four provider call sites in AshVault.Vault.Runtime to a plain module call. There is no runtime provider switch, and one vault per application is the shape this is built for.

When you genuinely need two — demonstrating two providers, or migrating between them — define two vault modules and resolve between them with the fun/2 vault form the DSL already accepts. See Two vaults in one application for the worked pattern and the one hazard it carries.

Summary

Callbacks

Introspect the vault's compile-time configuration.

The child specifications this vault's key provider needs supervised.

Decrypt an encoded envelope for a context, returning the plaintext.

Crypto-erase every key for a scope.

Encrypt a plaintext for a context, returning an encoded envelope.

Compute a MAC over data for a context, returning {key_version, tag}.

Compute a MAC over data under a stated :mac key version, returning the raw tag.

The current :mac key version for a context's scope. Optional, like mac_at!/3.

Rotate the :data key for a scope.

Rotate a scope's keyring for a purpose: rotate!(scope, purpose: :mac).

Run the operator setup step this vault's key provider needs, if it has one.

Verify a tag from mac!/2, returning :ok or raising.

Functions

The OTP application a vault module is being compiled into.

The default AshVault.Mac for a key provider: AshVault.Macs.OpenBaoTransit over AshVault.KeyProviders.OpenBaoTransit, whose :mac keys are opaque handles, and AshVault.Macs.HmacSha256 over everything else.

Define the vault's CachedKeyProvider module, or return the provider unchanged.

The purpose a rotate!/2 keyword list names: :data unless purpose: says otherwise.

Resolve the :cache option (and the {Cached, opts} wrapper form) into {inner_provider, cache_opts | nil}.

Compile-time guard: the key provider's key size must match the cipher's.

Compile-time guard for an explicitly configured mac:.

Callbacks

__ash_vault__(arg1)

@callback __ash_vault__(
  :key_provider
  | :cipher
  | :mac
  | :envelope
  | :scope
  | :rotation_policy
) :: module()

Introspect the vault's compile-time configuration.

child_specs()

@callback child_specs() :: [module()]

The child specifications this vault's key provider needs supervised.

decrypt!(binary, t)

@callback decrypt!(binary(), AshVault.Context.t()) :: binary()

Decrypt an encoded envelope for a context, returning the plaintext.

destroy!(scope)

@callback destroy!(scope :: term()) :: :ok

Crypto-erase every key for a scope.

encrypt!(binary, t)

@callback encrypt!(binary(), AshVault.Context.t()) :: binary()

Encrypt a plaintext for a context, returning an encoded envelope.

mac!(binary, t)

@callback mac!(binary(), AshVault.Context.t()) :: {pos_integer(), binary()}

Compute a MAC over data for a context, returning {key_version, tag}.

mac_at!(binary, pos_integer, t)

(optional)
@callback mac_at!(binary(), pos_integer(), AshVault.Context.t()) :: binary()

Compute a MAC over data under a stated :mac key version, returning the raw tag.

Optional, so a hand-written vault that predates it keeps compiling; every vault built with use AshVault.Vault has it, and AshVault.Macaroon requires it.

mac_key_version!(t)

(optional)
@callback mac_key_version!(AshVault.Context.t()) :: pos_integer()

The current :mac key version for a context's scope. Optional, like mac_at!/3.

rotate!(scope)

@callback rotate!(scope :: term()) :: {:ok, non_neg_integer()}

Rotate the :data key for a scope.

rotate!(scope, opts)

@callback rotate!(scope :: term(), opts :: keyword()) :: {:ok, non_neg_integer()}

Rotate a scope's keyring for a purpose: rotate!(scope, purpose: :mac).

setup()

@callback setup() :: :ok | {:error, term()}

Run the operator setup step this vault's key provider needs, if it has one.

verify_mac!(binary, term, term, t)

@callback verify_mac!(binary(), term(), term(), AshVault.Context.t()) :: :ok

Verify a tag from mac!/2, returning :ok or raising.

Functions

compiling_otp_app()

@spec compiling_otp_app() :: atom() | nil

The OTP application a vault module is being compiled into.

Used as the default for the :otp_app option, so that config :my_app, AshVault.KeyProviders.OpenBao, ... works with no further ceremony. Returns nil outside a Mix build — in which case only config :ash_vault, AshVault.KeyProviders.OpenBao, ... and an explicit config :ash_vault, otp_app: :my_app are consulted.

default_mac(provider)

@spec default_mac(module()) :: module()

The default AshVault.Mac for a key provider: AshVault.Macs.OpenBaoTransit over AshVault.KeyProviders.OpenBaoTransit, whose :mac keys are opaque handles, and AshVault.Macs.HmacSha256 over everything else.

define_cache_module!(vault, provider, cache_opts, location)

@spec define_cache_module!(module(), module(), keyword() | nil, keyword()) :: module()

Define the vault's CachedKeyProvider module, or return the provider unchanged.

Generating a real module (rather than teaching AshVault.Vault.Runtime to dispatch on a {module, opts} tuple) keeps the runtime's four provider call sites exactly as they are: a cached provider is an ordinary AshVault.KeyProvider module like any other.

purpose!(opts)

@spec purpose!(keyword()) :: AshVault.KeyProvider.purpose()

The purpose a rotate!/2 keyword list names: :data unless purpose: says otherwise.

Raises ArgumentError for anything but :data or :mac, and for unknown options, so a typo such as purpos: :mac cannot quietly rotate the data key instead.

resolve_cache!(vault, key_provider, opts, location \\ [])

@spec resolve_cache!(module(), term(), keyword(), keyword()) ::
  {module(), keyword() | nil}

Resolve the :cache option (and the {Cached, opts} wrapper form) into {inner_provider, cache_opts | nil}.

Returning the inner provider separately matters: verify_key_sizes!/2 has to keep seeing the provider the user actually configured. Pointing it at the generated wrapper would aim a compile-time check at a module that is mid-definition, and the wrapper's key_bytes/0 is a delegation anyway.

nil for the second element means no wrapping at all — which is what cache: false, an omitted :cache, and cache: true over AshVault.KeyProviders.Memory all produce, so those three are indistinguishable downstream.

verify_key_sizes!(vault, map)

@spec verify_key_sizes!(module(), map()) :: :ok

Compile-time guard: the key provider's key size must match the cipher's.

Called from the use AshVault.Vault macro. AshVault.KeyProvider.key_bytes/1 had zero callers, so a key_bytes: 16 in config, an OpenBao key_type: "aes128-gcm96", or a truncated key file on disk all reached the cipher unchecked — and were then reported as two different lies: AshVault.Errors.CiphertextIntegrityFailed on decrypt ("your data was tampered with", for a config typo) and a retryable AshVault.Errors.ProviderUnavailable naming the cipher as the provider on encrypt.

The check is deliberately conservative. It fires only when it can positively determine a mismatch: both modules must already be compiled and both must export key_bytes/0. A provider whose size depends on runtime configuration — AshVault.KeyProviders.OpenBao reads :key_type through AshVault.KeyProvider.config/1, which operators set in runtime.exs — cannot be settled at compile time, and a provider module may not even be compiled yet when the vault macro expands. Anything unresolvable passes here; AshVault.Vault.Runtime raises AshVault.Errors.KeySizeMismatch at the point of use, which is what actually carries the guarantee.

verify_mac_pairing!(vault, map)

@spec verify_mac_pairing!(module(), map()) :: :ok

Compile-time guard for an explicitly configured mac:.

Fires only when it can positively determine a fault, like verify_key_sizes!/2:

A vault with no mac: option is never checked here: existing vaults over third-party providers keep compiling, and AshVault.Errors.PurposeUnsupported is the runtime answer if one of them is ever asked to MAC.