# `AshVault.Vault`
[🔗](https://github.com/jakeschurch/ash_vault/blob/main/lib/ash_vault/vault.ex#L1)

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

  * `:key_provider` — **required**, an `AshVault.KeyProvider`
  * `:cipher` — an `AshVault.Cipher`, defaults to `AshVault.Ciphers.AES.GCM`
  * `:mac` — an `AshVault.Mac` for `mac!/2` and `verify_mac!/4`. Defaults to
    `AshVault.Macs.OpenBaoTransit` when the key provider is
    `AshVault.KeyProviders.OpenBaoTransit` (whose keys never leave OpenBao), and to
    `AshVault.Macs.HmacSha256` otherwise. See [Key purposes and MACs](key-purposes-and-macs.md).
  * `:envelope` — an `AshVault.Envelope`, defaults to `AshVault.Envelope.V1`
  * `:scope` — an `AshVault.Scope`, defaults to `AshVault.Scopes.AshTenant`
  * `:rotation_policy` — an `AshVault.RotationPolicy`, defaults to
    `AshVault.RotationPolicies.Manual`
  * `:otp_app` — the OTP application whose config key this vault's key provider may be
    configured under. Defaults to the application the vault module is compiled into,
    which is almost always what you want; see below.
  * `:cache` — wrap the key provider in `AshVault.KeyProviders.Cached`. **Defaults to
    `false`** and should stay that way unless you mean it; see below.

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 (`c: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 — `c:AshVault.KeyProvider.child_spec/1`
and `c: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](two-vaults.md) for the worked pattern and the one
hazard it carries.

# `__ash_vault__`

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

Introspect the vault's compile-time configuration.

# `child_specs`

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

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

# `decrypt!`

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

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

# `destroy!`

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

Crypto-erase every key for a scope.

# `encrypt!`

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

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

# `mac!`

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

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

# `mac_at!`
*optional* 

```elixir
@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!`
*optional* 

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

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

# `rotate!`

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

Rotate the `:data` key for a scope.

# `rotate!`

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

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

# `setup`

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

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

# `verify_mac!`

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

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

# `compiling_otp_app`

```elixir
@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`

```elixir
@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!`

```elixir
@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!`

```elixir
@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!`

```elixir
@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!`

```elixir
@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!`

```elixir
@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`:

  * the provider is compiled and its `c:AshVault.KeyProvider.purposes/0` does not list
    `:mac`;
  * `AshVault.Macs.OpenBaoTransit` over any provider but
    `AshVault.KeyProviders.OpenBaoTransit`, or `AshVault.Macs.HmacSha256` over it — the
    handle and the MAC would not understand each other.

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.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
