# `AshVault.Macaroon.CaveatCodec`
[🔗](https://github.com/jakeschurch/ash_vault/blob/main/lib/ash_vault/macaroon/caveat_codec.ex#L1)

The frozen, self-describing byte encoding of one caveat.

    caveat := name_len::8  name  tag::8  value

`name` is 1–63 bytes of `[a-z][a-z0-9_]*`. `tag` and `value`:

| tag    | type                                    | value bytes                                 |
| ------ | --------------------------------------- | ------------------------------------------- |
| `0x01` | `:string`                               | `len::16 utf8`                              |
| `0x02` | `:integer`                              | `signed-big-64`                             |
| `0x03` | `:boolean`                              | `0x00` or `0x01`                            |
| `0x04` | `:utc_datetime`, `:utc_datetime_usec`   | unix microseconds, `signed-big-64`          |
| `0x05` | `{:array, :string}`                     | `count::8` then `count` × `len::16 utf8`    |
| `0x06` | `{:array, :integer}`                    | `count::8` then `count` × `signed-big-64`   |

Self-describing so that `AshVault.Macaroon.attenuate/2` can append a caveat without
knowing the resource it is for; the verifier then checks each decoded tag against the
type the `caveat` entity declares and fails closed on any disagreement.

Decoding is strict: the value must consume the caveat exactly, strings must be valid
UTF-8, and the decoded value must re-encode to the identical bytes. There is exactly
one encoding of any caveat, so no two byte strings mean the same thing.

# `tag`

```elixir
@type tag() ::
  :string | :integer | :boolean | :datetime | :string_list | :integer_list
```

# `value`

```elixir
@type value() ::
  binary() | integer() | boolean() | DateTime.t() | [binary()] | [integer()]
```

# `decode`

```elixir
@spec decode(binary()) :: {:ok, {binary(), tag(), value()}} | :error
```

Decode one caveat into `{name, tag, value}`, strictly. `:error` for anything that is
not the unique canonical encoding of a caveat.

# `encode`

```elixir
@spec encode(binary(), tag(), value()) :: {:ok, binary()} | {:error, atom()}
```

Encode one caveat. `{:error, reason}` for a name, value or size outside the format.

# `infer_tag`

```elixir
@spec infer_tag(term()) :: {:ok, tag()} | :error
```

The tag an Elixir value encodes under, inferred from its shape. Used by `attenuate/2`,
which has no declaration to consult.

# `max_caveat_bytes`

```elixir
@spec max_caveat_bytes() :: pos_integer()
```

The largest encoded caveat accepted, in bytes: 256.

# `tag_for_type`

```elixir
@spec tag_for_type(term()) :: {:ok, tag()} | :error
```

The value tag an Ash type encodes under, or `:error` for a type with no stable encoding.

---

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