//! `iz fsck`: a read-only check of the database and the attachments. //! //! It checks: `integrity_check` returns `ok`; the migration history is contiguous and known to this build; //! every attachment row with location `local` has its file at the expected path, a regular file whose size //! and SHA-256 match the row; no row is stuck in `moving`; and every file in `attachments/` is named by a //! row (unnamed files are reported, not deleted). Rows with location `in` are not checked by default: their //! bytes are in another service, and the note says so. With `--remote` each of them is downloaded through the //! Files-service client (the same one `iz serve` uses, so the same configuration and token) and its size and //! SHA-256 are checked like a local file; the download is streamed and hashed, never held whole. The database //! is opened read-only and never migrated. The lock file is the only thing it may create. Exit status 0 when //! nothing is wrong, 1 when anything is. use std::collections::HashSet; use std::path::Path; use std::process::ExitCode; use std::sync::Arc; use futures_util::StreamExt; use iz_core::config::Config; use iz_core::manifest::digest_file; use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; use iz_core::store::export::{ReadOnly, migrations_problem}; use sha2::{Digest, Sha256}; use super::{database_file, describe, existing_data_dir, fail, take_lock}; use crate::in_store::InStore; use crate::oidc::{self, OidcClient}; /// Runs the check, prints the report, and maps the outcome to an exit status. `remote` asks for the attachments /// held at the Files service to be downloaded and checked as well. pub async fn run(config_path: &Path, remote: bool) -> 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 remote = if remote { match remote_store(&config) { Ok(store) => Some(store), Err(message) => return fail(message), } } else { None }; let mut report = Report::default(); check(&config, &data_dir, remote.as_ref(), &mut report).await; for line in &report.lines { println!("{line}"); } if report.problems == 0 { println!("fsck: clean"); ExitCode::SUCCESS } else { println!("fsck: {} problems found", report.problems); ExitCode::FAILURE } } /// The lines of the report and how many of them are problems. #[derive(Default)] struct Report { /// Every line printed, in order. lines: Vec, /// How many lines are problems (the exit status depends on it). problems: usize, } impl Report { /// Records a line that is fine. fn ok(&mut self, text: impl Into) { self.lines.push(format!("ok: {}", text.into())); } /// Records a line that is a problem. fn problem(&mut self, text: impl Into) { self.problems += 1; self.lines.push(format!("problem: {}", text.into())); } } /// The Files-service client that `iz serve` would build (`boot.rs`), for `--remote`. Refused when the Files service /// is not enabled, since then there is nothing to download. fn remote_store(config: &Config) -> Result { if !config.in_store.enabled { return Err("--remote needs in_store.enabled = true in the configuration".into()); } let url = config .in_store .url .as_deref() .ok_or("--remote needs in_store.url in the configuration")?; let oidc_config = config .oidc .as_ref() .ok_or("--remote needs the [oidc] section in the configuration")?; let secret = oidc::read_client_secret(&oidc_config.client_secret_file).map_err(|e| describe(&e))?; let client = OidcClient::new(oidc_config, &config.base_url, secret).map_err(|e| describe(&e))?; InStore::new(url, Arc::new(client)).map_err(|e| describe(&e)) } /// Downloads object `id` from the Files service and returns its size and lowercase hex SHA-256. The bytes are hashed /// as they arrive and never held whole. The error is the text for the report. async fn digest_remote(store: &InStore, id: &str) -> Result<(u64, String), String> { let response = store .get(id, None) .await .map_err(|error| error.to_string())?; let mut hasher = Sha256::new(); let mut size: u64 = 0; let mut chunks = response.bytes_stream(); while let Some(chunk) = chunks.next().await { let chunk = chunk.map_err(|error| error.to_string())?; size += chunk.len() as u64; hasher.update(&chunk); } Ok((size, hex::encode(hasher.finalize()))) } /// Runs every check. Nothing here writes to the data directory. async fn check(config: &Config, data_dir: &Path, remote: Option<&InStore>, report: &mut Report) { let attachments_dir = data_dir.join(ATTACHMENTS_DIR); let database = match database_file(config) { Ok(path) => path, Err(message) => { report.problem(message); return; } }; let db = match ReadOnly::open(&database).await { Ok(db) => db, Err(error) => { report.problem(format!("cannot open the database: {}", describe(&error))); return; } }; match db.integrity_check().await { Ok(rows) if rows == ["ok"] => report.ok("database integrity_check"), Ok(rows) => report.problem(format!("integrity_check: {}", rows.join("; "))), Err(error) => report.problem(format!("integrity_check failed: {}", describe(&error))), } match db.migration_versions().await { Ok(versions) => match migrations_problem(&versions) { None => report.ok(format!("migrations 1 to {} are contiguous", versions.len())), Some(problem) => report.problem(problem), }, Err(error) => report.problem(format!("cannot read migrations: {}", describe(&error))), } let rows = match db.attachment_rows().await { Ok(rows) => rows, Err(error) => { report.problem(format!("cannot read attachments: {}", describe(&error))); return; } }; let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); let mut local_ok = 0usize; let mut elsewhere = 0usize; let mut remote_ok = 0usize; for row in &rows { match row.location.as_str() { "local" => {} "in" => { elsewhere += 1; if let Some(store) = remote { match digest_remote(store, &row.id).await { Ok((size, _)) if size != row.size => report.problem(format!( "attachment {} is {size} bytes at the Files service, the row says {}", row.id, row.size )), Ok((_, digest)) if digest != row.sha256 => report.problem(format!( "attachment {} fails its sha256 at the Files service", row.id )), Ok(_) => remote_ok += 1, Err(reason) => report.problem(format!( "attachment {} cannot be read from the Files service: {reason}", row.id )), } } continue; } other => { report.problem(format!( "attachment {} is in location {other}; a move did not finish", row.id )); continue; } } let path = match blob_path(data_dir, &row.id) { Ok(path) => path, Err(_) => { report.problem(format!("attachment id {} is not a canonical ULID", row.id)); continue; } }; match std::fs::symlink_metadata(&path) { Err(_) => { report.problem(format!( "attachment {} has no file at {}", row.id, path.display() )); continue; } Ok(meta) if !meta.file_type().is_file() => { report.problem(format!("attachment {} is not a regular file", row.id)); continue; } Ok(_) => {} } match digest_file(&path) { Ok((size, _)) if size != row.size => report.problem(format!( "attachment {} is {size} bytes, the row says {}", row.id, row.size )), Ok((_, digest)) if digest != row.sha256 => { report.problem(format!("attachment {} fails its sha256", row.id)); } Ok(_) => local_ok += 1, Err(error) => report.problem(format!( "attachment {} cannot be read: {}", row.id, describe(&error) )), } } match remote { Some(_) => report.ok(format!( "{local_ok} local attachments match their rows; {remote_ok} of {elsewhere} held at the Files service match their rows" )), None => report.ok(format!( "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" )), } // Files in the attachments directory that no row names. They are reported; nothing is deleted. match std::fs::read_dir(&attachments_dir) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => { if local_ok > 0 { report.problem("the attachments directory does not exist".to_owned()); } } Err(error) => report.problem(format!("cannot list the attachments directory: {error}")), Ok(entries) => { let mut unnamed = 0usize; for entry in entries { let Ok(entry) = entry else { report.problem("cannot read an entry of the attachments directory".to_owned()); continue; }; let name = entry.file_name().to_string_lossy().into_owned(); if !known.contains(name.as_str()) { unnamed += 1; report.problem(format!("file {name} in attachments is named by no row")); } } if unnamed == 0 { report.ok("every file in attachments is named by a row"); } } } } #[cfg(test)] mod tests { use super::*; use iz_core::authz::Role; use iz_core::store::members::DirectoryMember; /// An attachment whose bytes were edited after the row was written must be reported. The check runs /// on a real database file built by the store, in a temp directory. #[tokio::test] async fn fsck_reports_an_edited_attachment() { let root = tempfile::tempdir().expect("temp dir"); let data = root.path().join("data"); std::fs::create_dir_all(&data).expect("data dir"); let db_path = data.join("iz.db"); let store = iz_core::store::Store::open(&db_path).await.expect("store"); let (board_id, task_id, member) = seed_task(&store).await; let id = iz_core::store::new_id(); let bytes = b"original attachment bytes"; let sha256 = hex::encode(::digest(bytes)); store .add_attachment( &board_id, &task_id, iz_core::store::attachments::NewAttachment { id: id.clone(), name: "note.txt".into(), mime: "text/plain".into(), size: bytes.len() as u64, sha256, uploaded_by: member, }, ) .await .expect("row"); let blob = blob_path(&data, &id).expect("path"); std::fs::create_dir_all(blob.parent().expect("parent")).expect("attachments dir"); std::fs::write(&blob, bytes).expect("bytes"); drop(store); let config = Config::parse(&format!( "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", db_path.display(), data.display(), )) .expect("config"); let mut clean = Report::default(); check( &config, &data.canonicalize().expect("canonical"), None, &mut clean, ) .await; assert_eq!( clean.problems, 0, "untouched data is clean: {:?}", clean.lines ); std::fs::write(&blob, b"edited attachment bytes!").expect("edit"); let mut dirty = Report::default(); check( &config, &data.canonicalize().expect("canonical"), None, &mut dirty, ) .await; assert!( dirty.problems > 0, "the edit is reported: {:?}", dirty.lines ); assert!( dirty.lines.iter().any(|line| line.contains(&id)), "the report names the attachment: {:?}", dirty.lines ); } /// One board, one task and the member who makes it. Returns (board id, task id, member sub). async fn seed_task(store: &iz_core::store::Store) -> (String, String, String) { let board = store.ensure_board("IZ").await.expect("board"); let member = DirectoryMember { sub: "ada".into(), email: "ada@example.com".into(), name: "Ada".into(), im_admin: false, disabled: false, locale: None, zoneinfo: "UTC".into(), picture_version: 0, updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store .apply_directory_member(&member, Role::Admin) .await .expect("member"); let member = member.sub; let columns = store.columns(&board.id).await.expect("columns"); let tags = store.tags(&board.id).await.expect("tags"); let task = store .create_task( &board.id, iz_core::store::tasks::NewTask { title: "Task".into(), description: String::new(), column_id: columns[0].id.clone(), tag_id: tags[0].id.clone(), deadline: None, meeting_at: None, assignees: Vec::new(), parent_id: None, link: None, }, &member, ) .await .expect("task"); (board.id, task.id, member) } }