//! Documents in a bucket, where the server keeps them: an upload lands there //! encrypted and opens, downloads and goes again; the check finds what is //! wrong; the files of a directory move into the bucket, again and again //! without harm; the mirror for the backups follows the bucket and fills a //! new one; a busy server is asked again and a wrong key is an error. use std::time::Duration; use axum::http::StatusCode; use sqlx::PgPool; use visa::config::{Auth, Config, FilesConfig, FilesPlace}; use visa::documents; use visa::files::{self, FileKey, Mirrored, Store}; use visa::s3::Bucket; use crate::common::fake_s3::FakeS3; use crate::common::{App, bucket_config, config, files_dir, local, pdf, with_config}; use crate::documents::person; fn on_bucket(pool: &PgPool, s3: &FakeS3) -> App { with_config(pool.clone(), bucket_config(Auth::Disabled, s3)) } fn object(id: i64) -> String { format!("documents/{id}.vdoc") } async fn ids(pool: &PgPool) -> Vec { sqlx::query_scalar("SELECT id FROM documents ORDER BY id") .fetch_all(pool) .await .unwrap() } /// Uploads one PDF per text to the person's documents. async fn upload(app: &App, person: i64, texts: &[&str]) { for t in texts { let r = app .upload( &format!("/people/{person}/documents"), &[("kind", "other")], &[(&format!("{t}.pdf"), &pdf(t))], ) .await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); } } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn an_upload_lies_encrypted_in_the_bucket_and_goes_with_its_document(pool: PgPool) { let s3 = FakeS3::start().await; let app = on_bucket(&pool, &s3); let id = person(&app, "Doe").await; let base = format!("/people/{id}/documents"); let scan = pdf("the photo page of a passport"); let r = app .upload( &base, &[("kind", "passport-photo-page")], &[("scan.pdf", &scan)], ) .await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); let did = ids(&pool).await[0]; // in the bucket under its id, encrypted, and nothing else there assert_eq!(s3.keys(), [object(did)]); let stored = s3.object(&object(did)).unwrap(); assert!(stored.starts_with(b"VISADOC1")); assert!(!stored.windows(10).any(|w| w == b"photo page")); // the write asked the server not to replace anything let put = format!("PUT /visa-documents/{} if-none-match", object(did)); assert!(s3.requests().contains(&put), "{:?}", s3.requests()); // it opens and downloads as it was uploaded let file = format!("{base}/{did}/file"); let r = app.get(&file).await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.bytes, scan); let r = app.get(&format!("{file}?download=1")).await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.bytes, scan); // the check reads it back from the bucket let store = app.st.files.as_ref().unwrap(); assert!( store .describe() .starts_with("bucket visa-documents at http://127.0.0.1:") ); store.check().await.unwrap(); let check = documents::check(&pool, store).await.unwrap(); assert_eq!(check.documents, 1); assert!(check.problems.is_empty(), "{:?}", check.problems); // deleted: the object goes with the row let r = app.post(&format!("{base}/{did}/delete"), &[]).await; assert_eq!(r.status, StatusCode::SEE_OTHER); assert!(s3.keys().is_empty(), "{:?}", s3.keys()); assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND); } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn the_check_finds_swapped_missing_and_stray_objects(pool: PgPool) { let s3 = FakeS3::start().await; let app = on_bucket(&pool, &s3); let id = person(&app, "Doe").await; upload(&app, id, &["first", "second", "third", "fourth"]).await; let ids = ids(&pool).await; let store = app.st.files.as_ref().unwrap(); assert!( documents::check(&pool, store) .await .unwrap() .problems .is_empty() ); // the first two swapped, the third gone, two objects of no document let (a, b) = ( s3.object(&object(ids[0])).unwrap(), s3.object(&object(ids[1])).unwrap(), ); s3.put(&object(ids[0]), &b); s3.put(&object(ids[1]), &a); s3.remove(&object(ids[2])); s3.put(&object(77), b"left over"); s3.put("notes.txt", b"not ours"); let r = app .get(&format!("/people/{id}/documents/{}/file", ids[0])) .await; assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR); assert!(r.text().contains("cannot be opened"), "{}", r.body); assert!(!r.bytes.windows(6).any(|w| w == b"second")); // five objects, read in pages of two let check = documents::check(&pool, store).await.unwrap(); let p = &check.problems; assert_eq!(p.len(), 5, "{p:?}"); assert!( p[0].contains("damaged, or the file of another document"), "{p:?}" ); assert!( p[1].contains("damaged, or the file of another document"), "{p:?}" ); assert!(p[2].contains("is missing"), "{p:?}"); assert!( p[3].contains("77.vdoc: a file without its document"), "{p:?}" ); assert!(p[4].contains("notes.txt: not a file of the store"), "{p:?}"); let lists = s3 .requests() .iter() .filter(|r| r.contains("list-type=2")) .count(); assert!(lists >= 3, "{:?}", s3.requests()); } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn the_files_move_from_their_directory_into_the_bucket(pool: PgPool) { // before: the files in a directory, as on the server until now let before = local(pool.clone()); let id = person(&before, "Doe").await; upload(&before, id, &["passport", "receipt"]).await; let ids = ids(&pool).await; let old = before.st.files.as_ref().unwrap(); let dir = old.dir().unwrap().to_path_buf(); let key = old.file_key().clone(); std::fs::write(dir.join("99.vdoc"), b"no document's").unwrap(); std::fs::write(dir.join(".98.vdoc.part"), b"cut short").unwrap(); let e = documents::migrate(&pool, &dir, old).await.unwrap_err(); assert!(e.to_string().contains("the store itself"), "{e}"); // after: the same key, the files in the bucket, byte for byte let s3 = FakeS3::start().await; let store = Store::in_bucket(&s3.config(), key.clone()).unwrap(); let moved = documents::migrate(&pool, &dir, &store).await.unwrap(); assert_eq!((moved.copied, moved.there), (2, 0)); assert_eq!(moved.strays, ["99.vdoc", ".98.vdoc.part"]); assert!(moved.missing.is_empty()); for id in &ids { let on_disk = std::fs::read(dir.join(files::file_name(*id))).unwrap(); assert_eq!(s3.object(&object(*id)).unwrap(), on_disk); } assert!(s3.object(&object(99)).is_none(), "strays stay behind"); // the app on the bucket opens them let after = with_config( pool.clone(), Config { files: Some(FilesConfig { place: FilesPlace::Bucket(s3.config()), key: key.clone(), }), ..config(Auth::Disabled) }, ); for (id_, text) in ids.iter().zip(["passport", "receipt"]) { let r = after .get(&format!("/people/{id}/documents/{id_}/file")) .await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.bytes, pdf(text)); } // again: nothing to copy, so a stopped run can simply start over let moved = documents::migrate(&pool, &dir, &store).await.unwrap(); assert_eq!((moved.copied, moved.there), (0, 2)); // a file in neither place is reported, not invented std::fs::remove_file(dir.join(files::file_name(ids[1]))).unwrap(); s3.remove(&object(ids[1])); let moved = documents::migrate(&pool, &dir, &store).await.unwrap(); assert_eq!(moved.missing, [ids[1]]); // the bucket holding other bytes for a document stops the copy, and // the object stays as it is s3.put(&object(ids[0]), b"other bytes"); let e = documents::migrate(&pool, &dir, &store).await.unwrap_err(); assert!(format!("{e:#}").contains("other bytes"), "{e:#}"); assert_eq!(s3.object(&object(ids[0])).unwrap(), b"other bytes"); // a damaged file in the directory is never copied s3.remove(&object(ids[0])); let path = dir.join(files::file_name(ids[0])); let mut damaged = std::fs::read(&path).unwrap(); let last = damaged.len() - 20; damaged[last] ^= 1; std::fs::write(&path, damaged).unwrap(); let e = documents::migrate(&pool, &dir, &store).await.unwrap_err(); assert!(format!("{e:#}").contains("damaged"), "{e:#}"); assert!(s3.object(&object(ids[0])).is_none()); } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn the_mirror_follows_the_bucket_and_fills_a_new_one(pool: PgPool) { let s3 = FakeS3::start().await; let app = on_bucket(&pool, &s3); let id = person(&app, "Doe").await; upload(&app, id, &["one", "two", "three"]).await; let ids = ids(&pool).await; let store = app.st.files.as_ref().unwrap(); let mirror = files_dir(); let m = files::mirror(store, &mirror).await.unwrap(); assert_eq!( m, Mirrored { copied: 3, kept: 0, removed: 0 } ); for id in &ids { assert_eq!( std::fs::read(mirror.join(files::file_name(*id))).unwrap(), s3.object(&object(*id)).unwrap() ); } // a deletion reaches the mirror at its next run let r = app .post(&format!("/people/{id}/documents/{}/delete", ids[2]), &[]) .await; assert_eq!(r.status, StatusCode::SEE_OTHER); let m = files::mirror(store, &mirror).await.unwrap(); assert_eq!( m, Mirrored { copied: 0, kept: 2, removed: 1 } ); // the bucket is lost: a new one is filled from the mirror and checks // out against the database let fresh = FakeS3::start().await; let restored = Store::in_bucket(&fresh.config(), store.file_key().clone()).unwrap(); let moved = documents::migrate(&pool, &mirror, &restored).await.unwrap(); assert_eq!((moved.copied, moved.there), (2, 0)); let check = documents::check(&pool, &restored).await.unwrap(); assert_eq!(check.documents, 2); assert!(check.problems.is_empty(), "{:?}", check.problems); std::fs::remove_dir_all(&mirror).ok(); } #[tokio::test] async fn a_busy_server_is_asked_again_and_a_wrong_key_is_an_error() { let s3 = FakeS3::start().await; let key = FileKey::random(); let bucket = Bucket::new(&s3.config()) .unwrap() .with_pause(Duration::from_millis(10)); let store = Store::with_bucket(bucket, key.clone()); // two refusals, then an answer: the third attempt goes through s3.fail_next(2); store.put(5, pdf("five")).await.unwrap(); assert_eq!(store.get(5).await.unwrap(), pdf("five")); // three refusals are an error that says what happened s3.fail_next(3); let e = store.get(5).await.unwrap_err(); assert!(format!("{e:#}").contains("HTTP 503 SlowDown"), "{e:#}"); // the same id again: refused, and the object stays let e = store.put(5, pdf("other")).await.unwrap_err(); assert!(format!("{e:#}").contains("other bytes"), "{e:#}"); assert_eq!(store.get(5).await.unwrap(), pdf("five")); // a wrong secret is refused, never taken for a missing file let mut cfg = s3.config(); cfg.secret_access_key = "wrong".into(); let wrong = Store::in_bucket(&cfg, key.clone()).unwrap(); let e = wrong.get(5).await.unwrap_err(); assert!(format!("{e:#}").contains("SignatureDoesNotMatch"), "{e:#}"); assert!(wrong.check().await.is_err()); assert!(store.check().await.is_ok()); // a bucket that does not exist is not a missing file either let mut cfg = s3.config(); cfg.bucket = "other-bucket".into(); let other = Store::in_bucket(&cfg, key).unwrap(); let e = other.get_sealed(5).await.unwrap_err(); assert!(format!("{e:#}").contains("NoSuchBucket"), "{e:#}"); // no secret in any of these messages assert!(!format!("{e:#}").contains(crate::common::fake_s3::SECRET)); }