forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

pack.rs574 lines, 22.0 KiBHistoryRawDownload
1//! `im-web pack` / `im-web unpack` — the family's backup, and its restore.
2//!
3//! One 0600 gzipped tar carries every service tree the deployment holds:
4//! the database with its WAL sidecars, the config directory, the signing
5//! key, and the object store. A `manifest.json` rides as the first member
6//! and names what went in, so a restore can check before it overwrites.
7//!
8//! The keys come from im's services table plus im itself — the archive
9//! follows the family as it grows, and no key is ever spelled out here.
10//!
11//! Like every CLI arm this runs while the server is stopped: Turso is a
12//! single-writer engine, and a database packed under a live writer is not
13//! a backup.
14
15use std::fs::{self, File, OpenOptions};
16use std::io::Read as _;
17use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
18use std::path::{Component, Path, PathBuf};
19
20use serde::{Deserialize, Serialize};
21
22use crate::config::Config;
23
24/// The manifest at the archive's root: which keys ride inside and which
25/// files each brought, and when it was packed. `version` gates the
26/// restore — a shape this binary does not know refuses itself instead of
27/// guessing.
28#[derive(Serialize, Deserialize)]
29struct Manifest {
30 version: u32,
31 packed_at: String,
32 services: Vec<PackedService>,
33}
34
35#[derive(Serialize, Deserialize)]
36struct PackedService {
37 key: String,
38 /// Paths relative to the pack root — the form the manifest names and
39 /// the restore writes back: `<key>/<key>.db`, `<key>/config/x.toml`.
40 files: Vec<String>,
41}
42
43const MANIFEST_NAME: &str = "manifest.json";
44
45/// Every family tree worth packing, one key each: the services table's
46/// rows plus im's own key. The row for im normally stands on that table —
47/// `register_self` writes it on every boot — but a database too young or
48/// too emptied to hold it does not keep im's tree out of the archive.
49pub async fn family_keys(config: &Config) -> Vec<String> {
50 let store = im_core::store::Store::open(&config.database)
51 .await
52 .expect("failed to open the database");
53 let services = im_core::services::list(&store)
54 .await
55 .expect("failed to read the services table");
56 drop(store);
57
58 let mut keys = vec![im_core::services::SELF_OWNER.to_string()];
59 for service in services {
60 if !keys.contains(&service.key) {
61 keys.push(service.key);
62 }
63 }
64 keys
65}
66
67/// `im-web pack [--root DIR] [--out FILE]`. `--root` is the directory the
68/// family trees sit under; without it, the parent of the working
69/// directory — on the server, `$HOME` with `$HOME/im`, `$HOME/in`, …
70/// inside. Without `--out`, a stamped name in the working directory.
71pub async fn pack_command(config: &Config, root: Option<&str>, out: Option<&str>) {
72 let keys = family_keys(config).await;
73 let root = root.map(PathBuf::from).unwrap_or_else(default_root);
74 let out = out.map(PathBuf::from).unwrap_or_else(archive_name);
75 println!(
76 "im packing {} service tree(s) from {}",
77 keys.len(),
78 root.display()
79 );
80 match pack(&root, &keys, &out) {
81 Ok(()) => println!("im packed {}", out.display()),
82 Err(problem) => {
83 eprintln!("im: {problem}");
84 std::process::exit(1);
85 }
86 }
87}
88
89/// `im-web unpack FILE [--root DIR] [--force]`. Without `--force` an
90/// existing target database stops the restore before anything moves.
91pub fn unpack_command(archive: &str, root: Option<&str>, force: bool) {
92 let root = root.map(PathBuf::from).unwrap_or_else(default_root);
93 println!("im restoring {archive} into {}", root.display());
94 match unpack(Path::new(archive), &root, force) {
95 Ok(restored) => println!("im restored {restored} file(s)"),
96 Err(problem) => {
97 eprintln!("im: {problem}");
98 std::process::exit(1);
99 }
100 }
101}
102
103/// Packs each key's tree — the database trio, the signing key, `config/`,
104/// `storage/` — into one 0600 gzipped tar. A missing piece is a line on
105/// stderr, not a failure: a tree without a `storage/` is normal, and the
106/// pack's job is to take what is there.
107pub fn pack(root: &Path, keys: &[String], out: &Path) -> Result<(), String> {
108 let mut packed = Vec::new();
109 for key in keys {
110 let home = root.join(key);
111 if !home.is_dir() {
112 eprintln!("im {key}: no tree at {}, skipping", home.display());
113 continue;
114 }
115 let mut files = Vec::new();
116 // The database travels with its WAL sidecars or not at all — a
117 // checkpointed tree legitimately carries neither.
118 for name in [
119 format!("{key}.db"),
120 format!("{key}.db-wal"),
121 format!("{key}.db-shm"),
122 format!("{key}.key"),
123 ] {
124 if home.join(&name).is_file() {
125 files.push(format!("{key}/{name}"));
126 } else {
127 eprintln!("im {key}: {name} not present, skipped");
128 }
129 }
130 for dir in ["config", "storage"] {
131 let tree = home.join(dir);
132 if !tree.exists() {
133 eprintln!("im {key}: {dir}/ not present, skipped");
134 continue;
135 }
136 if !tree.is_dir() {
137 return Err(format!("{} is not a directory", tree.display()));
138 }
139 files.extend(walk(&tree, root)?);
140 }
141 if files.is_empty() {
142 eprintln!("im {key}: nothing to pack, skipped");
143 continue;
144 }
145 files.sort();
146 packed.push(PackedService {
147 key: key.clone(),
148 files,
149 });
150 }
151 if packed.is_empty() {
152 return Err("nothing to pack: none of the family trees holds a file".into());
153 }
154
155 let manifest = Manifest {
156 version: 1,
157 packed_at: time::OffsetDateTime::now_utc()
158 .format(&time::format_description::well_known::Rfc3339)
159 .unwrap_or_else(|_| "unknown".into()),
160 services: packed,
161 };
162 let manifest_body = serde_json::to_vec_pretty(&manifest)
163 .map_err(|e| format!("failed to write the manifest: {e}"))?;
164
165 if let Some(parent) = out.parent() {
166 if !parent.as_os_str().is_empty() {
167 fs::create_dir_all(parent)
168 .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
169 }
170 }
171 // 0600 from the first byte: the archive carries signing keys, so
172 // there is no window where it reads wider.
173 let file = OpenOptions::new()
174 .create(true)
175 .truncate(true)
176 .write(true)
177 .mode(0o600)
178 .open(out)
179 .map_err(|e| format!("failed to create {}: {e}", out.display()))?;
180 let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(
181 file,
182 flate2::Compression::default(),
183 ));
184 let mut header = tar::Header::new_gnu();
185 header.set_size(manifest_body.len() as u64);
186 header.set_mode(0o600);
187 header.set_cksum();
188 tar.append_data(&mut header, MANIFEST_NAME, manifest_body.as_slice())
189 .map_err(|e| format!("failed to add {MANIFEST_NAME}: {e}"))?;
190 for service in &manifest.services {
191 for relative in &service.files {
192 let path = root.join(relative);
193 tar.append_path_with_name(&path, relative)
194 .map_err(|e| format!("failed to add {relative}: {e}"))?;
195 }
196 }
197 tar.into_inner()
198 .map_err(|e| format!("failed to seal {PART}: {e}", PART = out.display()))?
199 .finish()
200 .map_err(|e| format!("failed to seal {}: {e}", out.display()))?;
201 Ok(())
202}
203
204/// Restores an archive under `root`. Refuses when a target database is
205/// already there — unless `force` says an overwrite is meant — and lands
206/// every config, keys file, and signing key at 0600, whatever the packing
207/// machine's modes were. Answers the number of files restored.
208pub fn unpack(archive: &Path, root: &Path, force: bool) -> Result<usize, String> {
209 let manifest = read_manifest(archive)?;
210 if manifest.version != 1 {
211 return Err(format!(
212 "archive manifest version {} is not understood here",
213 manifest.version
214 ));
215 }
216 if !force {
217 let in_the_way: Vec<&str> = manifest
218 .services
219 .iter()
220 .filter(|service| {
221 root.join(&service.key)
222 .join(format!("{}.db", service.key))
223 .is_file()
224 })
225 .map(|service| service.key.as_str())
226 .collect();
227 if !in_the_way.is_empty() {
228 return Err(format!(
229 "refusing to overwrite an existing database for {} — pass --force to unpack over it",
230 in_the_way.join(", ")
231 ));
232 }
233 }
234
235 let file = File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?;
236 let mut restored = 0;
237 for entry in tar::Archive::new(flate2::read::GzDecoder::new(file))
238 .entries()
239 .map_err(|e| format!("failed to read {}: {e}", archive.display()))?
240 {
241 let mut entry =
242 entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?;
243 let name = entry
244 .path()
245 .map_err(|e| format!("{} is damaged: {e}", archive.display()))?
246 .to_path_buf();
247 let Some(relative) = safe_relative(&name) else {
248 return Err(format!(
249 "archive member {name:?} is not a safe relative path"
250 ));
251 };
252 if relative == Path::new(MANIFEST_NAME) {
253 continue;
254 }
255 // Directories are made as their files need them; anything else a
256 // member could be — a link, a device — is not something this
257 // archive has business carrying.
258 if !entry.header().entry_type().is_file() {
259 return Err(format!("archive member {relative:?} is not a regular file"));
260 }
261 let destination = root.join(relative);
262 if let Some(parent) = destination.parent() {
263 fs::create_dir_all(parent)
264 .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
265 }
266 entry
267 .unpack(&destination)
268 .map_err(|e| format!("failed to restore {}: {e}", destination.display()))?;
269 if let Some(secret) = secret_mode(&destination) {
270 fs::set_permissions(&destination, fs::Permissions::from_mode(secret))
271 .map_err(|e| format!("failed to tighten {}: {e}", destination.display()))?;
272 }
273 restored += 1;
274 }
275 Ok(restored)
276}
277
278/// Walks `dir` for regular files, each named relative to `root` — the
279/// form the manifest names and the restore writes back. Symlinks are
280/// refused rather than followed: the archive is the bytes of the tree,
281/// not where its links point.
282fn walk(dir: &Path, root: &Path) -> Result<Vec<String>, String> {
283 let mut files = Vec::new();
284 let mut stack = vec![dir.to_path_buf()];
285 while let Some(current) = stack.pop() {
286 let entries = fs::read_dir(&current)
287 .map_err(|e| format!("failed to read {}: {e}", current.display()))?;
288 for entry in entries {
289 let entry = entry
290 .map_err(|e| format!("failed to read {}: {e}", current.display()))?;
291 let path = entry.path();
292 let kind = entry
293 .file_type()
294 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
295 if kind.is_dir() {
296 stack.push(path);
297 } else if kind.is_file() {
298 let relative = path
299 .strip_prefix(root)
300 .map_err(|e| format!("failed to name {}: {e}", path.display()))?
301 .to_string_lossy()
302 .into_owned();
303 files.push(relative);
304 } else {
305 eprintln!("im skipping {}: not a regular file", path.display());
306 }
307 }
308 }
309 Ok(files)
310}
311
312/// The archive member as a path that stays under the restore root —
313/// `None` for the absolute, upward-traversing, or empty names an archive
314/// has no business carrying.
315fn safe_relative(name: &Path) -> Option<&Path> {
316 if name.is_absolute() || name.as_os_str().is_empty() {
317 return None;
318 }
319 for component in name.components() {
320 match component {
321 Component::Normal(_) | Component::CurDir => {}
322 _ => return None,
323 }
324 }
325 Some(name)
326}
327
328/// The mode a restored file is held to: 0600 for the things that carry
329/// secrets — config toml, `*.keys`, the signing keys — and `None` for
330/// everything else.
331fn secret_mode(path: &Path) -> Option<u32> {
332 let shown = path.to_string_lossy();
333 if shown.ends_with(".toml") || shown.ends_with(".keys") || shown.ends_with(".key") {
334 Some(0o600)
335 } else {
336 None
337 }
338}
339
340/// Reads the archive's manifest, its first member — the pass that decides
341/// whether the restore may start at all.
342fn read_manifest(archive: &Path) -> Result<Manifest, String> {
343 let file =
344 File::open(archive).map_err(|e| format!("failed to open {}: {e}", archive.display()))?;
345 for entry in tar::Archive::new(flate2::read::GzDecoder::new(file))
346 .entries()
347 .map_err(|e| format!("failed to read {}: {e}", archive.display()))?
348 {
349 let mut entry =
350 entry.map_err(|e| format!("{} is damaged: {e}", archive.display()))?;
351 let is_manifest = entry
352 .path()
353 .map_err(|e| format!("{} is damaged: {e}", archive.display()))?
354 == Path::new(MANIFEST_NAME);
355 if is_manifest {
356 let mut body = String::new();
357 entry
358 .read_to_string(&mut body)
359 .map_err(|e| format!("failed to read {MANIFEST_NAME}: {e}"))?;
360 return serde_json::from_str(&body)
361 .map_err(|e| format!("{}'s manifest does not parse: {e}", archive.display()));
362 }
363 }
364 Err(format!("{} carries no {MANIFEST_NAME}", archive.display()))
365}
366
367/// The parent of the working directory: on the server the trees sit under
368/// `$HOME`, the deploy directory the process runs from inside it.
369fn default_root() -> PathBuf {
370 let cwd = match std::env::current_dir() {
371 Ok(cwd) => cwd,
372 Err(e) => {
373 eprintln!("im: cannot read the working directory: {e}");
374 std::process::exit(2);
375 }
376 };
377 match cwd.parent() {
378 Some(parent) => parent.to_path_buf(),
379 None => {
380 eprintln!("im: no family root above {}", cwd.display());
381 eprintln!("usage: pass --root DIR");
382 std::process::exit(2);
383 }
384 }
385}
386
387/// The archive's default name: stamped, in the working directory.
388fn archive_name() -> PathBuf {
389 const STAMP: &[time::format_description::BorrowedFormatItem<'static>] =
390 time::macros::format_description!(
391 "im-pack-[year][month][day]-[hour][minute][second].tar.gz"
392 );
393 PathBuf::from(
394 time::OffsetDateTime::now_utc()
395 .format(STAMP)
396 .unwrap_or_else(|_| "im-pack.tar.gz".into()),
397 )
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 /// A throwaway tree under the OS temp dir, gone with the test.
405 struct TempDir(PathBuf);
406
407 impl TempDir {
408 fn new(label: &str) -> TempDir {
409 let path = std::env::temp_dir()
410 .join(format!("im-pack-{label}-{}", ulid::Ulid::generate()));
411 fs::create_dir_all(&path).unwrap();
412 TempDir(path)
413 }
414 }
415
416 impl Drop for TempDir {
417 fn drop(&mut self) {
418 let _ = fs::remove_dir_all(&self.0);
419 }
420 }
421
422 fn write(path: &Path, bytes: &[u8]) {
423 fs::create_dir_all(path.parent().unwrap()).unwrap();
424 fs::write(path, bytes).unwrap();
425 }
426
427 fn mode_of(path: &Path) -> u32 {
428 fs::metadata(path).unwrap().permissions().mode() & 0o777
429 }
430
431 /// The data-driven gate: the keys are whatever the caller hands over —
432 /// here `im` and a fixture sibling `xy` that is not in/iz — and the
433 /// roundtrip treats them identically. Also the standing refusals: the
434 /// archive lands 0600, secrets restore 0600, and a second unpack
435 /// stops at the existing database unless --force names the overwrite.
436 #[test]
437 fn roundtrip_im_and_xy() {
438 let source = TempDir::new("src");
439 // im: the full tree — database trio, signing key, config, storage.
440 write(&source.0.join("im/im.db"), b"im-db");
441 write(&source.0.join("im/im.db-wal"), b"im-wal");
442 write(&source.0.join("im/im.db-shm"), b"im-shm");
443 write(&source.0.join("im/im.key"), b"im-key");
444 write(&source.0.join("im/config/im.toml"), b"listen = \"127.0.0.1:7650\"\n");
445 write(&source.0.join("im/storage/a/blob"), b"im-blob");
446 // xy: a bare sibling — database and config only. `zz` has no tree
447 // at all; its pack is a stderr line, not a failure.
448 write(&source.0.join("xy/xy.db"), b"xy-db");
449 write(&source.0.join("xy/config/xy.toml"), b"listen = \"127.0.0.1:8000\"\n");
450
451 let keys = ["im".to_string(), "xy".to_string(), "zz".to_string()];
452 let out = source.0.join("pack.tar.gz");
453 pack(&source.0, &keys, &out).expect("pack succeeds");
454 assert!(out.is_file());
455 assert_eq!(mode_of(&out), 0o600, "the archive lands 0600");
456
457 let destination = TempDir::new("dest");
458 unpack(&out, &destination.0, false).expect("unpack into an empty root");
459 for (relative, bytes) in [
460 ("im/im.db", &b"im-db"[..]),
461 ("im/im.db-wal", b"im-wal"),
462 ("im/im.db-shm", b"im-shm"),
463 ("im/im.key", b"im-key"),
464 ("im/config/im.toml", b"listen = \"127.0.0.1:7650\"\n"),
465 ("im/storage/a/blob", b"im-blob"),
466 ("xy/xy.db", b"xy-db"),
467 ("xy/config/xy.toml", b"listen = \"127.0.0.1:8000\"\n"),
468 ] {
469 assert_eq!(
470 fs::read(destination.0.join(relative)).unwrap(),
471 bytes,
472 "{relative} must roundtrip"
473 );
474 }
475 for secret in ["im/im.key", "im/config/im.toml", "xy/config/xy.toml"] {
476 assert_eq!(
477 mode_of(&destination.0.join(secret)),
478 0o600,
479 "{secret} must land 0600"
480 );
481 }
482
483 // Without --force, a target database stops the restore before
484 // anything moves.
485 let problem = unpack(&out, &destination.0, false)
486 .expect_err("an existing database must refuse the unpack");
487 assert!(problem.contains("--force"), "the refusal names the way out: {problem}");
488 assert_eq!(
489 fs::read(destination.0.join("im/im.db")).unwrap(),
490 b"im-db",
491 "the refused unpack left the tree alone"
492 );
493 unpack(&out, &destination.0, true).expect("--force unpacks over it");
494 assert_eq!(fs::read(destination.0.join("im/im.db")).unwrap(), b"im-db");
495 }
496
497 /// A member whose name climbs out of the restore root is refused, not
498 /// extracted — a tampered archive cannot write past the root. The
499 /// tar library refuses to *write* such a name, so the hostile archive
500 /// is ustar bytes laid by hand, the way an attacker would.
501 #[test]
502 fn unpack_refuses_escaping_names() {
503 use std::io::Write as _;
504
505 let source = TempDir::new("evil-src");
506 let archive = source.0.join("evil.tar.gz");
507
508 let mut tar = Vec::new();
509 raw_member(
510 &mut tar,
511 MANIFEST_NAME,
512 br#"{"version":1,"packed_at":"now","services":[{"key":"xy","files":[]}]}"#,
513 );
514 raw_member(&mut tar, "../escape", b"gotcha");
515 tar.extend_from_slice(&[0u8; 1024]);
516 let mut gz = flate2::write::GzEncoder::new(
517 File::create(&archive).unwrap(),
518 flate2::Compression::default(),
519 );
520 gz.write_all(&tar).unwrap();
521 gz.finish().unwrap();
522
523 let destination = TempDir::new("evil-dest");
524 let problem = unpack(&archive, &destination.0, false)
525 .expect_err("an escaping member must refuse the unpack");
526 assert!(problem.contains("safe relative"), "{problem}");
527 assert!(
528 !destination.0.parent().unwrap().join("escape").exists(),
529 "nothing may land outside the root"
530 );
531 }
532
533 /// One raw ustar member: header block, body, padding — no library
534 /// path validation, so a hostile name travels through untouched.
535 fn raw_member(tar: &mut Vec<u8>, name: &str, body: &[u8]) {
536 let mut header = [0u8; 512];
537 header[..name.len()].copy_from_slice(name.as_bytes());
538 header[124..136].copy_from_slice(format!("{:011o}\0", body.len()).as_bytes());
539 header[136..148].copy_from_slice(b"00000000000\0");
540 header[148..156].copy_from_slice(b" ");
541 header[156] = b'0';
542 header[257..263].copy_from_slice(b"ustar\0");
543 header[263..265].copy_from_slice(b"00");
544 let sum: u32 = header.iter().map(|byte| u32::from(*byte)).sum();
545 header[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());
546 tar.extend_from_slice(&header);
547 tar.extend_from_slice(body);
548 tar.extend(std::iter::repeat_n(0u8, (512 - body.len() % 512) % 512));
549 }
550
551 /// An archive whose manifest names a shape this binary does not know
552 /// refuses itself instead of guessing.
553 #[test]
554 fn unpack_refuses_a_future_manifest() {
555 let source = TempDir::new("future-src");
556 let archive = source.0.join("future.tar.gz");
557 let file = File::create(&archive).unwrap();
558 let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(
559 file,
560 flate2::Compression::default(),
561 ));
562 let manifest = br#"{"version":99,"packed_at":"tomorrow","services":[]}"#;
563 let mut header = tar::Header::new_gnu();
564 header.set_size(manifest.len() as u64);
565 header.set_cksum();
566 tar.append_data(&mut header, MANIFEST_NAME, &manifest[..]).unwrap();
567 tar.into_inner().unwrap().finish().unwrap();
568
569 let destination = TempDir::new("future-dest");
570 let problem = unpack(&archive, &destination.0, false)
571 .expect_err("an unknown manifest version must refuse");
572 assert!(problem.contains("version"), "{problem}");
573 }
574}