//! `iz export --out `: writes the board to a new directory so it can be read or kept without the //! database. //! //! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity, //! attachment metadata and the members named by those rows), `attachments/` for every attachment whose //! 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 //! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing //! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing //! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No //! symlink is created, and nothing is written outside `--out`. use std::fs::{DirBuilder, OpenOptions}; use std::io::{Read, Write}; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::Path; use std::process::ExitCode; use iz_core::config::Config; use iz_core::manifest::write_manifest; use iz_core::staging::blob_path; use iz_core::store::export::{AttachmentRow, ReadOnly}; use iz_core::time::now_stamp; use sha2::{Digest, Sha256}; use super::{database_file, describe, existing_data_dir, fail, instance_key, take_lock}; /// The file that holds the board. const BOARD_FILE: &str = "board.json"; /// The directory inside `--out` that holds the attachment bytes. const ATTACHMENTS_DIR: &str = "attachments"; /// Read chunk for copying bytes. Reason: keeps memory flat for large attachments. const CHUNK: usize = 64 * 1024; /// Runs the export and maps its outcome to an exit status. pub async fn run(config_path: &Path, out: &Path) -> ExitCode { let config = match Config::load(config_path) { Ok(config) => config, Err(error) => return fail(describe(&error)), }; let data_dir = match existing_data_dir(&config) { Ok(dir) => dir, Err(message) => return fail(message), }; let _lock = match take_lock(&data_dir) { Ok(lock) => lock, Err(code) => return code, }; let key = match instance_key(&data_dir) { Ok(key) => key, Err(message) => return fail(message), }; if let Err(message) = prepare_out(out) { return fail(message); } match write_export(&config, &data_dir, out, &key).await { Ok(report) => { println!( "exported {} attachments with bytes and {} without to {}", report.with_bytes, report.without_bytes.len(), out.display() ); if report.without_bytes.is_empty() { return ExitCode::SUCCESS; } for (id, reason) in &report.without_bytes { eprintln!("iz: attachment {id} has no bytes in the export: {reason}"); } eprintln!( "iz: the export is incomplete; {} attachments have no bytes", report.without_bytes.len() ); ExitCode::FAILURE } Err(message) => fail(message), } } /// What an export wrote, for the summary. struct Report { /// Attachments whose bytes are in the export. with_bytes: usize, /// Attachments whose bytes are not, with the reason. without_bytes: Vec<(String, String)>, } /// Makes `out` a new directory with mode 0700, or accepts an existing empty one. A link or a file is /// refused, and so is a directory with anything in it. fn prepare_out(out: &Path) -> Result<(), String> { match std::fs::symlink_metadata(out) { Ok(meta) => { if !meta.file_type().is_dir() { return Err(format!("{} exists and is not a directory", out.display())); } let mut entries = std::fs::read_dir(out) .map_err(|error| format!("cannot read {}: {error}", out.display()))?; if entries.next().is_some() { return Err(format!("{} is not empty", out.display())); } Ok(()) } Err(_) => DirBuilder::new() .mode(0o700) .create(out) .map_err(|error| format!("cannot create {}: {error}", out.display())), } } /// Reads the database and writes the export. Every failure before the manifest leaves the directory /// partly written; the caller reports it and the operator removes it. async fn write_export( config: &Config, data_dir: &Path, out: &Path, key: &[u8; 32], ) -> Result { let database = database_file(config)?; let db = ReadOnly::open(&database) .await .map_err(|error| describe(&error))?; let board_ids = db.board_ids().await.map_err(|error| describe(&error))?; let [board_id] = board_ids.as_slice() else { return Err(format!( "expected one board in the database, found {}", board_ids.len() )); }; let dump = db .export_board(board_id) .await .map_err(|error| describe(&error))?; let rows = db .board_attachment_rows(board_id) .await .map_err(|error| describe(&error))?; DirBuilder::new() .mode(0o700) .recursive(true) .create(out.join(ATTACHMENTS_DIR)) .map_err(|error| format!("cannot create the attachments directory: {error}"))?; let mut written = vec![BOARD_FILE.to_owned()]; let mut attachments = Vec::with_capacity(rows.len()); let mut report = Report { with_bytes: 0, without_bytes: Vec::new(), }; for row in &rows { // The id is used in two file names, so it must be the canonical ULID text, or it is refused. let source = blob_path(data_dir, &row.id).map_err(|error| describe(&error))?; let mut entry = attachment_json(row); if row.location == "local" { match copy_blob(&source, &out.join(ATTACHMENTS_DIR).join(&row.id), row)? { Ok(()) => { let relative = format!("{ATTACHMENTS_DIR}/{}", row.id); entry["bytes"] = serde_json::Value::Bool(true); entry["file"] = serde_json::Value::String(relative.clone()); written.push(relative); report.with_bytes += 1; } Err(reason) => { entry["bytes"] = serde_json::Value::Bool(false); report.without_bytes.push((row.id.clone(), reason)); } } } else { entry["bytes"] = serde_json::Value::Bool(false); report.without_bytes.push(( row.id.clone(), format!( "location is {}, the bytes are not on this disk", row.location ), )); } attachments.push(entry); } let members = dump.members; let board = serde_json::json!({ "format": "iz-export", "version": 1, "exported_at": now_stamp(), "board": dump.board, "columns": dump.columns, "tags": dump.tags, "tasks": dump.tasks, "assignees": dump.assignees, "dependencies": dump.dependencies, "comments": dump.comments, "activity": dump.activity, "attachments": attachments, "members": members, }); let bytes = serde_json::to_vec_pretty(&board) .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?; write_new(&out.join(BOARD_FILE), &bytes)?; write_manifest(out, key, &now_stamp(), env!("IZ_BUILD_SHA"), &written) .map_err(|error| describe(&error))?; Ok(report) } /// The metadata of an attachment row as the export file states it. fn attachment_json(row: &AttachmentRow) -> serde_json::Value { serde_json::json!({ "id": row.id, "task_id": row.task_id, "name": row.name, "mime": row.mime, "size": row.size, "sha256": row.sha256, "uploaded_by": row.uploaded_by, "created_at": row.created_at, "location": row.location, }) } /// Copies the bytes of a local attachment to `dest` (created new, mode 0600) and checks that they have the /// size and digest of the row. The source must be a regular file. On a mismatch the copy is removed and the /// reason is returned as the inner error; the outer error is a failure to write. fn copy_blob( source: &Path, dest: &Path, row: &AttachmentRow, ) -> Result, String> { let meta = match std::fs::symlink_metadata(source) { Ok(meta) => meta, Err(_) => return Ok(Err("the bytes are missing from the store".into())), }; if !meta.file_type().is_file() { return Ok(Err("the stored entry is not a regular file".into())); } let mut input = std::fs::File::open(source) .map_err(|error| format!("cannot read {}: {error}", source.display()))?; let mut output = OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(dest) .map_err(|error| format!("cannot create {}: {error}", dest.display()))?; let mut hasher = Sha256::new(); let mut size: u64 = 0; let mut buffer = vec![0u8; CHUNK]; loop { let read = input .read(&mut buffer) .map_err(|error| format!("cannot read {}: {error}", source.display()))?; if read == 0 { break; } output .write_all(&buffer[..read]) .map_err(|error| format!("cannot write {}: {error}", dest.display()))?; hasher.update(&buffer[..read]); size += read as u64; } output .sync_all() .map_err(|error| format!("cannot sync {}: {error}", dest.display()))?; let digest = hex::encode(hasher.finalize()); if size != row.size || digest != row.sha256 { drop(output); std::fs::remove_file(dest) .map_err(|error| format!("cannot remove {}: {error}", dest.display()))?; return Ok(Err( "the bytes do not match the recorded size or digest".into() )); } Ok(Ok(())) } /// Writes a new file with mode 0600 and syncs it. Used for `board.json`. fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { let mut file = OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path) .map_err(|error| format!("cannot create {}: {error}", path.display()))?; file.write_all(bytes) .and_then(|()| file.sync_all()) .map_err(|error| format!("cannot write {}: {error}", path.display())) } #[cfg(test)] mod tests { use super::*; #[test] fn export_refuses_a_non_empty_out_directory() { let dir = tempfile::tempdir().expect("temp dir"); std::fs::write(dir.path().join("keep.txt"), b"x").expect("seed file"); let error = prepare_out(dir.path()).expect_err("non-empty must be refused"); assert!(error.contains("is not empty"), "got: {error}"); let empty = dir.path().join("fresh"); prepare_out(&empty).expect("a missing directory is created"); assert!(empty.is_dir()); } }