# `Strongbox.Rotation`
[🔗](https://github.com/hattoriai/strongbox/blob/v0.1.0-dev/lib/strongbox/rotation.ex#L1)

Rotating keys: what is still under the old ones, and writing it again
under the new.

Put the new key first in the vault's `c:Strongbox.keys/0`, keep the old
ones after it, and deploy. New values are written under the new key and
the old ones still decrypt. Then:

    Strongbox.Rotation.report(MyApp.Repo, MyApp.User)
    #=> %{email: %{"k2" => 1_204, "k1" => 88_311, nil => 12}, ...}

    Strongbox.Rotation.run(MyApp.Repo, MyApp.User)
    #=> {:ok, %{rewritten: 88_311, reindexed: 0, conflicts: 0, unreadable: 0}}

Once `report/3` shows nothing under a key, remove it from the vault.

`run/3` goes through the table in batches, in the order of its primary
key, and writes again each value whose key or format isn't the first
key's. It can be stopped and run again: it only writes what is stale.
Each write is a compare-and-swap: a row changed since it was read isn't
written (it counts as a conflict, and the change already used the new
key), so `run/3` is safe beside the app's own writes. Run it from a
release task or a background job.

Blind indexes are hashed again when the first index key changes:
`run/3` reads each indexed field, and writes its index if its hash under
the first index key isn't the one stored. Lookups with
`Strongbox.Query.where_index/3` find rows under any index key meanwhile.

It needs a schema with a single primary key.

# `summary`

```elixir
@type summary() :: %{
  rewritten: non_neg_integer(),
  reindexed: non_neg_integer(),
  conflicts: non_neg_integer(),
  unreadable: non_neg_integer()
}
```

# `report`

```elixir
@spec report(Ecto.Repo.t(), module(), keyword()) :: %{
  required(atom()) =&gt; %{
    required(binary() | nil | :unreadable) =&gt; non_neg_integer()
  }
}
```

Counts the values of each encrypted field of `schema` by the tag of the
key they were written with. `nil` counts the rows where the field is
`nil`; `:unreadable`, values that aren't in any known format.

Options: `:fields`, the encrypted fields to count (all by default);
`:batch_size`, 1000 by default.

# `run`

```elixir
@spec run(Ecto.Repo.t(), module(), keyword()) :: {:ok, summary()}
```

Writes again the values of `schema` that aren't under the first key, and
hashes again the blind indexes that aren't under the first index key.

Returns `{:ok, summary}`: how many values were `rewritten`, how many
indexes `reindexed`, how many rows changed meanwhile (`conflicts`, left
as they are), and how many values none of the keys decrypt
(`unreadable`, left as they are).

Options:

  * `:fields` - the encrypted fields to rotate, all by default.
  * `:indexes` - whether to hash blind indexes again, `true` by default.
  * `:batch_size` - rows read at a time, 500 by default.

---

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