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"
1877 name = "iz-core"1877 name = "iz-core"
1878 version = "0.1.0"1878 version = "0.1.0"
1879 dependencies = [1879 dependencies = [
1880+ "aws-lc-rs",
1880 "base64 0.23.1",1881 "base64 0.23.1",
1881 "bytes",1882 "bytes",
1882 "calamine",1883 "calamine",
README.mdmodified+5 -3
@@ -139,9 +139,11 @@ With a `[backup]` section, iz writes a backup set into `dir` every `interval_hou
139 139
140 - `iz.db`: a consistent copy of the database,140 - `iz.db`: a consistent copy of the database,
141 - `attachments/`: the local attachment files,141 - `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`.
143 144
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.
145 147
146 Restore with the server stopped:148 Restore with the server stopped:
147 149
@@ -151,7 +153,7 @@ iz restore --from /var/lib/iz/backups/<set dir>
151 sudo systemctl start iz153 sudo systemctl start iz
152 ```154 ```
153 155
154-`iz restore` checks the set against `manifest.json` before it writes anything. A set that fails the156+`iz restore` checks the set's `manifest.mac`, then the files against `manifest.json`, before it writes anything. A set that fails the
155 check is not restored. Do not copy the live database file by hand: it is written while iz runs.157 check is not restored. Do not copy the live database file by hand: it is written while iz runs.
156 158
157 ## Command line159 ## Command line
crates/iz-core/Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ publish = false
10 workspace = true10 workspace = true
11 11
12 [dependencies]12 [dependencies]
13+aws-lc-rs.workspace = true
13 base64.workspace = true14 base64.workspace = true
14 bytes.workspace = true15 bytes.workspace = true
15 calamine.workspace = true16 calamine.workspace = true
crates/iz-core/src/manifest.rsmodified+76 -26
@@ -8,15 +8,18 @@
8 //! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or8 //! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or
9 //! names another version, is refused too.9 //! names another version, is refused too.
10 //!10 //!
11-//! The manifest only detects changes to the set: someone who rewrites files and the manifest together11+//! The manifest is authenticated. `manifest.mac` next to it holds the HMAC-SHA256 of the exact bytes of
12-//! is not caught. Keeping the backup directory readable only by the service user is the protection12+//! `manifest.json`, keyed by a subkey of the instance key (`iz.key`, which lives outside the set). The
13-//! against that.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.
14 16
15 use std::collections::BTreeSet;17 use std::collections::BTreeSet;
16 use std::fs::File;18 use std::fs::File;
17 use std::io::Read;19 use std::io::Read;
18 use std::path::{Component, Path, PathBuf};20 use std::path::{Component, Path, PathBuf};
19 21
22+use aws_lc_rs::hmac;
20 use serde::{Deserialize, Serialize};23 use serde::{Deserialize, Serialize};
21 use sha2::{Digest, Sha256};24 use sha2::{Digest, Sha256};
22 25
@@ -24,10 +27,17 @@ use crate::error::{Error, Result};
24 27
25 /// The file name of the manifest inside a set.28 /// The file name of the manifest inside a set.
26 pub const MANIFEST_NAME: &str = "manifest.json";29 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";
27 /// The only manifest version this build reads and writes.32 /// The only manifest version this build reads and writes.
28 pub const MANIFEST_VERSION: u32 = 1;33 pub const MANIFEST_VERSION: u32 = 1;
29 /// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours.34 /// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours.
30 pub const MANIFEST_MAX_BYTES: u64 = 16 * 1024 * 1024;35 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";
31 41
32 /// One file of a set.42 /// One file of a set.
33 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]43 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -70,6 +80,14 @@ pub fn digest_file(path: &Path) -> Result<(u64, String)> {
70 Ok((size, hex::encode(hasher.finalize())))80 Ok((size, hex::encode(hasher.finalize())))
71 }81 }
72 82
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+
73 /// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty91 /// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty
74 /// component, no NUL or backslash.92 /// component, no NUL or backslash.
75 pub fn is_safe_relative(path: &str) -> bool {93 pub fn is_safe_relative(path: &str) -> bool {
@@ -82,11 +100,13 @@ pub fn is_safe_relative(path: &str) -> bool {
82 .all(|component| matches!(component, Component::Normal(_)))100 .all(|component| matches!(component, Component::Normal(_)))
83 }101 }
84 102
85-/// Writes `manifest.json` into `dir` with the given files. Each listed file must already exist in103+/// Writes `manifest.json` and `manifest.mac` into `dir` with the given files. Each listed file must already
86-/// `dir` and is hashed here, so the manifest describes what is on disk. The manifest is written to a104+/// exist in `dir` and is hashed here, so the manifest describes what is on disk. Both files are written to
87-/// temporary name and renamed into place, so a crash leaves either no manifest or a whole one.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.
88 pub fn write_manifest(107 pub fn write_manifest(
89 dir: &Path,108 dir: &Path,
109+ instance_key: &[u8; 32],
90 created_at: &str,110 created_at: &str,
91 build: &str,111 build: &str,
92 paths: &[String],112 paths: &[String],
@@ -113,17 +133,25 @@ pub fn write_manifest(
113 };133 };
114 let json = serde_json::to_vec_pretty(&manifest)134 let json = serde_json::to_vec_pretty(&manifest)
115 .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?;135 .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?;
116- let tmp = dir.join(format!("{MANIFEST_NAME}.tmp"));136+ let tag = hmac::sign(&manifest_key(instance_key), &json);
117- std::fs::write(&tmp, json)?;137+ write_synced(dir, MANIFEST_NAME, &json)?;
118- File::open(&tmp)?.sync_all()?;138+ write_synced(dir, MAC_NAME, hex::encode(tag.as_ref()).as_bytes())?;
119- std::fs::rename(&tmp, dir.join(MANIFEST_NAME))?;
120 Ok(manifest)139 Ok(manifest)
121 }140 }
122 141
123-/// Reads and checks a set. Returns the manifest when every listed file matches its size and digest and142+/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place.
124-/// no other file sits in the set. Errors name the first problem found.143+fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> {
125-pub fn verify_set(dir: &Path) -> Result<Manifest> {144+ let tmp = dir.join(format!("{name}.tmp"));
126- let manifest = read_manifest(&dir.join(MANIFEST_NAME))?;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)?;
127 let mut listed = BTreeSet::new();155 let mut listed = BTreeSet::new();
128 for file in &manifest.files {156 for file in &manifest.files {
129 if !is_safe_relative(&file.path) {157 if !is_safe_relative(&file.path) {
@@ -152,22 +180,26 @@ pub fn verify_set(dir: &Path) -> Result<Manifest> {
152 let mut on_disk = BTreeSet::new();180 let mut on_disk = BTreeSet::new();
153 collect_files(dir, dir, &mut on_disk)?;181 collect_files(dir, dir, &mut on_disk)?;
154 on_disk.remove(MANIFEST_NAME);182 on_disk.remove(MANIFEST_NAME);
183+ on_disk.remove(MAC_NAME);
155 if let Some(extra) = on_disk.difference(&listed).next() {184 if let Some(extra) = on_disk.difference(&listed).next() {
156 return Err(refused(format!("not listed in the manifest: {extra}")));185 return Err(refused(format!("not listed in the manifest: {extra}")));
157 }186 }
158 Ok(manifest)187 Ok(manifest)
159 }188 }
160 189
161-/// Reads the manifest with its size limit and checks its version.190+/// Reads the manifest of the set in `dir`. The MAC is checked against the exact bytes read, in constant
162-pub fn read_manifest(path: &Path) -> Result<Manifest> {191+/// time, before those bytes are parsed. Then the version is checked.
163- let meta = std::fs::symlink_metadata(path)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)
164 .map_err(|_| refused("the set has no manifest".to_owned()))?;194 .map_err(|_| refused("the set has no manifest".to_owned()))?;
165- if !meta.file_type().is_file() || meta.len() > MANIFEST_MAX_BYTES {195+ let mac = read_regular(&dir.join(MAC_NAME), MAC_MAX_BYTES)
166- return Err(refused(196+ .map_err(|_| refused("the manifest has no MAC".to_owned()))?;
167- "the manifest is not a regular file of a sane size".to_owned(),197+ let tag = std::str::from_utf8(&mac)
168- ));198+ .ok()
169- }199+ .and_then(|text| hex::decode(text.trim_end()).ok())
170- let bytes = std::fs::read(path)?;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()))?;
171 let manifest: Manifest = serde_json::from_slice(&bytes)203 let manifest: Manifest = serde_json::from_slice(&bytes)
172 .map_err(|e| refused(format!("the manifest is not valid: {e}")))?;204 .map_err(|e| refused(format!("the manifest is not valid: {e}")))?;
173 if manifest.version != MANIFEST_VERSION {205 if manifest.version != MANIFEST_VERSION {
@@ -179,6 +211,18 @@ pub fn read_manifest(path: &Path) -> Result<Manifest> {
179 Ok(manifest)211 Ok(manifest)
180 }212 }
181 213
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+
182 /// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other226 /// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other
183 /// non-regular entries are refused, so a set cannot hide a file behind a link.227 /// non-regular entries are refused, so a set cannot hide a file behind a link.
184 fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet<String>) -> Result<()> {228 fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet<String>) -> Result<()> {
@@ -236,20 +280,26 @@ mod tests {
236 #[test]280 #[test]
237 fn a_tampered_file_or_an_extra_file_is_refused() {281 fn a_tampered_file_or_an_extra_file_is_refused() {
238 let dir = tempfile::tempdir().expect("temp dir");282 let dir = tempfile::tempdir().expect("temp dir");
283+ let key = [3u8; 32];
239 std::fs::write(dir.path().join("iz.db"), b"one").expect("write");284 std::fs::write(dir.path().join("iz.db"), b"one").expect("write");
240 write_manifest(285 write_manifest(
241 dir.path(),286 dir.path(),
287+ &key,
242 "2026-10-28T00:00:00.000000000Z",288 "2026-10-28T00:00:00.000000000Z",
243 "t",289 "t",
244 &["iz.db".into()],290 &["iz.db".into()],
245 )291 )
246 .expect("manifest");292 .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+ );
248 298
249 std::fs::write(dir.path().join("iz.db"), b"two").expect("tamper");299 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());
251 std::fs::write(dir.path().join("iz.db"), b"one").expect("restore");301 std::fs::write(dir.path().join("iz.db"), b"one").expect("restore");
252 std::fs::write(dir.path().join("extra"), b"x").expect("extra");302 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());
254 }304 }
255 }305 }
crates/iz-core/src/secret.rsmodified+3 -1
@@ -49,7 +49,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
49 Ok(key)49 Ok(key)
50 }50 }
51 51
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]> {
53 #[cfg(unix)]55 #[cfg(unix)]
54 {56 {
55 use std::os::unix::fs::PermissionsExt;57 use std::os::unix::fs::PermissionsExt;
crates/iz-web/src/backup.rsmodified+20 -10
@@ -4,7 +4,7 @@
4 //!4 //!
5 //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a5 //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a
6 //! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and6 //! `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 its7+//! `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
8 //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed.8 //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed.
9 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever9 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever
10 //! deleted. Nothing is written in place.10 //! deleted. Nothing is written in place.
@@ -87,7 +87,7 @@ async fn run_once(
87 };87 };
88 let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id()));88 let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id()));
89 let outcome = tokio::select! {89 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,
91 _ = stop.wait_for(|stopped| *stopped) => {91 _ = stop.wait_for(|stopped| *stopped) => {
92 Err(Error::Io(std::io::Error::other("stopped before the set was finished")))92 Err(Error::Io(std::io::Error::other("stopped before the set was finished")))
93 }93 }
@@ -114,9 +114,15 @@ async fn run_once(
114 }114 }
115 }115 }
116 116
117-/// Writes the files of one set into `tmp` and the manifest last. Returns the number of files listed, not117+/// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files
118-/// counting the manifest. The caller removes `tmp` on error.118+/// listed, not 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> {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> {
120 create_dir(tmp, false)?;126 create_dir(tmp, false)?;
121 store.snapshot_to(&tmp.join(DB_FILE)).await?;127 store.snapshot_to(&tmp.join(DB_FILE)).await?;
122 let mut paths = vec![DB_FILE.to_owned()];128 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)
135 let dir = tmp.to_owned();141 let dir = tmp.to_owned();
136 let created = created_at.to_owned();142 let created = created_at.to_owned();
137 let build = env!("IZ_BUILD_SHA").to_owned();143 let build = env!("IZ_BUILD_SHA").to_owned();
138- tokio::task::spawn_blocking(move || manifest::write_manifest(&dir, &created, &build, &paths))144+ let key = *instance_key;
139- .await145+ tokio::task::spawn_blocking(move || {
140- .map_err(|error| Error::Io(std::io::Error::other(error)))??;146+ manifest::write_manifest(&dir, &key, &created, &build, &paths)
147+ })
148+ .await
149+ .map_err(|error| Error::Io(std::io::Error::other(error)))??;
141 Ok(files)150 Ok(files)
142 }151 }
143 152
@@ -235,12 +244,13 @@ mod tests {
235 let store = Store::open(&dir.path().join("iz.db")).await.expect("store");244 let store = Store::open(&dir.path().join("iz.db")).await.expect("store");
236 let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id()));245 let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id()));
237 let created = "2026-10-28T09:30:00.000000000Z";246 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)
239 .await249 .await
240 .expect("set written");250 .expect("set written");
241 publish(&tmp, dir.path(), "20261028T093000Z").expect("published");251 publish(&tmp, dir.path(), "20261028T093000Z").expect("published");
242 let published = dir.path().join("20261028T093000Z");252 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");
244 assert_eq!(verified.created_at, created);254 assert_eq!(verified.created_at, created);
245 assert!(verified.files.iter().any(|file| file.path == DB_FILE));255 assert!(verified.files.iter().any(|file| file.path == DB_FILE));
246 assert!(!tmp.exists(), "the temporary name is gone after the rename");256 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};
29 use crate::state::AppState;29 use crate::state::AppState;
30 30
31 /// Name of the instance key file inside the data directory.31 /// 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";
33 /// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals.33 /// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals.
34 const DEFAULT_KEY_PREFIX: &str = "IZ";34 const DEFAULT_KEY_PREFIX: &str = "IZ";
35 35
crates/iz-web/src/cli/export.rsmodified+14 -5
@@ -3,7 +3,7 @@
3 //!3 //!
4 //! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity,4 //! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity,
5 //! attachment metadata and the members named by those rows), `attachments/<id>` for every attachment whose5 //! 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 elsewhere6+//! 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
7 //! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing7 //! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing
8 //! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing8 //! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing
9 //! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No9 //! 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};
22 use iz_core::time::now_stamp;22 use iz_core::time::now_stamp;
23 use sha2::{Digest, Sha256};23 use sha2::{Digest, Sha256};
24 24
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};
26 26
27 /// The file that holds the board.27 /// The file that holds the board.
28 const BOARD_FILE: &str = "board.json";28 const BOARD_FILE: &str = "board.json";
@@ -45,10 +45,14 @@ pub async fn run(config_path: &Path, out: &Path) -> ExitCode {
45 Ok(lock) => lock,45 Ok(lock) => lock,
46 Err(code) => return code,46 Err(code) => return code,
47 };47 };
48+ let key = match instance_key(&data_dir) {
49+ Ok(key) => key,
50+ Err(message) => return fail(message),
51+ };
48 if let Err(message) = prepare_out(out) {52 if let Err(message) = prepare_out(out) {
49 return fail(message);53 return fail(message);
50 }54 }
51- match write_export(&config, &data_dir, out).await {55+ match write_export(&config, &data_dir, out, &key).await {
52 Ok(report) => {56 Ok(report) => {
53 println!(57 println!(
54 "exported {} attachments with bytes and {} without to {}",58 "exported {} attachments with bytes and {} without to {}",
@@ -104,7 +108,12 @@ fn prepare_out(out: &Path) -> Result<(), String> {
104 108
105 /// Reads the database and writes the export. Every failure before the manifest leaves the directory109 /// Reads the database and writes the export. Every failure before the manifest leaves the directory
106 /// partly written; the caller reports it and the operator removes it.110 /// 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> {
108 let database = database_file(config)?;117 let database = database_file(config)?;
109 let db = ReadOnly::open(&database)118 let db = ReadOnly::open(&database)
110 .await119 .await
@@ -187,7 +196,7 @@ async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result<Re
187 .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?;196 .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?;
188 write_new(&out.join(BOARD_FILE), &bytes)?;197 write_new(&out.join(BOARD_FILE), &bytes)?;
189 198
190- write_manifest(out, &now_stamp(), env!("IZ_BUILD_SHA"), &written)199+ write_manifest(out, key, &now_stamp(), env!("IZ_BUILD_SHA"), &written)
191 .map_err(|error| describe(&error))?;200 .map_err(|error| describe(&error))?;
192 Ok(report)201 Ok(report)
193 }202 }
crates/iz-web/src/cli/mod.rsmodified+16 -0
@@ -22,6 +22,9 @@ use std::process::ExitCode;
22 22
23 use clap::{Parser, Subcommand};23 use clap::{Parser, Subcommand};
24 use iz_core::config::Config;24 use iz_core::config::Config;
25+use iz_core::secret;
26+
27+use crate::boot::KEY_FILE;
25 28
26 /// The file inside the data directory that carries the process lock.29 /// The file inside the data directory that carries the process lock.
27 pub const LOCK_FILE: &str = "iz.lock";30 pub const LOCK_FILE: &str = "iz.lock";
@@ -133,6 +136,19 @@ pub fn existing_data_dir(config: &Config) -> Result<PathBuf, String> {
133 })136 })
134 }137 }
135 138
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+
136 /// The database path, checked to be a regular file that is not a link. Nothing is created.152 /// The database path, checked to be a regular file that is not a link. Nothing is created.
137 pub fn database_file(config: &Config) -> Result<PathBuf, String> {153 pub fn database_file(config: &Config) -> Result<PathBuf, String> {
138 let meta = std::fs::symlink_metadata(&config.database).map_err(|error| {154 let meta = std::fs::symlink_metadata(&config.database).map_err(|error| {
crates/iz-web/src/cli/restore.rsmodified+25 -8
@@ -1,6 +1,7 @@
1 //! `iz restore --from <set dir>`: replaces the database and the attachments with a verified backup set.1 //! `iz restore --from <set dir>`: replaces the database and the attachments with a verified backup set.
2 //!2 //!
3-//! Order: verify the set with `manifest::verify_set`; check that the configured database is a regular file3+//! 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
4 //! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data5 //! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data
5 //! directory and check each copy against the manifest; run `integrity_check` and the migration check on the6 //! directory and check each copy against the manifest; run `integrity_check` and the migration check on the
6 //! staged database. Nothing outside the staging directory changes until then. Only after that are the current7 //! 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};
21 use iz_core::store::export::{ReadOnly, migrations_problem};22 use iz_core::store::export::{ReadOnly, migrations_problem};
22 use iz_core::store::new_id;23 use iz_core::store::new_id;
23 24
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};
25 26
26 /// The database file name inside a backup set. Fixed: the set writer uses this name too.27 /// The database file name inside a backup set. Fixed: the set writer uses this name too.
27 const SET_DB: &str = "iz.db";28 const SET_DB: &str = "iz.db";
@@ -50,7 +51,11 @@ pub async fn run(config_path: &Path, from: &Path) -> ExitCode {
50 Ok(lock) => lock,51 Ok(lock) => lock,
51 Err(code) => return code,52 Err(code) => return code,
52 };53 };
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 {
54 Ok(summary) => {59 Ok(summary) => {
55 println!("{summary}");60 println!("{summary}");
56 ExitCode::SUCCESS61 ExitCode::SUCCESS
@@ -241,8 +246,13 @@ async fn check_staged(staged_db: &Path) -> Result<(), String> {
241 }246 }
242 247
243 /// The whole restore. Returns the summary line on success.248 /// The whole restore. Returns the summary line on success.
244-async fn restore(config: &Config, data_dir: &Path, from: &Path) -> Result<String, String> {249+async fn restore(
245- let manifest = manifest::verify_set(from).map_err(|error| describe(&error))?;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))?;
246 let attachment_ids = plan_set(&manifest)?;256 let attachment_ids = plan_set(&manifest)?;
247 let db_target = database_target(config, data_dir)?;257 let db_target = database_target(config, data_dir)?;
248 let attachments_dir = data_dir.join(ATTACHMENTS_DIR);258 let attachments_dir = data_dir.join(ATTACHMENTS_DIR);
@@ -416,11 +426,13 @@ mod tests {
416 let data = root.path().join("data");426 let data = root.path().join("data");
417 std::fs::create_dir_all(&set).expect("set dir");427 std::fs::create_dir_all(&set).expect("set dir");
418 std::fs::create_dir_all(&data).expect("data dir");428 std::fs::create_dir_all(&data).expect("data dir");
429+ let key = [5u8; 32];
419 let db = data.join("iz.db");430 let db = data.join("iz.db");
420 std::fs::write(&db, b"current database").expect("current db");431 std::fs::write(&db, b"current database").expect("current db");
421 std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db");432 std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db");
422 write_manifest(433 write_manifest(
423 &set,434 &set,
435+ &key,
424 "2026-10-28T00:00:00.000000000Z",436 "2026-10-28T00:00:00.000000000Z",
425 "test",437 "test",
426 &[SET_DB.to_owned()],438 &[SET_DB.to_owned()],
@@ -437,9 +449,14 @@ mod tests {
437 data.display(),449 data.display(),
438 ))450 ))
439 .expect("config");451 .expect("config");
440- let error = restore(&config, &data.canonicalize().expect("canonical"), &set)452+ let error = restore(
441- .await453+ &config,
442- .expect_err("tampered set must be refused");454+ &data.canonicalize().expect("canonical"),
455+ &set,
456+ &key,
457+ )
458+ .await
459+ .expect_err("tampered set must be refused");
443 assert!(460 assert!(
444 error.contains("changed since the set was written"),461 error.contains("changed since the set was written"),
445 "got: {error}"462 "got: {error}"
docs/architecture.mdmodified+6 -1
@@ -218,7 +218,12 @@ manifest, and never writes outside `DIR`. `iz restore --from SET` verifies a bac
218 database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the218 database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the
219 configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes219 configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes
220 read-only. Every command except `export` refuses while a server holds `data_dir/iz.lock`. Backups are written by220 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.
222 227
223 ---228 ---
224 229