# Encryption at rest

> How the Hub encrypts data at rest with a master key and per-user keys, what is and is not encrypted, sealed key files, key rotation, and what the apps store on devices.

Source: https://docs.posternmail.app/security/encryption/

This page explains which data the Hub encrypts on disk, with which keys, where those keys
live, and what happens if you lose them. It also covers what the desktop and mobile apps
keep on your devices.

## The keys

The Hub uses two levels of keys. All encryption is AES-256-GCM, which also detects any
change to the encrypted data.

| Key | What it is | Where it lives |
|---|---|---|
| **Master key** | A random 256-bit key, created on the Hub's first start. | The key file (`POSTERN_KEY_FILE`), kept outside the data folder. |
| **User data key** | A random 256-bit key per user, created with the account. | In `hub.db` (table `user_keys`), encrypted with the master key. |

The master key encrypts the user data keys and a few Hub-wide secrets. Each user data key
encrypts that user's credentials, message files and other private data. Every encrypted item
is also bound to what it is (for example "the credentials of mailbox `mbx_123`" or "the body
of message `msg_456`"), so an encrypted value cannot be copied into another place and
decrypted there.

The key file is separate on purpose: a copy of the data folder or of a backup, without the
key file, reveals none of the encrypted data.

Where the key file is for each install method:

**Docker Compose:**
In the volume `postern_postern-key`, at `/key/hub.key` inside the container. The data is in
the separate volume `postern_postern-data` (`/data`).
**Debian and Ubuntu, Fedora and RHEL and Raspberry Pi OS:**
`/var/lib/postern-key/hub.key`, next to (not inside) the data folder `/var/lib/postern`.
Both folders have mode 0700 and belong to the `postern` user; the file has mode 0600.
**Desktop app (built-in Hub):**
`hub-key/hub.key` in the desktop app's data folder (`~/Library/Application Support/Postern`,
`%APPDATA%\Postern` or `~/.config/Postern`), next to `hub-data/`. The app creates and
manages it.

## What is encrypted

### Encrypted with the user's data key

| Data | Where |
|---|---|
| Mailbox credentials: passwords, app passwords, OAuth access and refresh tokens | `hub.db` |
| Message bodies (text and HTML) and raw messages (`.eml`) | Files under `blobs/mail/<user>/` in the data folder |
| Attachments fetched from the provider | Files under `blobs/` |
| Files you upload while writing a message | Files under `blobs/` |
| Copies of messages that rules keep ("captured mail") | Files under `blobs/` |
| TOTP secrets and passkey credentials | `hub.db` |
| Secrets for rule alerts and webhooks, and AI assist API keys | `hub.db` |
| Temporary data of a mailbox sign-in in progress (OAuth) | `hub.db` |

### Encrypted with the master key

| Secret | Name in `hub.db` (table `kv`) |
|---|---|
| Google OAuth client secret, if set in the admin panel | `secret:google_client_secret` |
| Web Push private key (VAPID) | `secret:vapid_private` |
| The image proxy's signing key | `secret:proxy_key` |
| The push relay secret | `secret:relay` |

### Protected in other ways

| Data | Protection |
|---|---|
| Hub account passwords | Argon2id hashes, not reversible. |
| Session tokens | Only a hash is stored. |
| Recovery codes | Only hashes are stored. |

### Not encrypted at the application level

These are stored in `hub.db` as they are, because the Hub needs them for lists, sorting,
search and rules:

- Message metadata: sender and recipients, subject, date, flags, folders, tags, the short
  preview text (snippet) and the `Message-ID` and reference headers.
- The search index. It does not keep the text itself, but it does hold the words of your
  messages, so it reveals what they contain.
- Drafts and messages waiting to be sent: recipients, subject and text.
- Contacts, identities and signatures, templates, rules, settings, spaces and tags.
- Device names, push tokens, the security activity log.

