Per-user backup

bongo backup user writes one account (its keys, grants, group memberships and every message blob) into a directory on the server, while the account stays online. bongo backup search lists messages in such a backup, and bongo restore user puts mail back (see Restore).

Commands

bongo backup user ADDRESS --to DIR
bongo backup search --from DIR --user ADDRESS [--subject S] [--sender S]
                    [--since DATE] [--until DATE] [--limit N] [--json]

Both talk to the node’s control listener (server.control_addr, loopback only), signed with web.session_secret exactly as bongo user create is. Pass --http-addr and --session-secret (or BONGO_WEB_SESSION_SECRET) the same way.

  • DIR is a path on the server’s filesystem. It must be absolute and clean (no ..), and may not be, or lie inside, storage.data_dir, cluster.raft.data_dir or storage.pebble.wal_dir (when set). Symlinks are resolved first, so a link into the data directory is refused. A missing directory is created with mode 0700; files are written with mode 0600.
  • DIR itself must be owned by the user the server runs as and must not be writable by its group or by everyone (no g+w or o+w; 0700 or 0750 are fine). Otherwise another local user could plant a blob, a key file or a manifest that a later run, search or restore would read. backup user and backup search both refuse such a directory.
  • Everything is written through a directory handle (os.Root), so a symlink placed inside the backup tree cannot lead outside it. The handle is checked to be the directory that was validated (same device and inode), so a path swapped for a symlink or another directory between the check and the open is refused. Temporary files get a random suffix and are created exclusively (O_EXCL), so a file or symlink planted at a guessed name is never written through.
  • ADDRESS is the account’s primary address or its user id.
  • One backup runs at a time per node (a second request answers 409), and a lock file .backup.lock in DIR stops two runs sharing a directory. A lock left by a crashed run is never removed automatically: the error names the file.
  • search finds the account from the manifests in DIR, never from the live store, so it works for an account that has since been deleted. It reads the newest complete backup and checks the key file against the manifest’s SHA-256 before it trusts the contents. --since and --until take RFC 3339 or YYYY-MM-DD (an --until date covers that whole day, UTC). Subject and sender are case-insensitive substrings. Results are newest first; the default limit is 100 and the maximum 1000. A manifest in DIR that cannot be read, is damaged or names another user is skipped (logged with the user id of its directory and counted in skipped_manifests of the JSON answer), so one bad file does not stop searches of other accounts.
  • Free space: a run refuses to start, and stops between blobs, when the filesystem of DIR or of the data directory is below the server’s low-disk threshold (storage.min_free_mb, the same threshold that makes the server refuse new mail). It answers 507. A stopped run writes no manifest, so search and restore ignore it; the blobs it already copied stay and are reused by the next run. With min_free_mb = 0 the check is off.

Exit codes

Command 0 non-zero
backup user the run finished with every blob copied or already present any error, or the run finished but blobs_missing or blobs_corrupt is not zero (the manifest is still written, see below)
backup search the search ran, including when the list was cut at --limit (then a notice showing N of M matches goes to stderr; stdout carries only rows) any error: no backup, a refused directory, a key file that fails its digest

Consistency

The keys are read from a Pebble snapshot taken when the run starts, so every key in one backup is from one moment and writes made during the run are not in it. This was chosen over a Pebble checkpoint: a snapshot is O(1) and needs no directory, where a checkpoint links or copies the whole server’s files. The cost is that while the run lasts Pebble keeps the files the snapshot can still see, so compaction cannot reclaim them; a very long backup on a busy node holds extra disk until it ends.

The backup reads this node’s applied state and writes nothing to Pebble, the blob store or Raft. A follower can lag the leader: run it on the leader for the latest state. The manifest records applied_index, the Raft index applied when the snapshot was taken, so the lag is visible.

The snapshot is closed as soon as the keys are read, before the first blob is copied, so Pebble holds its files only for the scan, not for the blob copy.

Blobs are read from the live blob store after the snapshot. If a message was expunged and the blob GC reclaimed its body in between, the blob is counted in blobs_missing; the backup still completes. Every copied blob is hashed while it is copied and refused (counted in blobs_corrupt, never stored) unless its SHA-256 equals its name. The log carries the counts, not the hashes.

