forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

restore.rs474 lines, 17.4 KiBHistoryRawDownload
1//! `iz restore --from <set dir>`: replaces the database and the attachments with a verified backup set.
2//!
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
5//! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data
6//! directory and check each copy against the manifest; run `integrity_check` and the migration check on the
7//! staged database. Nothing outside the staging directory changes until then. Only after that are the current
8//! `iz.db`, `iz.db-wal`, `iz.db-shm` and `attachments` moved aside under a UTC stamp (kept, never deleted) and
9//! the staged files moved into place. If a move fails, the moves made so far are undone.
10//!
11//! Every path is joined from the data directory and fixed names; the only names taken from the set are the
12//! ones `verify_set` checked, and they are used only after they parse as canonical ULIDs.
13
14use std::fs::{DirBuilder, Permissions};
15use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
16use std::path::{Path, PathBuf};
17use std::process::ExitCode;
18
19use iz_core::config::Config;
20use iz_core::manifest::{self, Manifest};
21use iz_core::staging::{ATTACHMENTS_DIR, blob_path};
22use iz_core::store::export::{ReadOnly, migrations_problem};
23use iz_core::store::new_id;
24
25use super::{describe, existing_data_dir, fail, file_stamp, instance_key, take_lock};
26
27/// The database file name inside a backup set. Fixed: the set writer uses this name too.
28const SET_DB: &str = "iz.db";
29/// The directory name prefix of the staging directory inside the data directory.
30const STAGING_PREFIX: &str = "restore-staging-";
31
32/// Runs the restore and maps its outcome to an exit status.
33pub async fn run(config_path: &Path, from: &Path) -> ExitCode {
34 let config = match Config::load(config_path) {
35 Ok(config) => config,
36 Err(error) => return fail(describe(&error)),
37 };
38 if let Err(error) = std::fs::create_dir_all(&config.data_dir)
39 .and_then(|()| std::fs::set_permissions(&config.data_dir, Permissions::from_mode(0o700)))
40 {
41 return fail(format!(
42 "the data directory {} cannot be created: {error}",
43 config.data_dir.display()
44 ));
45 }
46 let data_dir = match existing_data_dir(&config) {
47 Ok(dir) => dir,
48 Err(message) => return fail(message),
49 };
50 let _lock = match take_lock(&data_dir) {
51 Ok(lock) => lock,
52 Err(code) => return code,
53 };
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 {
59 Ok(summary) => {
60 println!("{summary}");
61 ExitCode::SUCCESS
62 }
63 Err(message) => fail(message),
64 }
65}
66
67/// A canonical ULID name from a set. `None` for anything else, so a name is used only when it is the
68/// exact text the store would have written.
69fn canonical_id(name: &str) -> Option<String> {
70 // `blob_path` accepts exactly the canonical ULID text, so it is the one check for ids.
71 blob_path(Path::new("."), name)
72 .ok()
73 .map(|_| name.to_owned())
74}
75
76/// The files a restore takes from a set: `iz.db`, and `attachments/<id>` for each canonical id. Any other
77/// listed file is refused, so a set cannot smuggle a file into the data directory.
78fn plan_set(manifest: &Manifest) -> Result<Vec<String>, String> {
79 let mut attachments = Vec::new();
80 let mut has_db = false;
81 for file in &manifest.files {
82 if file.path == SET_DB {
83 has_db = true;
84 } else if let Some(id) = file
85 .path
86 .strip_prefix("attachments/")
87 .and_then(canonical_id)
88 {
89 attachments.push(id);
90 } else {
91 return Err(format!("the set lists an unexpected file: {}", file.path));
92 }
93 }
94 if !has_db {
95 return Err(format!("the set has no {SET_DB}"));
96 }
97 Ok(attachments)
98}
99
100/// The database path, joined from the canonical parent directory and the file name. Refused unless it is
101/// inside the data directory and is not a link, so the restore cannot replace a file outside it.
102fn database_target(config: &Config, data_dir: &Path) -> Result<PathBuf, String> {
103 let name = config.database.file_name().ok_or_else(|| {
104 format!(
105 "the database path has no file name: {}",
106 config.database.display()
107 )
108 })?;
109 let parent = config
110 .database
111 .parent()
112 .filter(|p| !p.as_os_str().is_empty())
113 .unwrap_or_else(|| Path::new("."));
114 let parent = parent.canonicalize().map_err(|error| {
115 format!(
116 "the database directory {} cannot be used: {error}",
117 parent.display()
118 )
119 })?;
120 if !parent.starts_with(data_dir) {
121 return Err(format!(
122 "the database {} is outside the data directory; restore refuses to replace it",
123 config.database.display()
124 ));
125 }
126 let target = parent.join(name);
127 if let Ok(meta) = std::fs::symlink_metadata(&target)
128 && !meta.file_type().is_file()
129 {
130 return Err(format!(
131 "the database {} is not a regular file",
132 target.display()
133 ));
134 }
135 Ok(target)
136}
137
138/// Copies `source` to `dest` (created new, mode 0600), then checks the copy against the manifest entry
139/// for `relative` so a set changed during the copy is refused.
140fn copy_checked(
141 manifest: &Manifest,
142 relative: &str,
143 source: &Path,
144 dest: &Path,
145) -> Result<(), String> {
146 let expected = manifest
147 .files
148 .iter()
149 .find(|file| file.path == relative)
150 .ok_or_else(|| format!("the set does not list {relative}"))?;
151 std::fs::copy(source, dest).map_err(|error| format!("cannot copy {relative}: {error}"))?;
152 std::fs::set_permissions(dest, Permissions::from_mode(0o600))
153 .map_err(|error| format!("cannot set the mode of {}: {error}", dest.display()))?;
154 let (size, digest) = manifest::digest_file(dest)
155 .map_err(|error| format!("cannot read the copy of {relative}: {}", describe(&error)))?;
156 if size != expected.size || digest != expected.sha256 {
157 return Err(format!("the set changed while it was copied: {relative}"));
158 }
159 Ok(())
160}
161
162/// The staging directory and what it holds, so a failure can remove exactly what was made.
163struct Staging {
164 dir: PathBuf,
165}
166
167impl Staging {
168 /// Makes a new staging directory with a fresh name inside the data directory, mode 0700.
169 fn create(data_dir: &Path) -> Result<Staging, String> {
170 let dir = data_dir.join(format!("{STAGING_PREFIX}{}", new_id()));
171 DirBuilder::new()
172 .mode(0o700)
173 .create(&dir)
174 .map_err(|error| format!("cannot create {}: {error}", dir.display()))?;
175 Ok(Staging { dir })
176 }
177
178 /// Removes the files a restore puts in the staging directory, then the directory. It removes only
179 /// regular files directly inside it and inside its `attachments` directory, and leaves anything else
180 /// in place.
181 fn discard(&self) {
182 let _ = remove_regular_files(&self.dir);
183 let attachments = self.dir.join(ATTACHMENTS_DIR);
184 let _ = remove_regular_files(&attachments);
185 let _ = std::fs::remove_dir(&attachments);
186 let _ = std::fs::remove_dir(&self.dir);
187 }
188}
189
190/// Removes every regular file directly inside `dir`. Links and directories are not touched.
191fn remove_regular_files(dir: &Path) -> std::io::Result<()> {
192 for entry in std::fs::read_dir(dir)? {
193 let entry = entry?;
194 if entry.file_type()?.is_file() {
195 std::fs::remove_file(entry.path())?;
196 }
197 }
198 Ok(())
199}
200
201/// Checks the staged database: `integrity_check` says `ok` and the migrations are contiguous. Its sidecars
202/// are removed when empty; a sidecar with bytes is refused.
203async fn check_staged(staged_db: &Path) -> Result<(), String> {
204 {
205 let db = ReadOnly::open(staged_db)
206 .await
207 .map_err(|error| describe(&error))?;
208 let rows = db
209 .integrity_check()
210 .await
211 .map_err(|error| describe(&error))?;
212 if rows != ["ok"] {
213 return Err(format!(
214 "the set's database fails integrity_check: {}",
215 rows.join("; ")
216 ));
217 }
218 let versions = db
219 .migration_versions()
220 .await
221 .map_err(|error| describe(&error))?;
222 if let Some(problem) = migrations_problem(&versions) {
223 return Err(format!("the set's database is refused: {problem}"));
224 }
225 }
226 for suffix in ["-wal", "-shm"] {
227 let mut sidecar = staged_db.as_os_str().to_owned();
228 sidecar.push(suffix);
229 let sidecar = PathBuf::from(sidecar);
230 match std::fs::symlink_metadata(&sidecar) {
231 Err(_) => {}
232 Ok(meta) if meta.len() == 0 => {
233 std::fs::remove_file(&sidecar)
234 .map_err(|error| format!("cannot remove {}: {error}", sidecar.display()))?;
235 }
236 Ok(meta) => {
237 return Err(format!(
238 "the staged database has {} bytes in {}",
239 meta.len(),
240 sidecar.display()
241 ));
242 }
243 }
244 }
245 Ok(())
246}
247
248/// The whole restore. Returns the summary line on success.
249async 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))?;
256 let attachment_ids = plan_set(&manifest)?;
257 let db_target = database_target(config, data_dir)?;
258 let attachments_dir = data_dir.join(ATTACHMENTS_DIR);
259 if let Ok(meta) = std::fs::symlink_metadata(&attachments_dir)
260 && !meta.file_type().is_dir()
261 {
262 return Err(format!("{} is not a directory", attachments_dir.display()));
263 }
264
265 // Stage and check everything first. A failure here removes the staging directory and changes nothing else.
266 let staging = Staging::create(data_dir)?;
267 let staged = stage(&staging, from, &manifest, &attachment_ids).await;
268 if let Err(message) = staged {
269 staging.discard();
270 return Err(message);
271 }
272
273 let stamp = file_stamp();
274 let result = swap_into_place(&staging.dir, &db_target, data_dir, &stamp);
275 match result {
276 Ok(moved) => {
277 if let Err(error) = std::fs::remove_dir(&staging.dir) {
278 eprintln!(
279 "iz: the staging directory {} could not be removed: {error}",
280 staging.dir.display()
281 );
282 }
283 Ok(format!(
284 "restored from {}: {} attachments; previous files kept as {}",
285 from.display(),
286 attachment_ids.len(),
287 moved.join(", ")
288 ))
289 }
290 Err(message) => {
291 staging.discard();
292 Err(message)
293 }
294 }
295}
296
297/// Copies the set's files into the staging directory and checks them. The staging directory always gets
298/// an `attachments` directory, even when the set has none, so the swap is the same in both cases.
299async fn stage(
300 staging: &Staging,
301 from: &Path,
302 manifest: &Manifest,
303 attachment_ids: &[String],
304) -> Result<(), String> {
305 let staged_db = staging.dir.join(SET_DB);
306 copy_checked(manifest, SET_DB, &from.join(SET_DB), &staged_db)?;
307 let staged_attachments = staging.dir.join(ATTACHMENTS_DIR);
308 DirBuilder::new()
309 .mode(0o700)
310 .create(&staged_attachments)
311 .map_err(|error| format!("cannot create {}: {error}", staged_attachments.display()))?;
312 for id in attachment_ids {
313 let relative = format!("{ATTACHMENTS_DIR}/{id}");
314 copy_checked(
315 manifest,
316 &relative,
317 &from.join(ATTACHMENTS_DIR).join(id),
318 &staged_attachments.join(id),
319 )?;
320 }
321 check_staged(&staged_db).await
322}
323
324/// One move made by the swap, so it can be undone.
325enum Move {
326 /// An existing file or directory moved aside, from, to.
327 Aside(PathBuf, PathBuf),
328 /// A staged file moved into place, from, to.
329 Placed(PathBuf, PathBuf),
330}
331
332/// Moves the current database files and attachments aside, then the staged ones into place. Returns the
333/// names the old files were kept under. If any move fails, the moves made so far are reversed.
334fn swap_into_place(
335 staging: &Path,
336 db_target: &Path,
337 data_dir: &Path,
338 stamp: &str,
339) -> Result<Vec<String>, String> {
340 let attachments = data_dir.join(ATTACHMENTS_DIR);
341 let mut old: Vec<(PathBuf, PathBuf)> = Vec::new();
342 for current in [
343 db_target.to_path_buf(),
344 with_suffix(db_target, "-wal"),
345 with_suffix(db_target, "-shm"),
346 attachments.clone(),
347 ] {
348 if std::fs::symlink_metadata(&current).is_ok() {
349 let aside = with_suffix(&current, &format!(".{stamp}"));
350 if std::fs::symlink_metadata(&aside).is_ok() {
351 return Err(format!(
352 "{} already exists; nothing was changed",
353 aside.display()
354 ));
355 }
356 old.push((current, aside));
357 }
358 }
359 let staged_db = staging.join(SET_DB);
360 let staged_attachments = staging.join(ATTACHMENTS_DIR);
361
362 let mut done: Vec<Move> = Vec::new();
363 let outcome = (|| -> std::io::Result<()> {
364 for (current, aside) in &old {
365 std::fs::rename(current, aside)?;
366 done.push(Move::Aside(current.clone(), aside.clone()));
367 }
368 std::fs::rename(&staged_db, db_target)?;
369 done.push(Move::Placed(staged_db.clone(), db_target.to_path_buf()));
370 std::fs::rename(&staged_attachments, &attachments)?;
371 done.push(Move::Placed(
372 staged_attachments.clone(),
373 attachments.clone(),
374 ));
375 std::fs::File::open(data_dir)?.sync_all()
376 })();
377
378 match outcome {
379 Ok(()) => Ok(old
380 .iter()
381 .map(|(_, aside)| aside.display().to_string())
382 .collect()),
383 Err(error) => {
384 // Undo in reverse. A failure to undo is reported with the paths, so the operator can finish by hand.
385 let mut stuck = Vec::new();
386 for step in done.into_iter().rev() {
387 // An aside file goes back to its original name; a placed file goes back to staging.
388 let undone = match &step {
389 Move::Aside(original, aside) => std::fs::rename(aside, original),
390 Move::Placed(staged, target) => std::fs::rename(target, staged),
391 };
392 if let Err(undo_error) = undone {
393 stuck.push(undo_error.to_string());
394 }
395 }
396 if stuck.is_empty() {
397 Err(format!("restore failed and was undone: {error}"))
398 } else {
399 Err(format!(
400 "restore failed: {error}; some moves could not be undone: {}",
401 stuck.join("; ")
402 ))
403 }
404 }
405 }
406}
407
408/// `path` with `suffix` appended to its file name.
409fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
410 let mut text = path.as_os_str().to_owned();
411 text.push(suffix);
412 PathBuf::from(text)
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418 use iz_core::manifest::write_manifest;
419
420 /// A set with a file that a manifest does not list, or whose bytes changed after the manifest was
421 /// written, must not be restored: nothing in the data directory may change.
422 #[tokio::test]
423 async fn restore_refuses_a_tampered_set_and_changes_nothing() {
424 let root = tempfile::tempdir().expect("temp dir");
425 let set = root.path().join("set");
426 let data = root.path().join("data");
427 std::fs::create_dir_all(&set).expect("set dir");
428 std::fs::create_dir_all(&data).expect("data dir");
429 let key = [5u8; 32];
430 let db = data.join("iz.db");
431 std::fs::write(&db, b"current database").expect("current db");
432 std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db");
433 write_manifest(
434 &set,
435 &key,
436 "2026-10-28T00:00:00.000000000Z",
437 "test",
438 &[SET_DB.to_owned()],
439 )
440 .expect("manifest");
441 // Tamper after the manifest is written.
442 let mut bytes = std::fs::read(set.join(SET_DB)).expect("read");
443 bytes[0] ^= 0x01;
444 std::fs::write(set.join(SET_DB), bytes).expect("tamper");
445
446 let config = Config::parse(&format!(
447 "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n",
448 db.display(),
449 data.display(),
450 ))
451 .expect("config");
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");
460 assert!(
461 error.contains("changed since the set was written"),
462 "got: {error}"
463 );
464 assert_eq!(
465 std::fs::read(&db).expect("db still there"),
466 b"current database"
467 );
468 let entries: Vec<_> = std::fs::read_dir(&data)
469 .expect("list")
470 .map(|e| e.expect("entry").file_name())
471 .collect();
472 assert_eq!(entries.len(), 1, "only the database remains: {entries:?}");
473 }
474}