If someone can read `hub.db`, they learn who you write with, about what, and when. To protect
that against a stolen disk, use full-disk or volume encryption (LUKS, FileVault, BitLocker)
on the machine. See the [Hardening checklist](https://docs.posternmail.app/security/hardening/).

## While the Hub runs

The master key and the user data keys are in memory while the Hub runs. Credentials are
decrypted only when the Hub talks to a provider, and they are never logged. The web app never
receives them.

So encryption at rest protects a copy of the disk, a backup or a stolen key-less data folder.
It does not protect against someone with root access on the running machine.

## Deleting a user

Deleting a user (by the user under **Settings → Account → Delete account**, or by an admin)
deletes their data and their wrapped data key. Anything still encrypted for them anywhere
becomes unreadable ("crypto-shredding").

> [!WARNING]
> Backups made before the deletion still contain that user's wrapped data key and data.
> Together with the key file they can be restored. To fully erase a user (for example for a
> GDPR request), also delete or expire the backups that contain them. See
> [Backups](https://docs.posternmail.app/admin/backups/).

## Back up the key file

> [!CAUTION]
> Without the key file, nothing encrypted can be recovered: not the mailbox credentials, not
> the stored messages, not the attachments. Postern's backups (`postern-hub backup` and the
> scheduled ones) deliberately do **not** include it.

Keep a copy of the key file somewhere other than your data backups, for example in a password
manager or on an offline USB stick.

If the key file is missing when the Hub starts, the Hub creates a **new** key file and starts
anyway, but nothing encrypted with the old key can be read: mailboxes fail to connect,
stored messages do not open, and the log shows `web push unavailable`. If you still have the
original key file, stop the Hub at once, put the original back in place (replacing the new
one) and start it again.

If the key file is lost and you have no copy:

- Everything the Hub encrypted is unreadable for good.
- Your mail itself is not lost. It is still at your providers. Set up a new Hub (new data
  folder and key), add your mailboxes again, and the Hub syncs them again. What is lost is
  data that only the Hub had: captured mail from rules, unsent uploads, TOTP and passkey
  registrations, and anything the encrypted fields held.
- `postern-hub doctor` reports a missing key next to an existing database as `key file ...
  is missing but a database exists: restore the key file from your backup`, and a key that
  does not fit as `... does not match this database (cannot decrypt ...): wrong key file?`.

## Seal the key file with a passphrase

A plain key file protects backups of the data folder. If someone gets both the data and the
key file (a full disk image, for example), they can decrypt everything. A **sealed** key file
is itself encrypted with a passphrase (Argon2id key derivation), so a stolen key file is
useless without the passphrase.

The Hub reads the passphrase only from the environment variable `POSTERN_KEY_PASSPHRASE`.
`postern-hub serve` does not prompt for it. If the key file is sealed and the variable is
missing, the Hub stops with `vault: key file is sealed; set POSTERN_KEY_PASSPHRASE`; a wrong
one gives `vault: wrong passphrase for sealed key file`.

> [!IMPORTANT]
> Sealing only helps if the passphrase is not stored on the same disk as the key file. A
> passphrase in `hub.env` or `.env` next to it gives no extra protection.

Passphrases must be at least 12 characters. CLI commands such as `backup` or `rotate-key`
prompt for it when run in a terminal and the variable is not set; `doctor` does not, and
warns that the key file is sealed.

### Seal an existing key: rotate with `--sealed`

To seal the key of a running Hub, create a new sealed key with `rotate-key --sealed` (below).
`keygen --sealed` is for a new Hub that has no key file yet; it refuses to overwrite an
existing key.

### Start a new Hub with a sealed key

Before the first start:

**Docker Compose:**
```sh
cd ~/postern && docker compose run --rm hub keygen --sealed
```

The command prompts for the passphrase twice. To start the Hub, pass the variable through
`~/postern/compose.override.yaml`, taking the value from your shell at start time:

```yaml
services:
  hub:
    environment:
      POSTERN_KEY_PASSPHRASE: ${POSTERN_KEY_PASSPHRASE:-}
```

```sh
read -rs POSTERN_KEY_PASSPHRASE && export POSTERN_KEY_PASSPHRASE
cd ~/postern && docker compose up -d
unset POSTERN_KEY_PASSPHRASE
```

Set the variable the same way before every later `docker compose up -d`. Without it, Compose
recreates the container with an empty passphrase and the Hub stops with the sealed-key error.

Docker keeps a container's environment in its configuration on the host's disk (visible with
`docker inspect`), so on Docker a sealed key protects copies of the key volume and of
backups, but not a full image of the host's disk.
**Debian and Ubuntu, Fedora and RHEL and Raspberry Pi OS:**
```sh
sudo install -d -m 0700 -o postern -g postern /var/lib/postern-key
sudo -u postern sh -c 'set -a; . /etc/postern/hub.env; exec postern-hub keygen --sealed'
```

The command prompts for the passphrase twice. To start the Hub without writing the passphrase
to disk, hand it to systemd's memory for the start and remove it again:

```sh
read -rs PASS && sudo systemctl set-environment POSTERN_KEY_PASSPHRASE="$PASS" && unset PASS
sudo systemctl start postern-hub
sudo systemctl unset-environment POSTERN_KEY_PASSPHRASE
```

The trade-off: after a reboot, or a restart once the variable is removed, the Hub cannot start
until you do this again. `Restart=on-failure` restarts also fail while it is unset.
**Desktop app (built-in Hub):**
Not available. The desktop app's built-in Hub always uses a plain key file in its data
folder. Protect it with your computer's disk encryption and user account.

## Rotate the master key

`postern-hub rotate-key` creates a new master key, re-encrypts every user data key and every
Hub-wide secret with it, and swaps the key files. Do it if you think the key file was
exposed. With `--sealed`, the new key file is sealed with a passphrase (from
`POSTERN_KEY_PASSPHRASE`, or a prompt).

The Hub must be stopped; otherwise the command stops with "stop the Hub before rotating the
key".

**Docker Compose:**
```sh
cd ~/postern
docker compose stop hub
docker compose run --rm hub rotate-key
docker compose up -d
```

Add `--sealed` after `rotate-key` to seal the new key.
**Debian and Ubuntu, Fedora and RHEL and Raspberry Pi OS:**
```sh
sudo systemctl stop postern-hub
sudo -u postern sh -c 'set -a; . /etc/postern/hub.env; exec postern-hub rotate-key'
sudo systemctl start postern-hub
```

Add `--sealed` after `rotate-key` to seal the new key.
**Desktop app (built-in Hub):**
Not available from the desktop app.

What the command prints:

```text
✓ Rotated the master key: 4 secret(s) re-sealed, user keys re-wrapped.
  New key: /var/lib/postern-key/hub.key (old key kept as /var/lib/postern-key/hub.key.bak)
! Back up the new key file now. Older backups still need the OLD key: keep it with them.
```

> **Check:** The Hub starts, you can open a message, and `postern-hub doctor` reports the key
> file without errors.

> **If it did not work:** If the command fails halfway, its message says which file the
> database uses now (`hub.key.new` or `hub.key`). Keep both files and do not delete
> anything. If the error is `secret ... cannot be decrypted with the current key`, the key
> file in place does not belong to this database.

After a rotation:

1. Back up the new `hub.key` right away.
2. Keep the old key (`hub.key.bak`) with your older backups: they can only be restored with
   it. Then remove `hub.key.bak` from the server, or an attacker who gets the disk also gets
   the old key and every old backup is readable again.

## What the apps store on your devices

| App | What it stores | Protection |
|---|---|---|
| **Web** | Nothing beyond the browser's normal cache. | The session is an `HttpOnly` cookie, which page scripts cannot read. |
| **Desktop** | Its Hub sign-in token in `hub-tokens.json` in the app's data folder (owner-only), encrypted with the system's key storage: Keychain on macOS, DPAPI on Windows, Secret Service or KWallet on Linux. If Linux offers no real key storage, the token is kept in memory only and you sign in again after a restart. | System key storage. |
| **Desktop, direct mode** | Its own mail engine in `engine/<hub>/` in the app's data folder: a database (`engine.db`) with your synced mail and the mailbox credentials fetched from the Hub, sealed with a key file (`engine.key`) in the same folder. | Your user account and disk encryption. The engine wipes the folder when the Hub revokes the device. |
| **iOS and Android** | The session token in the iOS Keychain or Android Keystore (`expo-secure-store`, on iOS only readable after the first unlock and never moved to another device). The mail engine's folder with mail and sealed credentials in the app's private storage; on iOS it is excluded from iCloud and computer backups. | System secure storage and the app sandbox; optional app lock with Face ID, Touch ID or fingerprint. The engine wipes its data when the device is revoked. |

Revoking a device in **Settings → Devices** ends its session at once. The app deletes its
local data the next time it reaches the Hub. A device that never comes back online keeps its
local copy, so also change the passwords or revoke the app passwords of your mailboxes if a
device is stolen.