A run with blobs_missing or blobs_corrupt above zero still writes its key file and manifest: everything else in it is good, and the counts say what is not. Restore treats such a run as partial: a message whose blob is not in DIR is skipped and counted, never restored without a body.

A blob already in DIR under its name is skipped as present only when its size equals the server’s copy; a file of another size is replaced. This is a cheap check, not a hash check: restore hashes every blob it reads and refuses one whose SHA-256 is not its name.

What is in a backup

From the snapshot, for the account with id {id}:

Content Keys
The account’s own records everything under /user/{id}/ except the three prefixes below
Address records /system/address/{address} whose owner is the account
Aliases routing to the account /system/alias/{address} whose target is its address
Grants given /acl/{calendar,mailbox,addressbook}/{id}/...
Grants held /aclrev/u:{id}/... and the forward /acl/... grant each names
Group memberships /system/groupmember/{id}/{group} and /system/group/{group}
Blobs every hash in a MailMeta raw_message and attachments (a split message’s skeleton and its attachment blobs)

The blob list uses store.MailMetaBlobHashes, the same function the blob GC uses to decide what is referenced, so the two cannot drift.

What is out, and why

  • /user/{id}/apppassword/ and /user/{id}/devicelink/: app password hashes and device-link tickets are credentials. After a restore the user creates new ones.
  • Calendar credentials (/user/{id}/calendar/{guid}): the record is kept, but publish_token (the public feed link) and publish_password_hash are cleared and published is set false, and a subscription’s source_url (which may hold a token in its path or query) is cut to its scheme and host, such as https://feeds.example. After a restore the owner publishes the calendar again (which makes a new link) and enters the feed URL of a subscription again; a restore must not fetch the cut URL as if it were the feed.
  • The sealed password of each remote-fetch account (/user/{id}/fetch/{guid}): the record is kept with credential cleared, so a restored account shows “password needed”. The fetched-message ledger (fetchseen/) is kept so that re-entering the password does not import everything again. fetchstate/ is the worker’s progress, bound to the account generation, and starts afresh.
  • An address record under /system/address/ that cannot be decoded is skipped and logged as a count (another account’s damaged record does not stop the backup). If it is the account’s own primary address record, the manifest’s records_skipped counts it, and a restore has to recreate the record.
  • DKIM keys, ACME keys, domain configuration, the domain-admin grants and the catch-all entries live under /system/ and belong to the server or domain, not to a user.
  • Grants the account reaches only through a group are the group’s, not the account’s. Group owners are not indexed, so a group the account owns but is not a member of is not found.
  • Derived indexes (SQLite, Bleve) are rebuilt from the keys and blobs.

Protect the files like the data directory

The profile is backed up whole. It holds the bcrypt password hash, the TOTP secret and the hashed recovery codes. Anyone who can read a backup can attack the password offline and can generate the account’s second factor. The backup also holds all the account’s mail in clear. Keep the directory on storage that is as well protected as storage.data_dir, on a filesystem owner the server user controls, and encrypt it if it leaves the machine.

Logs (component backup) carry the user id, counts, the applied index and the duration, never an address, folder name, subject, sender, key or blob hash. An unexpected failure is logged by its class (for example fs_open:no space left on device), not its text.

Format (version 1)

The format names logical keys and content hashes only. It does not depend on how the data directory lays out Pebble or blobs, so it survives a change to that layout.

DIR/
  .backup.lock                       held while a run is writing
  blobs/{first 2 hex}/{sha256 hex}   one file per blob, shared by every user in DIR
  users/{user id}/
    keys-{UTC timestamp}.bkv         the records of one run
    manifest-{same timestamp}.json   written last; its presence marks the run complete

The timestamp is 20060102T150405.000000000Z in UTC, so file names sort in time order and a restore can choose a run by it. A key file with no manifest (a run that crashed) is ignored. The directory is named by user id, not address, because the address can change; the manifest records it.

Write order: blobs first (each through a temporary name, fsync and rename, so a file with its final name is always whole and is never copied again), then the key file the same way, then the manifest the same way. A second backup of an unchanged account therefore copies no blobs and writes only a key file and a manifest.

Key file

The magic BONGOBK1, then records until end of file: uvarint key length, key, uvarint value length, value. Keys are Pebble keys, values are the stored bytes (protobuf for most records). Records are in a stable order. A reader bounds the key at 4 KiB and the value at 64 MiB and treats anything else, or a record cut short, as corruption.

