AshVault.Cipher behaviour (AshVault v0.2.0)

Copy Markdown View Source

Behaviour for AEAD ciphers, plus the registry used to resolve a cipher id read out of a stored envelope.

A cipher is identified by a stable atom id (for example :aes_256_gcm_v1) which is written into every envelope as a binary. Decryption looks the cipher back up through fetch/1, so the cipher a value was encrypted with is always the cipher used to decrypt it — even if the vault has since been configured with a different default.

Additional ciphers can be registered (binary-keyed, like the built-ins):

config :ash_vault, :ciphers, %{"my_cipher_v1" => MyApp.Ciphers.Custom}

Summary

Callbacks

Decrypt a payload under key, verifying it against aad.

Encrypt plaintext under key, binding aad into the authentication tag.

The stable identifier written into envelopes.

The exact key size, in bytes, this cipher requires.

Functions

Look up a cipher module by id.

The full binary-keyed cipher registry: built-in ciphers merged with configured ones.

Types

payload()

@type payload() :: %{ciphertext: binary(), nonce: binary(), tag: binary()}

Callbacks

decrypt(payload, key, aad)

@callback decrypt(payload(), key :: AshVault.Key.t(), aad :: binary()) ::
  {:ok, binary()} | {:error, :opaque_key_unsupported} | {:error, term()}

Decrypt a payload under key, verifying it against aad.

Takes the same AshVault.Key.t() union as encrypt/3.

encrypt(plaintext, key, aad)

@callback encrypt(plaintext :: binary(), key :: AshVault.Key.t(), aad :: binary()) ::
  {:ok, payload()} | {:error, :opaque_key_unsupported} | {:error, term()}

Encrypt plaintext under key, binding aad into the authentication tag.

key is an AshVault.Key.t(), which is a raw binary for every cipher and provider AshVault ships, and may also be an opaque %AshVault.Key{} handle to material held outside the BEAM heap. A cipher that cannot use a handle returns {:error, :opaque_key_unsupported}; it must never fall back to anything else.

id()

@callback id() :: atom()

The stable identifier written into envelopes.

key_bytes()

@callback key_bytes() :: pos_integer()

The exact key size, in bytes, this cipher requires.

Functions

fetch(id)

@spec fetch(atom() | binary()) :: {:ok, module()} | {:error, Exception.t()}

Look up a cipher module by id.

The registry is keyed by the binary id, which is exactly what the envelope stores, so the encode and decode directions cannot drift. An atom id is converted with Atom.to_string/1; untrusted input is never turned into an atom.

Examples

AshVault.Cipher.fetch(:aes_256_gcm_v1)
#=> {:ok, AshVault.Ciphers.AES.GCM}

AshVault.Cipher.fetch("aes_256_gcm_v1")
#=> {:ok, AshVault.Ciphers.AES.GCM}

AshVault.Cipher.fetch("nope")
#=> {:error, %AshVault.Errors.UnsupportedCipher{cipher_id: "nope"}}

registry()

@spec registry() :: %{optional(binary()) => module()}

The full binary-keyed cipher registry: built-in ciphers merged with configured ones.