forge
Explore
Log in

Don't you dare go Hollow

Backup manifest authenticated with HMAC keyed from iz.key

Browse files at this commit

0982f5fecdc93d7a6297ad687ed2d98bd9c048e9Ahmet Kaan GümüşParent: 34f693b
  • fix
    • backup manifest authenticated with HMAC keyed from iz.key
Show full message
🔒 fix: backup manifest authenticated with HMAC keyed from iz.key
Cargo.lockmodified+1 -0
@@ -1877,6 +1877,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
18771877 name = "iz-core"
18781878 version = "0.1.0"
18791879 dependencies = [
1880+ "aws-lc-rs",
18801881 "base64 0.23.1",
18811882 "bytes",
18821883 "calamine",
README.mdmodified+5 -3
@@ -139,9 +139,11 @@ With a `[backup]` section, iz writes a backup set into `dir` every `interval_hou
139139
140140 - `iz.db`: a consistent copy of the database,
141141 - `attachments/`: the local attachment files,
142-- `manifest.json`: a SHA-256 for each file.
142+- `manifest.json`: a SHA-256 for each file, and
143+- `manifest.mac`: an HMAC-SHA256 of `manifest.json`, keyed from `iz.key`.
143144
144-Backups do not copy `iz.key`. Keep that copy separately, as described in First run.
145+Backups do not copy `iz.key`. Keep that copy separately, as described in First run. A set can only be checked
146+and restored with the same `iz.key` that wrote it; a set without a valid `manifest.mac` is refused.
145147
146148 Restore with the server stopped:
147149
@@ -151,7 +153,7 @@ iz restore --from /var/lib/iz/backups/<set dir>
151153 sudo systemctl start iz
152154 ```
153155
154-`iz restore` checks the set against `manifest.json` before it writes anything. A set that fails the
156+`iz restore` checks the set's `manifest.mac`, then the files against `manifest.json`, before it writes anything. A set that fails the
155157 check is not restored. Do not copy the live database file by hand: it is written while iz runs.
156158
157159 ## Command line
crates/iz-core/Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ publish = false
1010 workspace = true
1111
1212 [dependencies]
13+aws-lc-rs.workspace = true
1314 base64.workspace = true
1415 bytes.workspace = true
1516 calamine.workspace = true
crates/iz-core/src/manifest.rsmodified+76 -26
@@ -8,15 +8,18 @@
88 //! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or
99 //! names another version, is refused too.
1010 //!
11-//! The manifest only detects changes to the set: someone who rewrites files and the manifest together
12-//! is not caught. Keeping the backup directory readable only by the service user is the protection
13-//! against that.
11+//! The manifest is authenticated. `manifest.mac` next to it holds the HMAC-SHA256 of the exact bytes of
12+//! `manifest.json`, keyed by a subkey of the instance key (`iz.key`, which lives outside the set). The
13+//! MAC is checked before the manifest is parsed or any listed file is read, so someone who can write to
14+//! the backup directory cannot change a file and its manifest consistently. Without the instance key a
15+//! set is refused. A set written before the MAC existed is refused too.
1416
1517 use std::collections::BTreeSet;
1618 use std::fs::File;
1719 use std::io::Read;
1820 use std::path::{Component, Path, PathBuf};
1921
22+use aws_lc_rs::hmac;
2023 use serde::{Deserialize, Serialize};
2124 use sha2::{Digest, Sha256};
2225
@@ -24,10 +27,17 @@ use crate::error::{Error, Result};
2427
2528 /// The file name of the manifest inside a set.
2629 pub const MANIFEST_NAME: &str = "manifest.json";
30+/// The file name of the MAC of the manifest inside a set: lowercase hex of the 32-byte HMAC-SHA256.
31+pub const MAC_NAME: &str = "manifest.mac";
2732 /// The only manifest version this build reads and writes.
2833 pub const MANIFEST_VERSION: u32 = 1;
2934 /// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours.
3035 pub const MANIFEST_MAX_BYTES: u64 = 16 * 1024 * 1024;
36+/// Largest MAC file read, in bytes. Reason: the MAC is 64 hex digits; anything larger is not ours.
37+pub const MAC_MAX_BYTES: u64 = 256;
38+/// The label that derives the manifest subkey from the instance key. Reason: a distinct label keeps this
39+/// key separate from any other use of the instance key.
40+const MAC_LABEL: &[u8] = b"iz backup manifest v1";
3141
3242 /// One file of a set.
3343 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -70,6 +80,14 @@ pub fn digest_file(path: &Path) -> Result<(u64, String)> {
7080 Ok((size, hex::encode(hasher.finalize())))
7181 }
7282
83+/// The HMAC key for manifests: `HMAC-SHA256(instance key, MAC_LABEL)`, used as the key of the manifest MAC.
84+/// Using a derived subkey means the instance key itself is never the MAC key.
85+pub fn manifest_key(instance_key: &[u8; 32]) -> hmac::Key {
86+ let master = hmac::Key::new(hmac::HMAC_SHA256, instance_key);
87+ let subkey = hmac::sign(&master, MAC_LABEL);
88+ hmac::Key::new(hmac::HMAC_SHA256, subkey.as_ref())
89+}
90+
7391 /// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty
7492 /// component, no NUL or backslash.
7593 pub fn is_safe_relative(path: &str) -> bool {
@@ -82,11 +100,13 @@ pub fn is_safe_relative(path: &str) -> bool {
82100 .all(|component| matches!(component, Component::Normal(_)))
83101 }
84102
85-/// Writes `manifest.json` into `dir` with the given files. Each listed file must already exist in
86-/// `dir` and is hashed here, so the manifest describes what is on disk. The manifest is written to a
87-/// temporary name and renamed into place, so a crash leaves either no manifest or a whole one.
103+/// Writes `manifest.json` and `manifest.mac` into `dir` with the given files. Each listed file must already
104+/// exist in `dir` and is hashed here, so the manifest describes what is on disk. Both files are written to
105+/// a temporary name and renamed into place, the manifest first and the MAC last, so a crash leaves a set
106+/// without a MAC, which the verifier refuses.
88107 pub fn write_manifest(
89108 dir: &Path,
109+ instance_key: &[u8; 32],
90110 created_at: &str,
91111 build: &str,
92112 paths: &[String],
@@ -113,17 +133,25 @@ pub fn write_manifest(
113133 };
114134 let json = serde_json::to_vec_pretty(&manifest)
115135 .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?;
116- let tmp = dir.join(format!("{MANIFEST_NAME}.tmp"));
117- std::fs::write(&tmp, json)?;
118- File::open(&tmp)?.sync_all()?;
119- std::fs::rename(&tmp, dir.join(MANIFEST_NAME))?;
136+ let tag = hmac::sign(&manifest_key(instance_key), &json);
137+ write_synced(dir, MANIFEST_NAME, &json)?;
138+ write_synced(dir, MAC_NAME, hex::encode(tag.as_ref()).as_bytes())?;
120139 Ok(manifest)
121140 }
122141
123-/// Reads and checks a set. Returns the manifest when every listed file matches its size and digest and
124-/// no other file sits in the set. Errors name the first problem found.
125-pub fn verify_set(dir: &Path) -> Result<Manifest> {
126- let manifest = read_manifest(&dir.join(MANIFEST_NAME))?;
142+/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place.
143+fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> {
144+ let tmp = dir.join(format!("{name}.tmp"));
145+ std::fs::write(&tmp, bytes)?;
146+ File::open(&tmp)?.sync_all()?;
147+ std::fs::rename(&tmp, dir.join(name))?;
148+ Ok(())
149+}
150+
151+/// Reads and checks a set. The manifest's MAC is checked first; then every listed file must match its
152+/// size and digest, and no other file may sit in the set. Errors name the first problem found.
153+pub fn verify_set(dir: &Path, instance_key: &[u8; 32]) -> Result<Manifest> {
154+ let manifest = read_manifest(dir, instance_key)?;
127155 let mut listed = BTreeSet::new();
128156 for file in &manifest.files {
129157 if !is_safe_relative(&file.path) {
@@ -152,22 +180,26 @@ pub fn verify_set(dir: &Path) -> Result<Manifest> {
152180 let mut on_disk = BTreeSet::new();
153181 collect_files(dir, dir, &mut on_disk)?;
154182 on_disk.remove(MANIFEST_NAME);
183+ on_disk.remove(MAC_NAME);
155184 if let Some(extra) = on_disk.difference(&listed).next() {
156185 return Err(refused(format!("not listed in the manifest: {extra}")));
157186 }
158187 Ok(manifest)
159188 }
160189
161-/// Reads the manifest with its size limit and checks its version.
162-pub fn read_manifest(path: &Path) -> Result<Manifest> {
163- let meta = std::fs::symlink_metadata(path)
190+/// Reads the manifest of the set in `dir`. The MAC is checked against the exact bytes read, in constant
191+/// time, before those bytes are parsed. Then the version is checked.
192+pub fn read_manifest(dir: &Path, instance_key: &[u8; 32]) -> Result<Manifest> {
193+ let bytes = read_regular(&dir.join(MANIFEST_NAME), MANIFEST_MAX_BYTES)
164194 .map_err(|_| refused("the set has no manifest".to_owned()))?;
165- if !meta.file_type().is_file() || meta.len() > MANIFEST_MAX_BYTES {
166- return Err(refused(
167- "the manifest is not a regular file of a sane size".to_owned(),
168- ));
169- }
170- let bytes = std::fs::read(path)?;
195+ let mac = read_regular(&dir.join(MAC_NAME), MAC_MAX_BYTES)
196+ .map_err(|_| refused("the manifest has no MAC".to_owned()))?;
197+ let tag = std::str::from_utf8(&mac)
198+ .ok()
199+ .and_then(|text| hex::decode(text.trim_end()).ok())
200+ .ok_or_else(|| refused("the manifest MAC is not valid hex".to_owned()))?;
201+ hmac::verify(&manifest_key(instance_key), &bytes, &tag)
202+ .map_err(|_| refused("the manifest does not match its MAC".to_owned()))?;
171203 let manifest: Manifest = serde_json::from_slice(&bytes)
172204 .map_err(|e| refused(format!("the manifest is not valid: {e}")))?;
173205 if manifest.version != MANIFEST_VERSION {
@@ -179,6 +211,18 @@ pub fn read_manifest(path: &Path) -> Result<Manifest> {
179211 Ok(manifest)
180212 }
181213
214+/// The bytes of a regular file that is not a link and is at most `max` bytes long.
215+fn read_regular(path: &Path, max: u64) -> Result<Vec<u8>> {
216+ let meta = std::fs::symlink_metadata(path)?;
217+ if !meta.file_type().is_file() || meta.len() > max {
218+ return Err(Error::Invalid(format!(
219+ "not a regular file of a sane size: {}",
220+ path.display()
221+ )));
222+ }
223+ Ok(std::fs::read(path)?)
224+}
225+
182226 /// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other
183227 /// non-regular entries are refused, so a set cannot hide a file behind a link.
184228 fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet<String>) -> Result<()> {
@@ -236,20 +280,26 @@ mod tests {
236280 #[test]
237281 fn a_tampered_file_or_an_extra_file_is_refused() {
238282 let dir = tempfile::tempdir().expect("temp dir");
283+ let key = [3u8; 32];
239284 std::fs::write(dir.path().join("iz.db"), b"one").expect("write");
240285 write_manifest(
241286 dir.path(),
287+ &key,
242288 "2026-10-28T00:00:00.000000000Z",
243289 "t",
244290 &["iz.db".into()],
245291 )
246292 .expect("manifest");
247- verify_set(dir.path()).expect("a fresh set verifies");
293+ verify_set(dir.path(), &key).expect("a fresh set verifies");
294+ assert!(
295+ verify_set(dir.path(), &[4u8; 32]).is_err(),
296+ "another key is refused"
297+ );
248298
249299 std::fs::write(dir.path().join("iz.db"), b"two").expect("tamper");
250- assert!(verify_set(dir.path()).is_err());
300+ assert!(verify_set(dir.path(), &key).is_err());
251301 std::fs::write(dir.path().join("iz.db"), b"one").expect("restore");
252302 std::fs::write(dir.path().join("extra"), b"x").expect("extra");
253- assert!(verify_set(dir.path()).is_err());
303+ assert!(verify_set(dir.path(), &key).is_err());
254304 }
255305 }
crates/iz-core/src/secret.rsmodified+3 -1
@@ -49,7 +49,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
4949 Ok(key)
5050 }
5151
52-fn read_key(path: &Path) -> Result<[u8; 32]> {
52+/// Reads an existing instance key at `path` without creating it. Refused like [`load_or_create_key`]
53+/// when the file is group or world accessible or has the wrong length.
54+pub fn read_key(path: &Path) -> Result<[u8; 32]> {
5355 #[cfg(unix)]
5456 {
5557 use std::os::unix::fs::PermissionsExt;
crates/iz-web/src/backup.rsmodified+20 -10
@@ -4,7 +4,7 @@
44 //!
55 //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a
66 //! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and
7-//! `manifest.json` written last (`iz_core::manifest`). A set is built in `.tmp-<ulid>` and renamed to its
7+//! `manifest.json` and `manifest.mac` written last (`iz_core::manifest`), the MAC keyed by the instance key. A set is built in `.tmp-<ulid>` and renamed to its
88 //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed.
99 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever
1010 //! deleted. Nothing is written in place.
@@ -87,7 +87,7 @@ async fn run_once(
8787 };
8888 let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id()));
8989 let outcome = tokio::select! {
90- result = write_set(&state.store, &state.config.data_dir, &tmp, &created_at) => result,
90+ result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result,
9191 _ = stop.wait_for(|stopped| *stopped) => {
9292 Err(Error::Io(std::io::Error::other("stopped before the set was finished")))
9393 }
@@ -114,9 +114,15 @@ async fn run_once(
114114 }
115115 }
116116
117-/// Writes the files of one set into `tmp` and the manifest last. Returns the number of files listed, not
118-/// counting the manifest. The caller removes `tmp` on error.
119-async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str) -> Result<usize> {
117+/// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files
118+/// listed, not counting the manifest. The caller removes `tmp` on error.
119+async fn write_set(
120+ store: &Store,
121+ data_dir: &Path,
122+ instance_key: &[u8; 32],
123+ tmp: &Path,
124+ created_at: &str,
125+) -> Result<usize> {
120126 create_dir(tmp, false)?;
121127 store.snapshot_to(&tmp.join(DB_FILE)).await?;
122128 let mut paths = vec![DB_FILE.to_owned()];
@@ -135,9 +141,12 @@ async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str)
135141 let dir = tmp.to_owned();
136142 let created = created_at.to_owned();
137143 let build = env!("IZ_BUILD_SHA").to_owned();
138- tokio::task::spawn_blocking(move || manifest::write_manifest(&dir, &created, &build, &paths))
139- .await
140- .map_err(|error| Error::Io(std::io::Error::other(error)))??;
144+ let key = *instance_key;
145+ tokio::task::spawn_blocking(move || {
146+ manifest::write_manifest(&dir, &key, &created, &build, &paths)
147+ })
148+ .await
149+ .map_err(|error| Error::Io(std::io::Error::other(error)))??;
141150 Ok(files)
142151 }
143152
@@ -235,12 +244,13 @@ mod tests {
235244 let store = Store::open(&dir.path().join("iz.db")).await.expect("store");
236245 let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id()));
237246 let created = "2026-10-28T09:30:00.000000000Z";
238- write_set(&store, dir.path(), &tmp, created)
247+ let key = [6u8; 32];
248+ write_set(&store, dir.path(), &key, &tmp, created)
239249 .await
240250 .expect("set written");
241251 publish(&tmp, dir.path(), "20261028T093000Z").expect("published");
242252 let published = dir.path().join("20261028T093000Z");
243- let verified = manifest::verify_set(&published).expect("the set verifies");
253+ let verified = manifest::verify_set(&published, &key).expect("the set verifies");
244254 assert_eq!(verified.created_at, created);
245255 assert!(verified.files.iter().any(|file| file.path == DB_FILE));
246256 assert!(!tmp.exists(), "the temporary name is gone after the rename");
crates/iz-web/src/boot.rsmodified+1 -1
@@ -29,7 +29,7 @@ use crate::security::{self, SecurityHeaders};
2929 use crate::state::AppState;
3030
3131 /// Name of the instance key file inside the data directory.
32-const KEY_FILE: &str = "iz.key";
32+pub const KEY_FILE: &str = "iz.key";
3333 /// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals.
3434 const DEFAULT_KEY_PREFIX: &str = "IZ";
3535
crates/iz-web/src/cli/export.rsmodified+14 -5
@@ -3,7 +3,7 @@
33 //!
44 //! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity,
55 //! attachment metadata and the members named by those rows), `attachments/<id>` for every attachment whose
6-//! bytes are on this disk, and `manifest.json` for all of them. An attachment whose bytes are elsewhere
6+//! bytes are on this disk, and `manifest.json` with its `manifest.mac` (HMAC under the instance key) for all of them. An attachment whose bytes are elsewhere
77 //! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing
88 //! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing
99 //! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No
@@ -22,7 +22,7 @@ use iz_core::store::export::{AttachmentRow, ReadOnly};
2222 use iz_core::time::now_stamp;
2323 use sha2::{Digest, Sha256};
2424
25-use super::{database_file, describe, existing_data_dir, fail, take_lock};
25+use super::{database_file, describe, existing_data_dir, fail, instance_key, take_lock};
2626
2727 /// The file that holds the board.
2828 const BOARD_FILE: &str = "board.json";
@@ -45,10 +45,14 @@ pub async fn run(config_path: &Path, out: &Path) -> ExitCode {
4545 Ok(lock) => lock,
4646 Err(code) => return code,
4747 };
48+ let key = match instance_key(&data_dir) {
49+ Ok(key) => key,
50+ Err(message) => return fail(message),
51+ };
4852 if let Err(message) = prepare_out(out) {
4953 return fail(message);
5054 }
51- match write_export(&config, &data_dir, out).await {
55+ match write_export(&config, &data_dir, out, &key).await {
5256 Ok(report) => {
5357 println!(
5458 "exported {} attachments with bytes and {} without to {}",
@@ -104,7 +108,12 @@ fn prepare_out(out: &Path) -> Result<(), String> {
104108
105109 /// Reads the database and writes the export. Every failure before the manifest leaves the directory
106110 /// partly written; the caller reports it and the operator removes it.
107-async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result<Report, String> {
111+async fn write_export(
112+ config: &Config,
113+ data_dir: &Path,
114+ out: &Path,
115+ key: &[u8; 32],
116+) -> Result<Report, String> {
108117 let database = database_file(config)?;
109118 let db = ReadOnly::open(&database)
110119 .await
@@ -187,7 +196,7 @@ async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result<Re
187196 .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?;
188197 write_new(&out.join(BOARD_FILE), &bytes)?;
189198
190- write_manifest(out, &now_stamp(), env!("IZ_BUILD_SHA"), &written)
199+ write_manifest(out, key, &now_stamp(), env!("IZ_BUILD_SHA"), &written)
191200 .map_err(|error| describe(&error))?;
192201 Ok(report)
193202 }
crates/iz-web/src/cli/mod.rsmodified+16 -0
@@ -22,6 +22,9 @@ use std::process::ExitCode;
2222
2323 use clap::{Parser, Subcommand};
2424 use iz_core::config::Config;
25+use iz_core::secret;
26+
27+use crate::boot::KEY_FILE;
2528
2629 /// The file inside the data directory that carries the process lock.
2730 pub const LOCK_FILE: &str = "iz.lock";
@@ -133,6 +136,19 @@ pub fn existing_data_dir(config: &Config) -> Result<PathBuf, String> {
133136 })
134137 }
135138
139+/// The instance key read from the data directory. It must exist: the commands that call this check or write
140+/// manifests under it, and never create a key on the way.
141+pub fn instance_key(data_dir: &Path) -> Result<[u8; 32], String> {
142+ let path = data_dir.join(KEY_FILE);
143+ secret::read_key(&path).map_err(|error| {
144+ format!(
145+ "the instance key {} cannot be used: {}",
146+ path.display(),
147+ describe(&error)
148+ )
149+ })
150+}
151+
136152 /// The database path, checked to be a regular file that is not a link. Nothing is created.
137153 pub fn database_file(config: &Config) -> Result<PathBuf, String> {
138154 let meta = std::fs::symlink_metadata(&config.database).map_err(|error| {
crates/iz-web/src/cli/restore.rsmodified+25 -8
@@ -1,6 +1,7 @@
11 //! `iz restore --from <set dir>`: replaces the database and the attachments with a verified backup set.
22 //!
3-//! Order: verify the set with `manifest::verify_set`; check that the configured database is a regular file
3+//! Order: verify the set with `manifest::verify_set`, which checks the manifest's MAC under the instance key before
4+//! it trusts the manifest; check that the configured database is a regular file
45 //! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data
56 //! directory and check each copy against the manifest; run `integrity_check` and the migration check on the
67 //! staged database. Nothing outside the staging directory changes until then. Only after that are the current
@@ -21,7 +22,7 @@ use iz_core::staging::{ATTACHMENTS_DIR, blob_path};
2122 use iz_core::store::export::{ReadOnly, migrations_problem};
2223 use iz_core::store::new_id;
2324
24-use super::{describe, existing_data_dir, fail, file_stamp, take_lock};
25+use super::{describe, existing_data_dir, fail, file_stamp, instance_key, take_lock};
2526
2627 /// The database file name inside a backup set. Fixed: the set writer uses this name too.
2728 const SET_DB: &str = "iz.db";
@@ -50,7 +51,11 @@ pub async fn run(config_path: &Path, from: &Path) -> ExitCode {
5051 Ok(lock) => lock,
5152 Err(code) => return code,
5253 };
53- match restore(&config, &data_dir, from).await {
54+ let key = match instance_key(&data_dir) {
55+ Ok(key) => key,
56+ Err(message) => return fail(message),
57+ };
58+ match restore(&config, &data_dir, from, &key).await {
5459 Ok(summary) => {
5560 println!("{summary}");
5661 ExitCode::SUCCESS
@@ -241,8 +246,13 @@ async fn check_staged(staged_db: &Path) -> Result<(), String> {
241246 }
242247
243248 /// The whole restore. Returns the summary line on success.
244-async fn restore(config: &Config, data_dir: &Path, from: &Path) -> Result<String, String> {
245- let manifest = manifest::verify_set(from).map_err(|error| describe(&error))?;
249+async fn restore(
250+ config: &Config,
251+ data_dir: &Path,
252+ from: &Path,
253+ key: &[u8; 32],
254+) -> Result<String, String> {
255+ let manifest = manifest::verify_set(from, key).map_err(|error| describe(&error))?;
246256 let attachment_ids = plan_set(&manifest)?;
247257 let db_target = database_target(config, data_dir)?;
248258 let attachments_dir = data_dir.join(ATTACHMENTS_DIR);
@@ -416,11 +426,13 @@ mod tests {
416426 let data = root.path().join("data");
417427 std::fs::create_dir_all(&set).expect("set dir");
418428 std::fs::create_dir_all(&data).expect("data dir");
429+ let key = [5u8; 32];
419430 let db = data.join("iz.db");
420431 std::fs::write(&db, b"current database").expect("current db");
421432 std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db");
422433 write_manifest(
423434 &set,
435+ &key,
424436 "2026-10-28T00:00:00.000000000Z",
425437 "test",
426438 &[SET_DB.to_owned()],
@@ -437,9 +449,14 @@ mod tests {
437449 data.display(),
438450 ))
439451 .expect("config");
440- let error = restore(&config, &data.canonicalize().expect("canonical"), &set)
441- .await
442- .expect_err("tampered set must be refused");
452+ let error = restore(
453+ &config,
454+ &data.canonicalize().expect("canonical"),
455+ &set,
456+ &key,
457+ )
458+ .await
459+ .expect_err("tampered set must be refused");
443460 assert!(
444461 error.contains("changed since the set was written"),
445462 "got: {error}"
docs/architecture.mdmodified+6 -1
@@ -218,7 +218,12 @@ manifest, and never writes outside `DIR`. `iz restore --from SET` verifies a bac
218218 database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the
219219 configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes
220220 read-only. Every command except `export` refuses while a server holds `data_dir/iz.lock`. Backups are written by
221-the `[backup]` worker (`VACUUM INTO` plus attachment copies and `manifest.json`, see `iz_core::manifest`).
221+the `[backup]` worker (`VACUUM INTO` plus attachment copies, `manifest.json` and `manifest.mac`, see `iz_core::manifest`).
222+A set's manifest is authenticated: `manifest.mac` is the HMAC-SHA256 of the exact bytes of `manifest.json`, keyed by
223+`HMAC-SHA256(iz.key, "iz backup manifest v1")`. `verify_set` checks the MAC in constant time before it parses the
224+manifest or reads a listed file, so a set changed in place (file and manifest together) is refused. `export` writes
225+the same pair, and `restore` and `export` need the existing `iz.key` (they never create one). A set written before
226+the MAC existed is refused.
222227
223228 ---
224229