Manifest

{
  "format_version": 1,
  "user_id": "...",
  "address": "alice@example.com",
  "created_at": "2026-11-29T15:04:05.123456789Z",
  "applied_index": 12345,
  "key_count": 20,
  "blob_count": 4,
  "blobs_copied": 4,
  "blobs_missing": 0,
  "blobs_corrupt": 0,
  "records_skipped": 0,
  "key_file": "keys-20261129T150405.123456789Z.bkv",
  "key_file_sha256": "..."
}

blob_count is the number of distinct blobs the account’s messages reference; blobs_copied is how many this run wrote (the rest were already in DIR). blobs_missing and blobs_corrupt count blobs that are not in DIR for this run, and records_skipped the account’s own records that could not be read; see Consistency for what restore does with them.

Restore

bongo restore user ADDRESS --from DIR [--at RUN|TIME] [--mailbox NAME]
                   [--messages ID,ID,...] [--mode restored|replace]
                   [--source-user ID] [--ignore-quota] [--json]
bongo restore user ADDRESS --from DIR --list

It talks to the control listener like the backup commands do (POST /internal/backup/restore and /internal/backup/runs, signed, loopback only). Run it on the leader: every write goes through Raft, and the checks for “already restored” read this node’s Pebble, which lags the leader on a follower. A follower answers 409. Upgrade every node before using replace mode without --messages (a whole account or one --mailbox), the only restore that removes anything: it uses its own expunge-by-UID command (/__mailbox_expunge_uids__/), which an older node stores as an unknown key and ignores. Nothing is removed there, so that node keeps the messages the rollback meant to remove (beside the restored copies) and its replica differs from the others; replaying the log does not repair it. No mail is lost on either side. Restored mode and replace with --messages send no such command.

What a restore trusts in the backup directory

The directory may hold planted files, so a message is restored only when every blob matches its name, the sizes recorded in the message are replaced by the verified byte counts, and its layout (the literal and attachment segments that rebuild the original) fits those blobs exactly and stays within the message size bound. A message that fails is counted skipped_corrupt. The spam score and the DKIM and SPF verdicts are kept as they were when the message first arrived, so someone who can write to the backup directory can forge them; keep it private. A run whose mail records exceed 1 GiB in total is refused with 422 (“backup run too large to restore”) before anything is written; restore one folder from a smaller run instead.

A message’s tag list is rebuilt too: names that are not a valid tag, not defined on the account, or repeated are dropped, and at most 20 tags (the per-message limit) are kept in their stored order. A record with more is not something the server writes; its message is still restored and the extra tags are dropped.

Message ids are checked against the shapes the server writes: 32 lower-case hex (restored and cross-owner copies), a lower-case UUID (delivery, journal reports, sent copies from the web), {unix nanoseconds}-{8 lower-case hex} (IMAP APPEND) and that form with a draft-, import- or welcome- prefix. --messages refuses any other id with 400. A folder entry in the key file with any other id is counted skipped_corrupt and not restored; in replace mode the live message with that id is still kept, not removed.

The account must exist, and nothing about it is restored

Restore refuses (404) an address that has no live account: create it first with bongo user create. This is deliberate. Recreating an account means address records, quota and domain checks, which bongo user create already does.

The profile record is never written back: the password hash and the authenticator secret are not restored, so there is no flag for them. Nor are app passwords, device links, fetch credentials or calendar publish tokens (the backup strips those, and restore does not invent them).

If the account was deleted and created again, it has a new user id. The backup is found by address (the manifests are read, not the live store) and restored into the new account’s keyspace. If several account directories in DIR claim the address (for example the old and the new account have both been backed up), restore answers 409; pass --source-user ID, the directory name under users/.

What is restored

Mail only: every folder and message of the run, plus the account’s tag definitions (created when the account lacks them, within the 100-tag limit; an existing tag is left alone, also one created at the same moment by someone else). A definition over the limit is not created; the restore logs how many at WARN with the user id and carries on. Any other failure to create a tag or set its colour (a Raft error, for example) stops the restore before any message is written. A message keeps a tag only if the account has a definition for it. A --mailbox or --messages restore does not create tag definitions, so a tag the account no longer has is dropped from the copy.

