---
title: "reencrypt"
description: "The re-encryption sweep: its three subcommands, the database role it needs, what its output means, and when a retired key is safe to remove."
---

The second half of a `TOKEN_ENCRYPTION_KEY` rotation. Adding a new key makes new
writes use it; `reencrypt` rewrites the rows still sealed under the old one.
Until it reports nothing left, the old key has to stay in
`TOKEN_ENCRYPTION_KEYS_PREVIOUS`.

The same pass rewrites ciphertext stored before values were
[bound to their row](/deployment/key-rotation#row-binding), including rows
already on the current key. A deployment that has never rotated a key still has
that work to do once.

```text
backend/cmd/reencrypt
```

This page is the command reference. For the whole procedure, in order, see
[Rotate the encryption key](/deployment/key-rotation).

## Synopsis

```bash
reencrypt report
reencrypt plan
reencrypt apply
reencrypt --version
```

Exactly one argument. No argument, more than one, or an unrecognised word exits
non-zero with a usage message. The binary's own messages call it
`trustowl-reencrypt`; in the image it is installed as `/app/reencrypt`.

## Subcommands

| Command | Effect |
|---|---|
| `report` | Counts the stored ciphertext by column and key version, how many of those rows are not yet bound to their record, and says whether previous keys can be retired. Changes nothing |
| `plan` | Runs the sweep without writing: reads and decrypts rows that are on an old version or unbound, and reports what `apply` would rewrite |
| `apply` | Rewrites every row that is on an old version or unbound, under the current key and bound to its row; ciphertext and version column together in one statement |

`apply` is idempotent. A row already on the current version and bound is skipped
rather than re-sealed, so a second run rewrites nothing, and an interrupted run is
finished by running it again.

`plan` proves the keys work before anything is written: it decrypts with the
old key and seals with the new one, and discards the result. It reads a single
batch of 500 rows per column (per organization, for the tenant tables), so on a
large table its counts are a floor rather than a total. `report` has the exact
counts.

## What it sweeps

Eight columns, each opened and re-sealed with the key derived for its own
purpose:

| Column | What it holds |
|---|---|
| `users.github_access_token` | A linked GitHub account's OAuth token |
| `webhook_endpoints.secret_encrypted` | A webhook endpoint's signing secret |
| `webhook_endpoints.previous_secret_encrypted` | The signing secret being rotated out |
| `org_identity_providers.secrets_encrypted` | Single sign-on client secrets |
| `user_mfa_factors.secret_encrypted` | Customers' TOTP seeds |
| `registry_credentials.secret_encrypted` | Stored credentials of every kind: registry, git, cloud and Kubernetes |
| `notification_targets.secret_encrypted` | Notification destination secrets |
| `staff_users.mfa_secret_encrypted` | Support-console staff TOTP seeds |

Queued mail and notifications (`mail_outbox.payload_encrypted`) are not swept.
A queued message is delivered or abandoned within the dispatcher's retry
schedule, so there is no standing backlog to rewrite.

## The role it must run as

The sweep reads every organization's rows. Row-level security does not raise an
error when it hides a row; it returns nothing. A role the policies filter would
therefore count zero rows on the old key and tell you the key is safe to
delete.

`reencrypt` refuses to start in that position. Before `report`, `plan` or
`apply` does anything, it checks that the connected role is one of:

- a superuser or a role with `BYPASSRLS`, or
- a role covered by the `tenant_isolation_maintenance` policy, which the
  migrations create for the role that ran them.

In practice: give it the same `DATABASE_URL` that `migrate` uses, not the
application's login role. With the application role it exits non-zero and names
the role.

## Environment it reads

`reencrypt` loads the full API configuration, so that the keys it uses are
exactly the keys the application uses. That means it needs everything the API
needs to start, including `JWT_SECRET` outside development, and it fails on
the same invalid settings.

| Variable | Effect |
|---|---|
| `DATABASE_URL` | Required. The schema owner, as above |
| `TOKEN_ENCRYPTION_KEY` | The current key. Rows are rewritten under it |
| `TOKEN_ENCRYPTION_KEY_VERSION` | The version new ciphertext is stamped with. Default `1` |
| `TOKEN_ENCRYPTION_KEYS_PREVIOUS` | The retired keys, as `version:hexkey` pairs. Needed to open the rows being rewritten |
| `SECRETS_REQUIRE_BOUND` | When `true`, `plan` and `apply` refuse unbound ciphertext instead of upgrading it, and `report` words an unbound row as an anomaly. Default `false` |
| `DB_MAX_OPEN_CONNS`, `DB_MAX_IDLE_CONNS` | Pool size, as for the API |

`DB_STATEMENT_TIMEOUT` and `DB_IDLE_IN_TRANSACTION_TIMEOUT` are ignored here.
A sweep over every organization legitimately runs longer than a request may, so
the command opens its pool with both bounds removed.

## Reading the output

`report` prints one line per column and version:

```text
COLUMN                                   KEY VERSION  ROWS  UNBOUND
users.github_access_token                1            14    14  <- not yet re-encrypted
webhook_endpoints.secret_encrypted       2            9     4
registry_credentials.secret_encrypted    1            3     3   <- not yet re-encrypted

current key version: 2
17 row(s) still need `trustowl-reencrypt apply`. Do NOT remove anything from TOKEN_ENCRYPTION_KEYS_PREVIOUS yet.
21 row(s) are NOT bound to their record and could be copied between rows. `trustowl-reencrypt apply` rewrites them. Leave SECRETS_REQUIRE_BOUND off until this reads 0.
```

It gives two verdicts, and they are independent. When no row is on an old key
it says `every row is on the current key: previous keys can now be retired.`
When no row is unbound it says `every row is bound to its record:
SECRETS_REQUIRE_BOUND can be switched on.` A database holding no ciphertext at
all prints `no stored ciphertext`.

`plan` and `apply` print one line per swept column:

```text
COLUMN                                 SCANNED  REWRITTEN  UNREADABLE
users.github_access_token              14       14         0
webhook_endpoints.secret_encrypted     9        0          0
```

The table is printed even when the run fails part-way, because a sweep that
stopped on the fourth column still finished three.

**`UNREADABLE` is the column to watch.** It counts rows the sweep could not
open. Those rows are left exactly as they are, never rewritten and never
deleted, and the command exits non-zero. There are three causes:

- No key this process holds opens the row: a key was retired before the sweep
  ran. Restore it to `TOKEN_ENCRYPTION_KEYS_PREVIOUS` and run again.
- The ciphertext was sealed for a different row. It does not belong where it
  is. Find out how it got there before doing anything else.
- `SECRETS_REQUIRE_BOUND` is on and the row is in the unbound format.

## Running it

<Tabs>
  <Tab title="Production Compose">
    The shipped file has a `reencrypt` service in the `maintenance` profile. It
    never starts with `up`, and it connects as the owner through
    `MIGRATION_DATABASE_URL`:

    ```bash
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt report
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt plan
    docker compose -f infra/docker/docker-compose.prod.yml --env-file infra/docker/.env \
      run --rm reencrypt apply
    ```

    The service receives only the variables the compose file names. The two
    rotation variables are among them; `SECRETS_REQUIRE_BOUND` is not, at this
    release. See
    [Production Compose](/installation/production-compose#which-variables-reach-the-containers).
  </Tab>
  <Tab title="Published image">
    ```bash
    docker run --rm --env-file rotation.env --entrypoint /app/reencrypt \
      ghcr.io/trustivan/trustivan-backend:v1.0.0 report
    ```

    `rotation.env` carries the same configuration the API runs with, with
    `DATABASE_URL` replaced by the schema owner's.
  </Tab>
  <Tab title="From source">
    ```bash
    cd backend
    GOEXPERIMENT=jsonv2 go run ./cmd/reencrypt report
    ```

    The binary loads `../.env` if present, which is what makes it work from
    `backend/` in development.
  </Tab>
</Tabs>

## Exit status

| Result | Exit |
|---|---|
| `report`, whatever it found | `0` |
| `plan` or `apply` with no unreadable rows | `0` |
| Any unreadable row | non-zero |
| Wrong role, invalid configuration, or a database error | non-zero |

`report` exiting `0` is not the signal that a key can be retired. Its last line
is.

## Related

- [Rotate the encryption key](/deployment/key-rotation): the procedure this
  command is one step of.
- [`migrate`](/cli-reference/migrate): the other command that runs as the
  schema owner.
- [Environment variables](/configuration/environment#encryption-key-rotation):
  the rotation variables and what startup refuses.
