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

The implementation behind every module that `use`s `AshVault.Vault`.

Generated vault modules are one-line delegations into this module, passing their
compile-time configuration as an opts map. Keeping the logic here (rather than in the
`use` macro) keeps generated code tiny, stack traces readable, and this code testable
on its own.

All functions here take `opts`, a map with the `:key_provider`, `:cipher`, `:envelope`,
`:scope` and `:rotation_policy` modules, and — for `mac!/3` and `verify_mac!/5` — the
`:mac` module. `:vault`, when present, labels telemetry.

# `opts`

```elixir
@type opts() :: %{
  :key_provider =&gt; module(),
  :cipher =&gt; module(),
  :envelope =&gt; module(),
  :scope =&gt; module(),
  :rotation_policy =&gt; module(),
  optional(:mac) =&gt; module(),
  optional(:vault) =&gt; module()
}
```

# `build_aad`

```elixir
@spec build_aad(term(), AshVault.Context.t()) :: binary()
```

Build the additional authenticated data bound into every ciphertext.

The format is frozen:

    "ashvault:v1|" <> scope <> "|" <> inspect(resource) <> "|" <> field

It is a stable, human-inspectable binary rather than `:erlang.term_to_binary/1`,
because term encoding is not guaranteed stable across OTP releases and ciphertext must
outlive OTP upgrades. Binding scope, resource and field means a value cannot be
replayed into a different tenant, resource or column.

# `current_mac_version!`

```elixir
@spec current_mac_version!(AshVault.Context.t(), opts()) :: pos_integer()
```

The current version of the scope's `:mac` keyring, minting the keyring on first use.

What `mac_at!/4` needs to sign under the current key, and what a verifier compares a
stated version against to decide whether that version is still accepted. Raises
`AshVault.Errors.KeyDestroyed` for an erased scope, `AshVault.Errors.PurposeUnsupported`
when the provider has no `:mac` keyring and `AshVault.Errors.ProviderUnavailable` for an
outage. Never returns key material.

# `decrypt!`

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

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

The cipher is resolved from the envelope, not from the vault's configured default, so
values keep decrypting after the default cipher changes.

Raises `AshVault.Errors.InvalidCiphertext` or `AshVault.Errors.UnsupportedEnvelope` for
unparseable input, `AshVault.Errors.KeyDestroyed` for crypto-erased scopes,
`AshVault.Errors.KeyNotFound` for unknown key versions, and
`AshVault.Errors.CiphertextIntegrityFailed` when the tag does not verify.

# `destroy!`

```elixir
@spec destroy!(term(), opts()) :: :ok
```

Destroy every key for a scope (crypto-erasure), raising on provider failure.

Returns only once the provider has confirmed the destruction.

# `encrypt!`

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

Encrypt `plaintext` for the given context, returning an encoded envelope.

Raises `AshVault.Errors.MissingScope` if the scope cannot be resolved, and
`AshVault.Errors.ProviderUnavailable` / `AshVault.Errors.KeyDestroyed` if the key
provider cannot supply a current key.

# `mac!`

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

Compute a MAC over `data` for a context, under the scope's current `:mac` key.

Returns `{key_version, tag}`: `tag` is the raw bytes `AshVault.Mac.c:mac/3` produced,
and `key_version` is what `verify_mac!/5` needs back. The tag is bound to the scope,
resource and field through the same associated data `encrypt!/3` uses
(`build_aad/2`), so a tag minted for one tenant, resource or field never verifies for
another.

The scope's `:mac` keyring is minted on first use. Raises
`AshVault.Errors.KeyDestroyed` for an erased scope, `AshVault.Errors.PurposeUnsupported`
when the provider has no `:mac` keyring, and `AshVault.Errors.ProviderUnavailable` for
an outage.

Emits `[:ash_vault, :mac, :sign]`; see `AshVault.Telemetry`.

# `mac_at!`

```elixir
@spec mac_at!(binary(), term(), AshVault.Context.t(), opts()) :: binary()
```

Compute a MAC over `data` under one **stated** version of the scope's `:mac` keyring.

`mac!/3` always signs under the current version; this is its version-pinned sibling,
for a caller that must recompute a tag at the version a credential names — a macaroon
verifier recomputes its root signature this way, then compares the result itself.

The key is fetched exactly as `verify_mac!/5` fetches it, so the taxonomy is the same:
`AshVault.Errors.KeyDestroyed` (the scope was erased — revoked), `AshVault.Errors.KeyNotFound`
(no such version, including a non-integer one — invalid) and
`AshVault.Errors.ProviderUnavailable` (retry; nothing was decided). It never mints a
keyring: a version that does not exist is `KeyNotFound`, not a fresh key.

Emits `[:ash_vault, :mac, :sign]` with the stated `key_version`.

# `map_provider_error`

```elixir
@spec map_provider_error(term(), term(), AshVault.Context.t()) :: Exception.t()
```

Map a key provider's raw error term onto an AshVault error struct.

# `resolve_scope!`

```elixir
@spec resolve_scope!(AshVault.Context.t(), module(), atom()) :: binary()
```

Resolve `scope_module` against `ctx`, enforcing the scope invariant.

One place enforces it, so a custom `AshVault.Scope` that returns a non-binary fails
here with a clear message rather than differently in each provider — a provider's own
`validate_scope!/1` would raise a bare `ArgumentError` naming the provider, which tells
an operator nothing about the scope module that actually produced the bad term.

Public because the lookup-token path (`AshVault.Lookup.field_key/3`) resolves a scope
outside `encrypt!/3` and `decrypt!/3` and must reach the same check.

Raises `AshVault.Errors.InvalidScope` for a non-binary, and re-raises
`AshVault.Errors.MissingScope` tagged with `operation`.

# `rotate!`

```elixir
@spec rotate!(term(), opts()) :: {:ok, non_neg_integer()}
```

Rotate the `:data` key for a scope, raising on provider failure.

# `rotate!`

```elixir
@spec rotate!(term(), AshVault.KeyProvider.purpose(), opts()) ::
  {:ok, non_neg_integer()}
```

Rotate a scope's keyring for `purpose`, raising on provider failure.

`:data` calls the provider's `c:AshVault.KeyProvider.rotate/1`, exactly as `rotate!/2`
always has. A purpose the provider does not serve raises
`AshVault.Errors.PurposeUnsupported` — a configuration fault, never reported as an
outage.

# `verify_mac!`

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

Verify a tag produced by `mac!/3`, returning `:ok` or raising.

The key is fetched **before** the tag is looked at, so the answer about the key always
wins over the answer about the tag:

  * `AshVault.Errors.KeyDestroyed` — the scope was erased. Every tag it issued is
    revoked, however valid it once was.
  * `AshVault.Errors.KeyNotFound` — `key_version` does not exist (including a
    non-integer one).
  * `AshVault.Errors.ProviderUnavailable` — the provider could not answer. Retryable,
    and never reported as an invalid tag.
  * `AshVault.Errors.InvalidMac` — everything was found and the tag is wrong: tampered,
    forged, paired with the wrong version, or minted under another scope, resource or
    field.

Comparison is constant-time (`AshVault.Macs.HmacSha256`) or done by OpenBao
(`AshVault.Macs.OpenBaoTransit`). Emits `[:ash_vault, :mac, :verify]`.

---

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