In the backup but not restored by this command: contacts and address books, calendars, events and tasks, rules, preferences, grants, forwarding targets, fetch accounts and group memberships. Each has its own limits and validation (five calendars, twenty books, contact-group derivation, rule order), a subscription calendar’s URL is cut down and must not be fetched, and a grant needs the other person’s consent. Read them from the key file if you need them.

Choosing the run

--list prints each run of the account in DIR (its stamp, keys, blobs, how many blobs are missing or corrupt, and whether the run is partial) and writes nothing. --at takes a run stamp or an RFC 3339 time and uses the newest run at or before it; the default is the latest. A run counts only if its manifest is present and its key file matches the manifest’s SHA-256: a run without a manifest (an unfinished backup) or with a damaged key file is passed over, and when every run is damaged the answer is 422.

Modes

restored (the default) copies each folder into a new one named Restored YYYY-MM-DD HH:MM:SS/{folder}, with the time of the run in UTC, so the whole account of one run sits under one parent folder and two runs never merge. Nothing existing is touched. A folder whose name would not be valid today (for example over 255 bytes with the prefix) is skipped and counted as skipped_invalid_name.

replace is the rollback. In order:

  1. The account is saved as a new backup run in the same directory. If that fails (low disk, the directory is locked) nothing else happens. The run stamp is printed as safety_backup. The first such run is the true pre-rollback state; a rerun saves another one.
  2. For each folder, a backed-up message that is already in the folder (same source GUID) is kept as it is, with its current flags; the others are delivered as new copies.
  3. Only after every copy is delivered, the messages that the folder held when the restore began and that are not in the backup are removed, by explicit UID. A message the user flagged \Deleted is never swept up by this: only the listed UIDs go. Mail that arrived during the restore is not in the list and stays.

A failure part way therefore leaves extra messages, never lost ones. A folder that is gone is created again with a new id, so shares of the old one stay revoked. Folders that exist now and are not in the backup are left alone. --messages with replace puts those messages back into their own folders and removes nothing. Restored messages lose \Deleted and \Recent and keep their other flags.

Safety of the backup directory

The directory may hold planted or damaged files. Every blob is opened through an os.Root, must be a regular file (a symlink is refused) no larger than the server’s maximum message size, and is hashed before the blob store sees any of it: a file whose SHA-256 is not its name is skipped as skipped_corrupt and never reaches the store or a message. A message is delivered only after all of its blobs are verified and written; a message with a missing blob is skipped_no_body. A restore never writes a message that points at a blob it does not have. Blobs and messages are written one message at a time, so a long restore cannot outlive the blob GC’s one-hour grace before a blob is referenced. A blob is not written again for a later message only once a delivered message references it; a blob written for a message that was then skipped (another of its blobs missing or bad) is unreferenced, so the next message that uses it writes it again, which restarts its grace window before the delivery refers to it.

Partial failure and reruns

Message GUIDs and folder names are derived from the run and the source: the new GUID is the first 32 hex characters of sha256("bongo-restore" NUL target user NUL run stamp NUL source GUID). Folders are created explicitly (never on first delivery, which would give them UIDVALIDITY 1). Before each folder the restore reads the target’s messages and skips every one whose derived GUID (or, in replace mode, source GUID) is already there. A restore that stops (a Raft error, low disk, a cancelled request) answers 500 with the progress so far and complete: false. Run the same command again, with --at set to the printed run stamp (a replace run saved a newer run, so “latest” would now mean that one), and it finishes without duplicates. The result lists per folder: restored, already_present, skipped_no_body, skipped_corrupt, skipped_invalid_name, expunged. The command exits non-zero when the restore is incomplete or any skipped_* count is above zero.

The “already present” check is check-then-act. One restore runs at a time per node (the same semaphore as backups, plus the directory lock), but another client delivering at the same moment is not serialised with it.

Quota

Before anything is written the restore sums the size of the blobs of the messages that are not in the target yet and asks the quota check (the per-user quota_bytes and the domain limit). The figure it compares with is the one the leader last computed, which can be up to ten minutes old. Over the limit the restore is refused with 422 and writes nothing, unless --ignore-quota is given; that is logged with the user id and the byte count. A failing quota check fails the restore.

Logs

backup: restore ... lines carry the user id and counts, never an address, folder name, tag name, subject or hash. Errors are logged by class, and the error_class in a partial result’s body is the same class as the log line.

View this page's source on GitHub