diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 0e62717..87c6ec5 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -1833,20 +1833,18 @@ mod tests { } #[tokio::test] - async fn new_user_has_default_profile() { + async fn profile_defaults_round_trip_and_validate() { let dir = tempfile::tempdir().unwrap(); let (store, user) = store_with_user(&dir).await; + + // Scenario: a new user has an empty bio and UTC. assert_eq!(user.about, ""); assert_eq!(user.timezone, "UTC"); let fetched = store.user_by_id(&user.id).await.unwrap().unwrap(); assert_eq!(fetched.about, ""); assert_eq!(fetched.timezone, "UTC"); - } - #[tokio::test] - async fn set_profile_round_trips_and_validates() { - let dir = tempfile::tempdir().unwrap(); - let (store, user) = store_with_user(&dir).await; + // Scenario: a valid profile is saved; invalid input is refused and changes nothing. store .set_profile(&user.id, "Hello *world*", "Europe/Istanbul") .await @@ -1934,12 +1932,13 @@ mod tests { } #[tokio::test] - async fn avatar_upsert_hash_delete() { + async fn avatar_upsert_hash_delete_and_removed_with_its_user() { let dir = tempfile::tempdir().unwrap(); let (store, user) = store_with_user(&dir).await; + + // Scenario: upsert replaces the image and its hash; delete is idempotent. assert_eq!(store.avatar(&user.id).await.unwrap(), None); assert_eq!(store.avatar_hash(&user.id).await.unwrap(), None); - store.set_avatar(&user.id, b"png-1", "aaaa").await.unwrap(); store.set_avatar(&user.id, b"png-2", "bbbb").await.unwrap(); assert_eq!( @@ -1950,31 +1949,33 @@ mod tests { store.avatar_hash(&user.id).await.unwrap().as_deref(), Some("bbbb") ); - store.delete_avatar(&user.id).await.unwrap(); store.delete_avatar(&user.id).await.unwrap(); assert_eq!(store.avatar(&user.id).await.unwrap(), None); - } - #[tokio::test] - async fn avatar_is_removed_with_its_user() { - let dir = tempfile::tempdir().unwrap(); - let (store, user) = store_with_user(&dir).await; - store.set_avatar(&user.id, b"png", "cccc").await.unwrap(); + // Scenario: deleting the user row removes its avatar with it. + let doomed = store + .create_user("Doomed", None, "hash", false) + .await + .unwrap(); + store.set_avatar(&doomed.id, b"png", "cccc").await.unwrap(); { let conn = store.inner.conn.lock().await; - conn.execute("DELETE FROM users WHERE id = ?1", (user.id.clone(),)) + conn.execute("DELETE FROM users WHERE id = ?1", (doomed.id.clone(),)) .await .unwrap(); } - assert_eq!(store.avatar(&user.id).await.unwrap(), None); + assert_eq!(store.avatar(&doomed.id).await.unwrap(), None); } #[tokio::test] - async fn delete_repo_removes_repo_and_children_atomically() { + async fn delete_repo_scenarios() { let dir = tempfile::tempdir().unwrap(); let (store, tahinli) = store_with_user(&dir).await; let bob = store.create_user("Bob", None, "hash", false).await.unwrap(); + + // Scenario: deleting a repo removes its collaborators, push events and branch + // rules atomically, and leaves the other repo and its rows untouched. let keep = store .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main") .await @@ -1987,14 +1988,16 @@ mod tests { .set_collaborator(&gone.id, &bob.id, Role::Write) .await .unwrap(); - store - .record_push_event(&gone.id, &tahinli.id, "refs/heads/main", "0", "1", "https") - .await - .unwrap(); - store - .record_push_event(&keep.id, &tahinli.id, "refs/heads/main", "0", "1", "https") - .await - .unwrap(); + for repo in [&gone, &keep] { + store + .record_push_event(&repo.id, &tahinli.id, "refs/heads/main", "0", "1", "https") + .await + .unwrap(); + store + .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(false, false)) + .await + .unwrap(); + } store.delete_repo(&gone.id).await.unwrap(); @@ -2008,14 +2011,18 @@ mod tests { for (sql, expect) in [ ("SELECT COUNT(*) FROM push_events WHERE repo_id = ?1", 0i64), ("SELECT COUNT(*) FROM collaborators WHERE repo_id = ?1", 0), + ( + "SELECT COUNT(*) FROM branch_protections WHERE repo_id = ?1", + 0, + ), ] { let mut rows = conn.query(sql, (gone.id.clone(),)).await.unwrap(); let row = rows.next().await.unwrap().unwrap(); assert_eq!(col_int(&row, 0).unwrap(), expect, "{sql}"); } } - // The other repo and its events are untouched. assert!(store.repo_by_id(&keep.id).await.unwrap().is_some()); + assert_eq!(store.list_branch_rules(&keep.id).await.unwrap().len(), 1); { let conn = store.inner.conn.lock().await; let mut rows = conn @@ -2028,70 +2035,175 @@ mod tests { let row = rows.next().await.unwrap().unwrap(); assert_eq!(col_int(&row, 0).unwrap(), 1); } - } - #[tokio::test] - async fn delete_repo_missing_is_not_found_and_changes_nothing() { - let dir = tempfile::tempdir().unwrap(); - let (store, tahinli) = store_with_user(&dir).await; - let keep = store - .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main") + // Scenario: a missing id is NotFound; deleting twice reports NotFound the second time. + let later = store + .create_repo(&tahinli.id, "later", "", Visibility::Public, "main") .await .unwrap(); assert!(matches!( store.delete_repo("01m4yv0we1e0yew2ras7jnb9sk").await, Err(Error::NotFound) )); - assert!(store.repo_by_id(&keep.id).await.unwrap().is_some()); - // Deleting twice: the second call reports NotFound. - store.delete_repo(&keep.id).await.unwrap(); + assert!(store.repo_by_id(&later.id).await.unwrap().is_some()); + store.delete_repo(&later.id).await.unwrap(); assert!(matches!( - store.delete_repo(&keep.id).await, + store.delete_repo(&later.id).await, Err(Error::NotFound) )); } #[tokio::test] - async fn branch_rule_required_checks_round_trip_and_normalise() { + async fn branch_rule_scenarios() { let dir = tempfile::tempdir().unwrap(); let (store, owner) = store_with_user(&dir).await; - let repo = store - .create_repo(&owner.id, "proj", "", Visibility::Public, "main") - .await - .unwrap(); - let flags = RuleFlags { - required_checks: vec![ - " ci/test ".into(), - "lint".into(), - "ci/test".into(), - " ".into(), - ], - ..RuleFlags::default() - }; - let rule = store - .upsert_branch_rule(&repo.id, "main", flags) - .await - .unwrap(); - assert_eq!(rule.required_checks, vec!["ci/test", "lint"]); - assert_eq!( - store.list_branch_rules(&repo.id).await.unwrap()[0].required_checks, - vec!["ci/test", "lint"] - ); - // Saving without checks clears them; a control character is refused. - let cleared = store - .upsert_branch_rule(&repo.id, "main", RuleFlags::default()) - .await - .unwrap(); - assert!(cleared.required_checks.is_empty()); - let bad = RuleFlags { - required_checks: vec!["a\nb".into()], - ..RuleFlags::default() - }; - assert!(matches!( - store.upsert_branch_rule(&repo.id, "main", bad).await, - Err(Error::Invalid(_)) - )); + // Scenario: required checks are trimmed, de-duplicated and blanks dropped; + // saving without checks clears them; a control character is refused. + { + let repo = store + .create_repo(&owner.id, "checks", "", Visibility::Public, "main") + .await + .unwrap(); + let flags = RuleFlags { + required_checks: vec![ + " ci/test ".into(), + "lint".into(), + "ci/test".into(), + " ".into(), + ], + ..RuleFlags::default() + }; + let rule = store + .upsert_branch_rule(&repo.id, "main", flags) + .await + .unwrap(); + assert_eq!(rule.required_checks, vec!["ci/test", "lint"]); + assert_eq!( + store.list_branch_rules(&repo.id).await.unwrap()[0].required_checks, + vec!["ci/test", "lint"] + ); + let cleared = store + .upsert_branch_rule(&repo.id, "main", RuleFlags::default()) + .await + .unwrap(); + assert!(cleared.required_checks.is_empty()); + let bad = RuleFlags { + required_checks: vec!["a\nb".into()], + ..RuleFlags::default() + }; + assert!(matches!( + store.upsert_branch_rule(&repo.id, "main", bad).await, + Err(Error::Invalid(_)) + )); + } + + // Scenario: listing, upserting the same pattern updates in place, bad patterns refused. + { + let repo = store + .create_repo(&owner.id, "list", "", Visibility::Public, "main") + .await + .unwrap(); + assert!(store.list_branch_rules(&repo.id).await.unwrap().is_empty()); + + let main = store + .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(false, false)) + .await + .unwrap(); + store + .upsert_branch_rule(&repo.id, "release/*", RuleFlags::basic(true, false)) + .await + .unwrap(); + let rules = store.list_branch_rules(&repo.id).await.unwrap(); + let patterns: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect(); + assert_eq!(patterns, ["main", "release/*"]); + + // Same pattern updates the flags in place and keeps the id and created_at. + let updated = store + .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, true)) + .await + .unwrap(); + assert_eq!(updated.id, main.id); + assert_eq!(updated.created_at, main.created_at); + assert!(updated.allow_force_push && updated.allow_deletion); + let rules = store.list_branch_rules(&repo.id).await.unwrap(); + assert_eq!(rules.len(), 2); + assert_eq!(rules[0], updated); + + assert!(matches!( + store + .upsert_branch_rule(&repo.id, "refs/heads/x", RuleFlags::basic(false, false)) + .await, + Err(Error::Invalid(_)) + )); + } + + // Scenario: merge and push fields round-trip; an out-of-range value is refused. + { + let repo = store + .create_repo(&owner.id, "fields", "", Visibility::Public, "main") + .await + .unwrap(); + let flags = RuleFlags { + allow_force_push: false, + allow_deletion: false, + required_approvals: 20, + block_on_changes_requested: true, + require_up_to_date: true, + restrict_push: true, + require_merge_queue: true, + required_checks: Vec::new(), + }; + let saved = store + .upsert_branch_rule(&repo.id, "main", flags.clone()) + .await + .unwrap(); + assert_eq!(saved.required_approvals, 20); + assert!( + saved.block_on_changes_requested && saved.require_up_to_date && saved.restrict_push + ); + assert_eq!( + store.list_branch_rules(&repo.id).await.unwrap(), + vec![saved] + ); + + // Out of range is refused and stores nothing new. + let too_many = RuleFlags { + required_approvals: 21, + ..flags + }; + assert!(matches!( + store.upsert_branch_rule(&repo.id, "main", too_many).await, + Err(Error::Invalid(_)) + )); + let rules = store.list_branch_rules(&repo.id).await.unwrap(); + assert_eq!(rules[0].required_approvals, 20); + } + + // Scenario: deleting a rule is scoped to its own repo. + { + let a = store + .create_repo(&owner.id, "scope-a", "", Visibility::Public, "main") + .await + .unwrap(); + let b = store + .create_repo(&owner.id, "scope-b", "", Visibility::Public, "main") + .await + .unwrap(); + let rule_b = store + .upsert_branch_rule(&b.id, "main", RuleFlags::basic(false, false)) + .await + .unwrap(); + + assert!(matches!( + store.delete_branch_rule(&a.id, &rule_b.id).await, + Err(Error::NotFound) + )); + assert_eq!(store.list_branch_rules(&b.id).await.unwrap().len(), 1); + + store.delete_branch_rule(&b.id, &rule_b.id).await.unwrap(); + assert!(store.list_branch_rules(&b.id).await.unwrap().is_empty()); + } } #[tokio::test] @@ -2137,157 +2249,6 @@ mod tests { .is_empty() ); } - - #[tokio::test] - async fn branch_rules_list_upsert_and_update() { - let dir = tempfile::tempdir().unwrap(); - let (store, tahinli) = store_with_user(&dir).await; - let repo = store - .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") - .await - .unwrap(); - assert!(store.list_branch_rules(&repo.id).await.unwrap().is_empty()); - - let main = store - .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(false, false)) - .await - .unwrap(); - store - .upsert_branch_rule(&repo.id, "release/*", RuleFlags::basic(true, false)) - .await - .unwrap(); - let rules = store.list_branch_rules(&repo.id).await.unwrap(); - let patterns: Vec<&str> = rules.iter().map(|r| r.pattern.as_str()).collect(); - assert_eq!(patterns, ["main", "release/*"]); - - // Same pattern updates the flags in place and keeps the id and created_at. - let updated = store - .upsert_branch_rule(&repo.id, "main", RuleFlags::basic(true, true)) - .await - .unwrap(); - assert_eq!(updated.id, main.id); - assert_eq!(updated.created_at, main.created_at); - assert!(updated.allow_force_push && updated.allow_deletion); - let rules = store.list_branch_rules(&repo.id).await.unwrap(); - assert_eq!(rules.len(), 2); - assert_eq!(rules[0], updated); - - assert!(matches!( - store - .upsert_branch_rule(&repo.id, "refs/heads/x", RuleFlags::basic(false, false)) - .await, - Err(Error::Invalid(_)) - )); - } - - #[tokio::test] - async fn branch_rule_merge_and_push_fields_round_trip() { - let dir = tempfile::tempdir().unwrap(); - let (store, tahinli) = store_with_user(&dir).await; - let repo = store - .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") - .await - .unwrap(); - let flags = RuleFlags { - allow_force_push: false, - allow_deletion: false, - required_approvals: 20, - block_on_changes_requested: true, - require_up_to_date: true, - restrict_push: true, - require_merge_queue: true, - required_checks: Vec::new(), - }; - let saved = store - .upsert_branch_rule(&repo.id, "main", flags.clone()) - .await - .unwrap(); - assert_eq!(saved.required_approvals, 20); - assert!( - saved.block_on_changes_requested && saved.require_up_to_date && saved.restrict_push - ); - assert_eq!( - store.list_branch_rules(&repo.id).await.unwrap(), - vec![saved] - ); - - // Out of range is refused and stores nothing new. - let too_many = RuleFlags { - required_approvals: 21, - ..flags - }; - assert!(matches!( - store.upsert_branch_rule(&repo.id, "main", too_many).await, - Err(Error::Invalid(_)) - )); - let rules = store.list_branch_rules(&repo.id).await.unwrap(); - assert_eq!(rules[0].required_approvals, 20); - } - - #[tokio::test] - async fn branch_rule_delete_is_scoped_to_repo() { - let dir = tempfile::tempdir().unwrap(); - let (store, tahinli) = store_with_user(&dir).await; - let a = store - .create_repo(&tahinli.id, "a", "", Visibility::Public, "main") - .await - .unwrap(); - let b = store - .create_repo(&tahinli.id, "b", "", Visibility::Public, "main") - .await - .unwrap(); - let rule_b = store - .upsert_branch_rule(&b.id, "main", RuleFlags::basic(false, false)) - .await - .unwrap(); - - assert!(matches!( - store.delete_branch_rule(&a.id, &rule_b.id).await, - Err(Error::NotFound) - )); - assert_eq!(store.list_branch_rules(&b.id).await.unwrap().len(), 1); - - store.delete_branch_rule(&b.id, &rule_b.id).await.unwrap(); - assert!(store.list_branch_rules(&b.id).await.unwrap().is_empty()); - } - - #[tokio::test] - async fn delete_repo_removes_branch_rules() { - let dir = tempfile::tempdir().unwrap(); - let (store, tahinli) = store_with_user(&dir).await; - let gone = store - .create_repo(&tahinli.id, "gone", "", Visibility::Public, "main") - .await - .unwrap(); - let keep = store - .create_repo(&tahinli.id, "keep", "", Visibility::Public, "main") - .await - .unwrap(); - store - .upsert_branch_rule(&gone.id, "main", RuleFlags::basic(false, false)) - .await - .unwrap(); - store - .upsert_branch_rule(&keep.id, "main", RuleFlags::basic(false, false)) - .await - .unwrap(); - - store.delete_repo(&gone.id).await.unwrap(); - - let conn = store.inner.conn.lock().await; - let mut rows = conn - .query( - "SELECT COUNT(*) FROM branch_protections WHERE repo_id = ?1", - (gone.id.clone(),), - ) - .await - .unwrap(); - let row = rows.next().await.unwrap().unwrap(); - assert_eq!(col_int(&row, 0).unwrap(), 0); - drop(rows); - drop(conn); - assert_eq!(store.list_branch_rules(&keep.id).await.unwrap().len(), 1); - } } // collaborators (settings page) @@ -2598,8 +2559,10 @@ mod security_tests { } #[tokio::test] - async fn set_email_and_password_hash_persist() { + async fn account_email_password_and_session_scenarios() { let (store, user, _dir) = store_with_user().await; + + // Scenario: email and password hash persist; a bad email and a missing user are refused. store .set_email(&user.id, "tahinli@example.com") .await @@ -2613,11 +2576,8 @@ mod security_tests { store.set_email("missing", "a@b.c").await, Err(Error::NotFound) )); - } - #[tokio::test] - async fn delete_sessions_except_keeps_the_named_one() { - let (store, user, _dir) = store_with_user().await; + // Scenario: deleting sessions except one keeps only the named session. let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600)); let keep = store .create_session(&user.id, "h1", "c1", &expiry, None) @@ -2644,8 +2604,15 @@ mod security_tests { } #[tokio::test] - async fn totp_enrollment_then_replay_and_recovery_rules() { + async fn totp_scenarios() { let (store, user, _dir) = store_with_user().await; + + // Scenario: enabling without a secret is refused and leaves TOTP off. + let err = store.enable_totp(&user.id, 1, &[]).await; + assert!(matches!(err, Err(Error::NotFound))); + assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled); + + // Scenario: enrollment, then replay and recovery-code rules. let fresh = store.totp_state(&user.id).await.unwrap().unwrap(); assert_eq!(fresh.sealed_secret, None); assert!(!fresh.enabled); @@ -2699,40 +2666,36 @@ mod security_tests { assert!(!off.enabled); assert_eq!(off.last_step, 0); assert_eq!(store.unused_recovery_codes(&user.id).await.unwrap(), 0); - } - #[tokio::test] - async fn enable_without_a_secret_is_refused() { - let (store, user, _dir) = store_with_user().await; - let err = store.enable_totp(&user.id, 1, &[]).await; - assert!(matches!(err, Err(Error::NotFound))); - assert!(!store.totp_state(&user.id).await.unwrap().unwrap().enabled); - } - - #[tokio::test] - async fn totp_device_tracks_added_last_used_and_name() { - let (store, user, _dir) = store_with_user().await; - assert_eq!(store.password_changed_at(&user.id).await.unwrap(), None); - store.set_totp_secret(&user.id, "v1:sealed").await.unwrap(); - let pending = store.totp_state(&user.id).await.unwrap().unwrap(); + // Scenario: device fields (added, last used, name) on a second user. + let device = store + .create_user("device-owner", None, "h", false) + .await + .unwrap(); + assert_eq!(store.password_changed_at(&device.id).await.unwrap(), None); + store + .set_totp_secret(&device.id, "v1:sealed") + .await + .unwrap(); + let pending = store.totp_state(&device.id).await.unwrap().unwrap(); assert_eq!((pending.created_at, pending.last_used_at), (None, None)); store - .enable_totp(&user.id, 100, &[recovery_hash("aaaa-bbbb")]) + .enable_totp(&device.id, 100, &[recovery_hash("aaaa-bbbb")]) .await .unwrap(); - let on = store.totp_state(&user.id).await.unwrap().unwrap(); + let on = store.totp_state(&device.id).await.unwrap().unwrap(); let added = on.created_at.clone().expect("created_at set on enable"); assert_eq!(on.last_used_at.as_deref(), Some(added.as_str())); assert_eq!(on.name, None); store - .set_totp_name(&user.id, Some("Work phone")) + .set_totp_name(&device.id, Some("Work phone")) .await .unwrap(); assert_eq!( store - .totp_state(&user.id) + .totp_state(&device.id) .await .unwrap() .unwrap() @@ -2743,17 +2706,17 @@ mod security_tests { // Stamps have nanosecond precision and sort as text, so a later use compares greater. std::thread::sleep(std::time::Duration::from_millis(5)); - assert!(store.accept_totp_step(&user.id, 101).await.unwrap()); - let used = store.totp_state(&user.id).await.unwrap().unwrap(); + assert!(store.accept_totp_step(&device.id, 101).await.unwrap()); + let used = store.totp_state(&device.id).await.unwrap().unwrap(); assert!(used.last_used_at.as_deref().unwrap() > added.as_str()); assert_eq!(used.created_at.as_deref(), Some(added.as_str())); // A replayed step is refused and leaves the last use alone. std::thread::sleep(std::time::Duration::from_millis(5)); - assert!(!store.accept_totp_step(&user.id, 101).await.unwrap()); + assert!(!store.accept_totp_step(&device.id, 101).await.unwrap()); assert_eq!( store - .totp_state(&user.id) + .totp_state(&device.id) .await .unwrap() .unwrap() @@ -2761,21 +2724,30 @@ mod security_tests { used.last_used_at ); - store.set_totp_name(&user.id, None).await.unwrap(); + store.set_totp_name(&device.id, None).await.unwrap(); assert_eq!( - store.totp_state(&user.id).await.unwrap().unwrap().name, + store.totp_state(&device.id).await.unwrap().unwrap().name, None ); - store.disable_totp(&user.id).await.unwrap(); - let off = store.totp_state(&user.id).await.unwrap().unwrap(); + store.disable_totp(&device.id).await.unwrap(); + let off = store.totp_state(&device.id).await.unwrap().unwrap(); assert_eq!( (off.name, off.created_at, off.last_used_at), (None, None, None) ); - store.set_password_hash(&user.id, "new-hash").await.unwrap(); - assert!(store.password_changed_at(&user.id).await.unwrap().is_some()); + store + .set_password_hash(&device.id, "new-hash") + .await + .unwrap(); + assert!( + store + .password_changed_at(&device.id) + .await + .unwrap() + .is_some() + ); } fn recovery_hash(code: &str) -> String { diff --git a/crates/forge-core/src/store/snapshot.rs b/crates/forge-core/src/store/snapshot.rs index 75de4ac..de610ed 100644 --- a/crates/forge-core/src/store/snapshot.rs +++ b/crates/forge-core/src/store/snapshot.rs @@ -193,7 +193,7 @@ mod tests { use super::*; #[tokio::test] - async fn vacuum_into_snapshot_opens_read_only_with_its_data() { + async fn snapshot_verifies_good_copies_and_refuses_bad_ones() { let dir = tempfile::tempdir().expect("tempdir"); let store = Store::open(&dir.path().join("forge.db")) .await @@ -213,6 +213,7 @@ mod tests { .await .expect("repo"); + // Scenario: a snapshot holds all its data in the main file and opens read only. let snap = dir.path().join("snap").join("forge.db"); std::fs::create_dir_all(snap.parent().expect("parent")).expect("mkdir"); store.snapshot_to(&snap).await.expect("snapshot"); @@ -242,6 +243,22 @@ mod tests { info.repos, vec![(repo.id.clone(), "Tahinli".to_string(), "demo".to_string())] ); + + // Scenario: a garbage file and a truncated copy both fail verification. + let garbage = dir.path().join("garbage.db"); + std::fs::write(&garbage, b"not a database at all, just text padding").expect("write"); + assert!( + verify_snapshot(&garbage).await.is_err(), + "garbage must not verify" + ); + + let bytes = std::fs::read(&snap).expect("read"); + let cut = dir.path().join("cut.db"); + std::fs::write(&cut, &bytes[..bytes.len() / 2]).expect("write"); + assert!( + verify_snapshot(&cut).await.is_err(), + "a truncated copy must not verify" + ); } #[tokio::test] @@ -255,27 +272,4 @@ mod tests { let info = verify_snapshot(&snap).await.expect("verify"); assert!(info.repos.is_empty()); } - - #[tokio::test] - async fn truncated_or_garbage_snapshot_fails_verification() { - let dir = tempfile::tempdir().expect("tempdir"); - let store = Store::open(&dir.path().join("forge.db")) - .await - .expect("open"); - store - .create_user("Bob", None, "hash", false) - .await - .expect("user"); - let snap = dir.path().join("snap.db"); - store.snapshot_to(&snap).await.expect("snapshot"); - - let garbage = dir.path().join("garbage.db"); - std::fs::write(&garbage, b"not a database at all, just text padding").expect("write"); - assert!(verify_snapshot(&garbage).await.is_err()); - - let bytes = std::fs::read(&snap).expect("read"); - let cut = dir.path().join("cut.db"); - std::fs::write(&cut, &bytes[..bytes.len() / 2]).expect("write"); - assert!(verify_snapshot(&cut).await.is_err()); - } } diff --git a/crates/forge-core/src/store/suspension.rs b/crates/forge-core/src/store/suspension.rs index be91ec5..f5a052b 100644 --- a/crates/forge-core/src/store/suspension.rs +++ b/crates/forge-core/src/store/suspension.rs @@ -208,8 +208,10 @@ mod tests { } #[tokio::test] - async fn suspension_blocks_sessions_and_lifts() { - let (store, _admin, other, _d) = fixture().await; + async fn suspension_scenarios() { + let (store, admin, other, _d) = fixture().await; + + // Scenario: suspending ends the user's sessions until it is lifted. store .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None) .await @@ -223,26 +225,8 @@ mod tests { ); assert!(store.unsuspend_user(&other.id).await.unwrap()); assert!(store.suspension(&other.id).await.unwrap().is_none()); - } - #[tokio::test] - async fn last_admin_cannot_be_demoted_or_suspended() { - let (store, admin, other, _d) = fixture().await; - assert!(matches!( - store.set_admin(&admin.id, false).await, - Err(Error::Conflict(_)) - )); - assert!(matches!( - store.suspend_user(&admin.id, "", None).await, - Err(Error::Conflict(_)) - )); - store.set_admin(&other.id, true).await.unwrap(); - store.set_admin(&admin.id, false).await.unwrap(); - } - - #[tokio::test] - async fn suspension_stops_tokens_and_ssh_keys() { - let (store, _admin, other, _d) = fixture().await; + // Scenario: suspending also revokes API tokens and SSH keys until lifted. store .create_token(&other.id, "ci", "tokhash", &["repo".to_owned()], None) .await @@ -259,5 +243,18 @@ mod tests { store.unsuspend_user(&other.id).await.unwrap(); assert!(store.token_by_hash("tokhash").await.unwrap().is_some()); assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some()); + + // Scenario: the last admin cannot be demoted or suspended. + // Runs last because it promotes `other` to admin. + assert!(matches!( + store.set_admin(&admin.id, false).await, + Err(Error::Conflict(_)) + )); + assert!(matches!( + store.suspend_user(&admin.id, "", None).await, + Err(Error::Conflict(_)) + )); + store.set_admin(&other.id, true).await.unwrap(); + store.set_admin(&admin.id, false).await.unwrap(); } } diff --git a/crates/forge-core/src/store/transfers.rs b/crates/forge-core/src/store/transfers.rs index 04f50fe..91639f8 100644 --- a/crates/forge-core/src/store/transfers.rs +++ b/crates/forge-core/src/store/transfers.rs @@ -275,217 +275,163 @@ mod tests { } } - async fn owner_of(fx: &Fixture) -> String { + async fn owner_of(store: &Store, repo_id: &str) -> String { + store.repo_by_id(repo_id).await.unwrap().unwrap().owner_id + } + + /// A fresh repo owned by tahinli, so each scenario has its own transfer state. + async fn new_repo(fx: &Fixture, name: &str) -> String { fx.store - .repo_by_id(&fx.repo.id) + .create_repo(&fx.tahinli.id, name, "", Visibility::Private, "main") .await .unwrap() - .unwrap() - .owner_id + .id } #[tokio::test] - async fn repo_stays_until_the_target_accepts() { + async fn transfer_scenarios() { let fx = fixture().await; + + // Scenario: an org target is visible to its owners only and accepted by them. + let repo = new_repo(&fx, "for-acme").await; + let org = fx.store.create_org("acme", &fx.carol.id).await.unwrap(); + assert_eq!(org.kind, AccountKind::Org); fx.store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .add_org_member(&org.id, &fx.bob.id, OrgMemberRole::Member) .await .unwrap(); - let pending = fx - .store - .pending_transfer(&fx.repo.id) + fx.store + .initiate_transfer(&repo, &org.id, &fx.tahinli.id) .await - .unwrap() .unwrap(); - assert_eq!(pending.to_owner_name, "bob"); - assert_eq!(pending.initiated_by_name, "tahinli"); - assert_eq!(pending.from_owner_name, "tahinli"); - assert!(!pending.to_is_org); - assert_eq!(owner_of(&fx).await, fx.tahinli.id); - fx.store - .accept_transfer(&fx.repo.id, &fx.bob.id) + let listed = fx + .store + .pending_transfers_for_user(&fx.bob.id) .await .unwrap(); - assert_eq!(owner_of(&fx).await, fx.bob.id); assert!( - fx.store - .pending_transfer(&fx.repo.id) - .await - .unwrap() - .is_none() + listed.is_empty(), + "a plain member does not see org transfers" ); - } + let listed = fx + .store + .pending_transfers_for_user(&fx.carol.id) + .await + .unwrap(); + assert_eq!(listed.len(), 1); + assert!(listed[0].to_is_org); - #[tokio::test] - async fn only_the_target_can_accept() { - let fx = fixture().await; + assert!(matches!( + fx.store.accept_transfer(&repo, &fx.bob.id).await, + Err(Error::NotFound) + )); + fx.store.accept_transfer(&repo, &fx.carol.id).await.unwrap(); + assert_eq!(owner_of(&fx.store, &repo).await, org.id); + + // Scenario: the repo stays with its owner until the target accepts. + let repo = fx.repo.id.clone(); fx.store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await .unwrap(); - let err = fx.store.accept_transfer(&fx.repo.id, &fx.carol.id).await; - assert!(matches!(err, Err(Error::NotFound))); - let err = fx.store.accept_transfer(&fx.repo.id, &fx.tahinli.id).await; - assert!(matches!(err, Err(Error::NotFound))); - assert_eq!(owner_of(&fx).await, fx.tahinli.id); - } + let pending = fx.store.pending_transfer(&repo).await.unwrap().unwrap(); + assert_eq!(pending.to_owner_name, "bob"); + assert_eq!(pending.initiated_by_name, "tahinli"); + assert_eq!(pending.from_owner_name, "tahinli"); + assert!(!pending.to_is_org); + assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id); - #[tokio::test] - async fn decline_and_cancel_leave_the_repo_in_place() { - let fx = fixture().await; + fx.store.accept_transfer(&repo, &fx.bob.id).await.unwrap(); + assert_eq!(owner_of(&fx.store, &repo).await, fx.bob.id); + assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none()); + + // Scenario: only the target can accept; the owner and strangers get NotFound. + let repo = new_repo(&fx, "targeted").await; fx.store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await .unwrap(); + let err = fx.store.accept_transfer(&repo, &fx.carol.id).await; + assert!(matches!(err, Err(Error::NotFound))); + let err = fx.store.accept_transfer(&repo, &fx.tahinli.id).await; + assert!(matches!(err, Err(Error::NotFound))); + assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id); + + // Scenario: a declined transfer and a cancelled one both leave the repo in place. + let repo = new_repo(&fx, "declined").await; fx.store - .decline_transfer(&fx.repo.id, &fx.bob.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await .unwrap(); - assert_eq!(owner_of(&fx).await, fx.tahinli.id); - assert!( - fx.store - .pending_transfer(&fx.repo.id) - .await - .unwrap() - .is_none() - ); + fx.store.decline_transfer(&repo, &fx.bob.id).await.unwrap(); + assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id); + assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none()); fx.store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await .unwrap(); - fx.store.cancel_transfer(&fx.repo.id).await.unwrap(); - assert!( - fx.store - .pending_transfer(&fx.repo.id) - .await - .unwrap() - .is_none() - ); + fx.store.cancel_transfer(&repo).await.unwrap(); + assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none()); assert!(matches!( - fx.store.cancel_transfer(&fx.repo.id).await, + fx.store.cancel_transfer(&repo).await, Err(Error::NotFound) )); - assert_eq!(owner_of(&fx).await, fx.tahinli.id); - } + assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id); - #[tokio::test] - async fn second_open_transfer_conflicts() { - let fx = fixture().await; + // Scenario: a second open transfer on the same repo conflicts. + let repo = new_repo(&fx, "contested").await; fx.store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await .unwrap(); let again = fx .store - .initiate_transfer(&fx.repo.id, &fx.carol.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.carol.id, &fx.tahinli.id) .await; assert!(matches!(again, Err(Error::Conflict(_)))); - } - #[tokio::test] - async fn expired_transfer_cannot_be_accepted_and_is_replaced() { - let fx = fixture().await; + // Scenario: an expired transfer cannot be accepted and is replaced by a new one. + let repo = new_repo(&fx, "expiring").await; fx.store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await .unwrap(); { let conn = fx.store.inner.conn.lock().await; conn.execute( - "UPDATE repo_transfers SET expires_at = '2000-01-01T00:00:00.000000000Z'", - (), + "UPDATE repo_transfers SET expires_at = '2000-01-01T00:00:00.000000000Z' WHERE repo_id = ?1", + (repo.clone(),), ) .await .unwrap(); } - assert!( - fx.store - .pending_transfer(&fx.repo.id) - .await - .unwrap() - .is_none() - ); + assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none()); assert!(matches!( - fx.store.accept_transfer(&fx.repo.id, &fx.bob.id).await, + fx.store.accept_transfer(&repo, &fx.bob.id).await, Err(Error::NotFound) )); - assert_eq!(owner_of(&fx).await, fx.tahinli.id); + assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id); fx.store - .initiate_transfer(&fx.repo.id, &fx.carol.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.carol.id, &fx.tahinli.id) .await .unwrap(); - let pending = fx - .store - .pending_transfer(&fx.repo.id) - .await - .unwrap() - .unwrap(); + let pending = fx.store.pending_transfer(&repo).await.unwrap().unwrap(); assert_eq!(pending.to_owner_name, "carol"); - } - #[tokio::test] - async fn name_clash_at_the_target_is_refused_up_front() { - let fx = fixture().await; + // Scenario: a target that already has a repo of the same name is refused up front. + let repo = new_repo(&fx, "clash").await; fx.store - .create_repo(&fx.bob.id, "proj", "", Visibility::Private, "main") + .create_repo(&fx.bob.id, "clash", "", Visibility::Private, "main") .await .unwrap(); let err = fx .store - .initiate_transfer(&fx.repo.id, &fx.bob.id, &fx.tahinli.id) + .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id) .await; assert!(matches!(err, Err(Error::Conflict(_)))); - assert!( - fx.store - .pending_transfer(&fx.repo.id) - .await - .unwrap() - .is_none() - ); - } - - #[tokio::test] - async fn org_target_is_accepted_by_its_owners_only() { - let fx = fixture().await; - let org = fx.store.create_org("acme", &fx.carol.id).await.unwrap(); - assert_eq!(org.kind, AccountKind::Org); - fx.store - .add_org_member(&org.id, &fx.bob.id, OrgMemberRole::Member) - .await - .unwrap(); - fx.store - .initiate_transfer(&fx.repo.id, &org.id, &fx.tahinli.id) - .await - .unwrap(); - - let listed = fx - .store - .pending_transfers_for_user(&fx.bob.id) - .await - .unwrap(); - assert!( - listed.is_empty(), - "a plain member does not see org transfers" - ); - let listed = fx - .store - .pending_transfers_for_user(&fx.carol.id) - .await - .unwrap(); - assert_eq!(listed.len(), 1); - assert!(listed[0].to_is_org); - - assert!(matches!( - fx.store.accept_transfer(&fx.repo.id, &fx.bob.id).await, - Err(Error::NotFound) - )); - fx.store - .accept_transfer(&fx.repo.id, &fx.carol.id) - .await - .unwrap(); - assert_eq!(owner_of(&fx).await, org.id); + assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none()); } } diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index 592579a..6d8452e 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -429,8 +429,10 @@ mod tests { } #[tokio::test] - async fn ghost_is_created_once_and_cannot_log_in() { + async fn ghost_account_and_refused_deletions() { let fx = fixture().await; + + // Scenario: the ghost is created once and cannot log in. let again = fx.store.ensure_ghost_user().await.unwrap(); assert_eq!(again.id, fx.ghost.id); assert_eq!(fx.ghost.username, "ghost"); @@ -442,11 +444,33 @@ mod tests { "!", &fx.ghost.password_hash )); + + // Scenario: the ghost itself cannot be deleted. + assert!(matches!( + fx.store.delete_user(&fx.ghost.id, &fx.ghost.id).await, + Err(Error::Forbidden(_)) + )); + + // Scenario: a user who owns a repo is refused and nothing changes. + let err = fx.store.delete_user(&fx.bob.id, &fx.ghost.id).await; + assert!( + matches!(err, Err(Error::Conflict(ref m)) if m == "transfer or delete their repositories first"), + "{err:?}" + ); + assert!(fx.store.user_by_id(&fx.bob.id).await.unwrap().is_some()); + assert!(fx.store.repo_by_id(&fx.repo_id).await.unwrap().is_some()); + + // Scenario: the last administrator is refused (before a second admin exists). + let err = fx.store.delete_user(&fx.admin.id, &fx.ghost.id).await; + assert!(matches!(err, Err(Error::Conflict(_))), "{err:?}"); + assert!(fx.store.user_by_id(&fx.admin.id).await.unwrap().is_some()); } #[tokio::test] - async fn authored_content_moves_to_ghost_and_stays_readable() { + async fn authored_content_moves_to_ghost_and_preview_changes_nothing() { let fx = fixture().await; + + // Scenario: authored content moves to the ghost and stays readable. let issue = fx .store .create_issue(&fx.repo_id, &fx.tahinli.id, "Bug", "body") @@ -518,18 +542,39 @@ mod tests { 0 ); assert!(fx.store.user_by_id(&fx.tahinli.id).await.unwrap().is_none()); - } - #[tokio::test] - async fn owning_a_repo_refuses_and_changes_nothing() { - let fx = fixture().await; - let err = fx.store.delete_user(&fx.bob.id, &fx.ghost.id).await; + // Scenario: a deletion preview reports counts and changes nothing. + let second_admin = fx + .store + .create_user("Carol", None, "hash", true) + .await + .unwrap(); + fx.store + .create_issue(&fx.repo_id, &second_admin.id, "t", "b") + .await + .unwrap(); + let preview = fx + .store + .deletion_preview(&second_admin.id, Some(&fx.ghost.id)) + .await + .unwrap(); + assert_eq!(reassigned(&preview, "issues"), Some(1)); assert!( - matches!(err, Err(Error::Conflict(ref m)) if m == "transfer or delete their repositories first"), - "{err:?}" + fx.store + .user_by_id(&second_admin.id) + .await + .unwrap() + .is_some() + ); + assert_eq!( + scalar( + &fx.store, + "SELECT COUNT(*) FROM issues WHERE author_id = ?1", + &second_admin.id + ) + .await, + 1 ); - assert!(fx.store.user_by_id(&fx.bob.id).await.unwrap().is_some()); - assert!(fx.store.repo_by_id(&fx.repo_id).await.unwrap().is_some()); } #[tokio::test] @@ -581,54 +626,6 @@ mod tests { ); } - #[tokio::test] - async fn last_administrator_is_refused() { - let fx = fixture().await; - let err = fx.store.delete_user(&fx.admin.id, &fx.ghost.id).await; - assert!(matches!(err, Err(Error::Conflict(_))), "{err:?}"); - assert!(fx.store.user_by_id(&fx.admin.id).await.unwrap().is_some()); - } - - #[tokio::test] - async fn ghost_cannot_be_deleted_and_preview_changes_nothing() { - let fx = fixture().await; - assert!(matches!( - fx.store.delete_user(&fx.ghost.id, &fx.ghost.id).await, - Err(Error::Forbidden(_)) - )); - let second_admin = fx - .store - .create_user("Carol", None, "hash", true) - .await - .unwrap(); - fx.store - .create_issue(&fx.repo_id, &second_admin.id, "t", "b") - .await - .unwrap(); - let preview = fx - .store - .deletion_preview(&second_admin.id, Some(&fx.ghost.id)) - .await - .unwrap(); - assert_eq!(reassigned(&preview, "issues"), Some(1)); - assert!( - fx.store - .user_by_id(&second_admin.id) - .await - .unwrap() - .is_some() - ); - assert_eq!( - scalar( - &fx.store, - "SELECT COUNT(*) FROM issues WHERE author_id = ?1", - &second_admin.id - ) - .await, - 1 - ); - } - #[tokio::test] async fn discussions_and_comments_move_to_ghost() { let fx = fixture().await;