| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::collections::HashSet; |
| 14 | use std::path::Path; |
| 15 | use std::process::ExitCode; |
| 16 | use std::sync::Arc; |
| 17 | |
| 18 | use futures_util::StreamExt; |
| 19 | use iz_core::config::Config; |
| 20 | use iz_core::manifest::digest_file; |
| 21 | use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; |
| 22 | use iz_core::store::export::{ReadOnly, migrations_problem}; |
| 23 | use sha2::{Digest, Sha256}; |
| 24 | |
| 25 | use super::{database_file, describe, existing_data_dir, fail, take_lock}; |
| 26 | use crate::in_store::InStore; |
| 27 | use crate::oidc::{self, OidcClient}; |
| 28 | |
| 29 | |
| 30 | |
| 31 | pub async fn run(config_path: &Path, remote: bool) -> ExitCode { |
| 32 | let config = match Config::load(config_path) { |
| 33 | Ok(config) => config, |
| 34 | Err(error) => return fail(describe(&error)), |
| 35 | }; |
| 36 | let data_dir = match existing_data_dir(&config) { |
| 37 | Ok(dir) => dir, |
| 38 | Err(message) => return fail(message), |
| 39 | }; |
| 40 | let _lock = match take_lock(&data_dir) { |
| 41 | Ok(lock) => lock, |
| 42 | Err(code) => return code, |
| 43 | }; |
| 44 | let remote = if remote { |
| 45 | match remote_store(&config) { |
| 46 | Ok(store) => Some(store), |
| 47 | Err(message) => return fail(message), |
| 48 | } |
| 49 | } else { |
| 50 | None |
| 51 | }; |
| 52 | let mut report = Report::default(); |
| 53 | check(&config, &data_dir, remote.as_ref(), &mut report).await; |
| 54 | for line in &report.lines { |
| 55 | println!("{line}"); |
| 56 | } |
| 57 | if report.problems == 0 { |
| 58 | println!("fsck: clean"); |
| 59 | ExitCode::SUCCESS |
| 60 | } else { |
| 61 | println!("fsck: {} problems found", report.problems); |
| 62 | ExitCode::FAILURE |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | |
| 67 | #[derive(Default)] |
| 68 | struct Report { |
| 69 | |
| 70 | lines: Vec<String>, |
| 71 | |
| 72 | problems: usize, |
| 73 | } |
| 74 | |
| 75 | impl Report { |
| 76 | |
| 77 | fn ok(&mut self, text: impl Into<String>) { |
| 78 | self.lines.push(format!("ok: {}", text.into())); |
| 79 | } |
| 80 | |
| 81 | |
| 82 | fn problem(&mut self, text: impl Into<String>) { |
| 83 | self.problems += 1; |
| 84 | self.lines.push(format!("problem: {}", text.into())); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | fn remote_store(config: &Config) -> Result<InStore, String> { |
| 91 | if !config.in_store.enabled { |
| 92 | return Err("--remote needs in_store.enabled = true in the configuration".into()); |
| 93 | } |
| 94 | let url = config |
| 95 | .in_store |
| 96 | .url |
| 97 | .as_deref() |
| 98 | .ok_or("--remote needs in_store.url in the configuration")?; |
| 99 | let oidc_config = config |
| 100 | .oidc |
| 101 | .as_ref() |
| 102 | .ok_or("--remote needs the [oidc] section in the configuration")?; |
| 103 | let secret = |
| 104 | oidc::read_client_secret(&oidc_config.client_secret_file).map_err(|e| describe(&e))?; |
| 105 | let client = |
| 106 | OidcClient::new(oidc_config, &config.base_url, secret).map_err(|e| describe(&e))?; |
| 107 | InStore::new(url, Arc::new(client)).map_err(|e| describe(&e)) |
| 108 | } |
| 109 | |
| 110 | |
| 111 | |
| 112 | async fn digest_remote(store: &InStore, id: &str) -> Result<(u64, String), String> { |
| 113 | let response = store |
| 114 | .get(id, None) |
| 115 | .await |
| 116 | .map_err(|error| error.to_string())?; |
| 117 | let mut hasher = Sha256::new(); |
| 118 | let mut size: u64 = 0; |
| 119 | let mut chunks = response.bytes_stream(); |
| 120 | while let Some(chunk) = chunks.next().await { |
| 121 | let chunk = chunk.map_err(|error| error.to_string())?; |
| 122 | size += chunk.len() as u64; |
| 123 | hasher.update(&chunk); |
| 124 | } |
| 125 | Ok((size, hex::encode(hasher.finalize()))) |
| 126 | } |
| 127 | |
| 128 | |
| 129 | async fn check(config: &Config, data_dir: &Path, remote: Option<&InStore>, report: &mut Report) { |
| 130 | let attachments_dir = data_dir.join(ATTACHMENTS_DIR); |
| 131 | let database = match database_file(config) { |
| 132 | Ok(path) => path, |
| 133 | Err(message) => { |
| 134 | report.problem(message); |
| 135 | return; |
| 136 | } |
| 137 | }; |
| 138 | let db = match ReadOnly::open(&database).await { |
| 139 | Ok(db) => db, |
| 140 | Err(error) => { |
| 141 | report.problem(format!("cannot open the database: {}", describe(&error))); |
| 142 | return; |
| 143 | } |
| 144 | }; |
| 145 | match db.integrity_check().await { |
| 146 | Ok(rows) if rows == ["ok"] => report.ok("database integrity_check"), |
| 147 | Ok(rows) => report.problem(format!("integrity_check: {}", rows.join("; "))), |
| 148 | Err(error) => report.problem(format!("integrity_check failed: {}", describe(&error))), |
| 149 | } |
| 150 | match db.migration_versions().await { |
| 151 | Ok(versions) => match migrations_problem(&versions) { |
| 152 | None => report.ok(format!("migrations 1 to {} are contiguous", versions.len())), |
| 153 | Some(problem) => report.problem(problem), |
| 154 | }, |
| 155 | Err(error) => report.problem(format!("cannot read migrations: {}", describe(&error))), |
| 156 | } |
| 157 | let rows = match db.attachment_rows().await { |
| 158 | Ok(rows) => rows, |
| 159 | Err(error) => { |
| 160 | report.problem(format!("cannot read attachments: {}", describe(&error))); |
| 161 | return; |
| 162 | } |
| 163 | }; |
| 164 | |
| 165 | let known: HashSet<&str> = rows.iter().map(|row| row.id.as_str()).collect(); |
| 166 | let mut local_ok = 0usize; |
| 167 | let mut elsewhere = 0usize; |
| 168 | let mut remote_ok = 0usize; |
| 169 | for row in &rows { |
| 170 | match row.location.as_str() { |
| 171 | "local" => {} |
| 172 | "in" => { |
| 173 | elsewhere += 1; |
| 174 | if let Some(store) = remote { |
| 175 | match digest_remote(store, &row.id).await { |
| 176 | Ok((size, _)) if size != row.size => report.problem(format!( |
| 177 | "attachment {} is {size} bytes at the Files service, the row says {}", |
| 178 | row.id, row.size |
| 179 | )), |
| 180 | Ok((_, digest)) if digest != row.sha256 => report.problem(format!( |
| 181 | "attachment {} fails its sha256 at the Files service", |
| 182 | row.id |
| 183 | )), |
| 184 | Ok(_) => remote_ok += 1, |
| 185 | Err(reason) => report.problem(format!( |
| 186 | "attachment {} cannot be read from the Files service: {reason}", |
| 187 | row.id |
| 188 | )), |
| 189 | } |
| 190 | } |
| 191 | continue; |
| 192 | } |
| 193 | other => { |
| 194 | report.problem(format!( |
| 195 | "attachment {} is in location {other}; a move did not finish", |
| 196 | row.id |
| 197 | )); |
| 198 | continue; |
| 199 | } |
| 200 | } |
| 201 | let path = match blob_path(data_dir, &row.id) { |
| 202 | Ok(path) => path, |
| 203 | Err(_) => { |
| 204 | report.problem(format!("attachment id {} is not a canonical ULID", row.id)); |
| 205 | continue; |
| 206 | } |
| 207 | }; |
| 208 | match std::fs::symlink_metadata(&path) { |
| 209 | Err(_) => { |
| 210 | report.problem(format!( |
| 211 | "attachment {} has no file at {}", |
| 212 | row.id, |
| 213 | path.display() |
| 214 | )); |
| 215 | continue; |
| 216 | } |
| 217 | Ok(meta) if !meta.file_type().is_file() => { |
| 218 | report.problem(format!("attachment {} is not a regular file", row.id)); |
| 219 | continue; |
| 220 | } |
| 221 | Ok(_) => {} |
| 222 | } |
| 223 | match digest_file(&path) { |
| 224 | Ok((size, _)) if size != row.size => report.problem(format!( |
| 225 | "attachment {} is {size} bytes, the row says {}", |
| 226 | row.id, row.size |
| 227 | )), |
| 228 | Ok((_, digest)) if digest != row.sha256 => { |
| 229 | report.problem(format!("attachment {} fails its sha256", row.id)); |
| 230 | } |
| 231 | Ok(_) => local_ok += 1, |
| 232 | Err(error) => report.problem(format!( |
| 233 | "attachment {} cannot be read: {}", |
| 234 | row.id, |
| 235 | describe(&error) |
| 236 | )), |
| 237 | } |
| 238 | } |
| 239 | match remote { |
| 240 | Some(_) => report.ok(format!( |
| 241 | "{local_ok} local attachments match their rows; {remote_ok} of {elsewhere} held at the Files service match their rows" |
| 242 | )), |
| 243 | None => report.ok(format!( |
| 244 | "{local_ok} local attachments match their rows; {elsewhere} are held elsewhere and not checked" |
| 245 | )), |
| 246 | } |
| 247 | |
| 248 | |
| 249 | match std::fs::read_dir(&attachments_dir) { |
| 250 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 251 | if local_ok > 0 { |
| 252 | report.problem("the attachments directory does not exist".to_owned()); |
| 253 | } |
| 254 | } |
| 255 | Err(error) => report.problem(format!("cannot list the attachments directory: {error}")), |
| 256 | Ok(entries) => { |
| 257 | let mut unnamed = 0usize; |
| 258 | for entry in entries { |
| 259 | let Ok(entry) = entry else { |
| 260 | report.problem("cannot read an entry of the attachments directory".to_owned()); |
| 261 | continue; |
| 262 | }; |
| 263 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 264 | if !known.contains(name.as_str()) { |
| 265 | unnamed += 1; |
| 266 | report.problem(format!("file {name} in attachments is named by no row")); |
| 267 | } |
| 268 | } |
| 269 | if unnamed == 0 { |
| 270 | report.ok("every file in attachments is named by a row"); |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | #[cfg(test)] |
| 277 | mod tests { |
| 278 | use super::*; |
| 279 | use iz_core::authz::Role; |
| 280 | use iz_core::store::members::DirectoryMember; |
| 281 | |
| 282 | |
| 283 | |
| 284 | #[tokio::test] |
| 285 | async fn fsck_reports_an_edited_attachment() { |
| 286 | let root = tempfile::tempdir().expect("temp dir"); |
| 287 | let data = root.path().join("data"); |
| 288 | std::fs::create_dir_all(&data).expect("data dir"); |
| 289 | let db_path = data.join("iz.db"); |
| 290 | let store = iz_core::store::Store::open(&db_path).await.expect("store"); |
| 291 | let (board_id, task_id, member) = seed_task(&store).await; |
| 292 | let id = iz_core::store::new_id(); |
| 293 | let bytes = b"original attachment bytes"; |
| 294 | let sha256 = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(bytes)); |
| 295 | store |
| 296 | .add_attachment( |
| 297 | &board_id, |
| 298 | &task_id, |
| 299 | iz_core::store::attachments::NewAttachment { |
| 300 | id: id.clone(), |
| 301 | name: "note.txt".into(), |
| 302 | mime: "text/plain".into(), |
| 303 | size: bytes.len() as u64, |
| 304 | sha256, |
| 305 | uploaded_by: member, |
| 306 | }, |
| 307 | ) |
| 308 | .await |
| 309 | .expect("row"); |
| 310 | let blob = blob_path(&data, &id).expect("path"); |
| 311 | std::fs::create_dir_all(blob.parent().expect("parent")).expect("attachments dir"); |
| 312 | std::fs::write(&blob, bytes).expect("bytes"); |
| 313 | drop(store); |
| 314 | |
| 315 | let config = Config::parse(&format!( |
| 316 | "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7654\"\nbase_url = \"http://127.0.0.1:7654\"\n", |
| 317 | db_path.display(), |
| 318 | data.display(), |
| 319 | )) |
| 320 | .expect("config"); |
| 321 | let mut clean = Report::default(); |
| 322 | check( |
| 323 | &config, |
| 324 | &data.canonicalize().expect("canonical"), |
| 325 | None, |
| 326 | &mut clean, |
| 327 | ) |
| 328 | .await; |
| 329 | assert_eq!( |
| 330 | clean.problems, 0, |
| 331 | "untouched data is clean: {:?}", |
| 332 | clean.lines |
| 333 | ); |
| 334 | |
| 335 | std::fs::write(&blob, b"edited attachment bytes!").expect("edit"); |
| 336 | let mut dirty = Report::default(); |
| 337 | check( |
| 338 | &config, |
| 339 | &data.canonicalize().expect("canonical"), |
| 340 | None, |
| 341 | &mut dirty, |
| 342 | ) |
| 343 | .await; |
| 344 | assert!( |
| 345 | dirty.problems > 0, |
| 346 | "the edit is reported: {:?}", |
| 347 | dirty.lines |
| 348 | ); |
| 349 | assert!( |
| 350 | dirty.lines.iter().any(|line| line.contains(&id)), |
| 351 | "the report names the attachment: {:?}", |
| 352 | dirty.lines |
| 353 | ); |
| 354 | } |
| 355 | |
| 356 | |
| 357 | async fn seed_task(store: &iz_core::store::Store) -> (String, String, String) { |
| 358 | let board = store.ensure_board("IZ").await.expect("board"); |
| 359 | let member = DirectoryMember { |
| 360 | sub: "ada".into(), |
| 361 | email: "ada@example.com".into(), |
| 362 | name: "Ada".into(), |
| 363 | im_admin: false, |
| 364 | disabled: false, |
| 365 | locale: None, |
| 366 | zoneinfo: "UTC".into(), |
| 367 | picture_version: 0, |
| 368 | updated_at: "2026-10-28T09:00:00.000000000Z".into(), |
| 369 | }; |
| 370 | store |
| 371 | .apply_directory_member(&member, Role::Admin) |
| 372 | .await |
| 373 | .expect("member"); |
| 374 | let member = member.sub; |
| 375 | let columns = store.columns(&board.id).await.expect("columns"); |
| 376 | let tags = store.tags(&board.id).await.expect("tags"); |
| 377 | let task = store |
| 378 | .create_task( |
| 379 | &board.id, |
| 380 | iz_core::store::tasks::NewTask { |
| 381 | title: "Task".into(), |
| 382 | description: String::new(), |
| 383 | column_id: columns[0].id.clone(), |
| 384 | tag_id: tags[0].id.clone(), |
| 385 | deadline: None, |
| 386 | meeting_at: None, |
| 387 | assignees: Vec::new(), |
| 388 | parent_id: None, |
| 389 | link: None, |
| 390 | }, |
| 391 | &member, |
| 392 | ) |
| 393 | .await |
| 394 | .expect("task"); |
| 395 | (board.id, task.id, member) |
| 396 | } |
| 397 | } |