From bcd5f3125b757bd7065d8bb696dc2a950eabbaa2 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:49:11 -0600 Subject: [PATCH 01/12] fix(node): pin mirror syncs to their recorded origin --- crates/twigpine-node/src/api/peers.rs | 138 ++++++++++++++- crates/twigpine-node/src/db/mod.rs | 187 ++++++++++++++++++++- crates/twigpine-node/src/sync.rs | 233 +++++++++++++++++++++++++- 3 files changed, 552 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index f89a755ad..0a9cb708f 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -522,8 +522,29 @@ pub async fn notify_sync( // separator or a traversal segment places the mirror outside repos_dir. Reject // it here, before the queue row and the ref-update row are written. The message // names the field and nothing about where repos live on disk. - if let Err(e) = crate::git::repo_store::validate_repo_slug(&req.repo) { - return Err(AppError::BadRequest(format!("invalid repo field: {e}"))); + let (owner_short, repo_name) = match crate::git::repo_store::validate_repo_slug(&req.repo) { + Ok(parts) => parts, + Err(e) => return Err(AppError::BadRequest(format!("invalid repo field: {e}"))), + }; + + // The worker remains authoritative because gossip and manual trigger write + // the same queue. This early answer keeps an unauthorized notifier from + // enqueueing work or seeding the feed when durable row state already proves + // the outcome. First-sync ambiguity is left to the worker. + match crate::sync::sync_origin_row_verdict( + &state.db, + owner_short, + repo_name, + &req.repo, + &req.node_did, + ) + .await? + { + crate::sync::SyncOriginRowVerdict::Denied(reason) => { + return Err(AppError::Forbidden(reason.into())); + } + crate::sync::SyncOriginRowVerdict::FirstSync + | crate::sync::SyncOriginRowVerdict::PinnedOrigin => {} } state @@ -1339,6 +1360,119 @@ mod tests { ); } + #[sqlx::test] + async fn sync_notify_rejects_a_peer_that_is_not_the_recorded_origin(pool: PgPool) { + // Issue #432: HTTP must not enqueue or feed-record a row the worker is + // certain to reject. The wrong peer learns 403; the recorded origin's + // positive control below proves this is not a deny-everything gate. + let state = test_state(pool.clone()).await; + let attacker_did = seed_peer(&state).await; + let origin_did = "did:key:z6MkRecordedOrigin"; + state + .db + .upsert_mirror_repo_with_origin( + "z6Mkfoo", + "hello", + "/mirror/hello.git", + None, + false, + Some(origin_did), + ) + .await + .unwrap(); + let router = crate::server::build_router(state); + let resp = router + .oneshot(unsigned_post( + "/api/v1/sync/notify", + ¬ify_body("z6Mkfoo/hello", &attacker_did), + "198.51.100.23:5000", + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::FORBIDDEN); + let queued: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sync_queue") + .fetch_one(&pool) + .await + .unwrap(); + let feed: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM received_ref_updates") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(queued, 0, "unauthorized notify must not enqueue sync work"); + assert_eq!(feed, 0, "unauthorized notify must not seed the feed"); + } + + #[sqlx::test] + async fn sync_notify_accepts_the_recorded_origin(pool: PgPool) { + let state = test_state(pool.clone()).await; + let origin_did = seed_peer(&state).await; + state + .db + .upsert_mirror_repo_with_origin( + "z6Mkfoo", + "hello", + "/mirror/hello.git", + None, + false, + Some(&origin_did), + ) + .await + .unwrap(); + let router = crate::server::build_router(state); + let resp = router + .oneshot(unsigned_post( + "/api/v1/sync/notify", + ¬ify_body("z6Mkfoo/hello", &origin_did), + "198.51.100.24:5000", + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let queued: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sync_queue") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(queued, 1, "the recorded origin must still enqueue"); + } + + #[sqlx::test] + async fn sync_notify_rejects_peer_sync_into_a_canonical_repo(pool: PgPool) { + // A canonical row is this node's authoritative copy. A peer mirror + // notification must not queue a force-fetch into the shared disk path. + let state = test_state(pool.clone()).await; + let peer_did = seed_peer(&state).await; + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1, $2, $3, $4, TRUE, 'main', $5, $5, $6)", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind("hello") + .bind("did:key:z6Mkfoo") + .bind("canonical") + .bind(&now) + .bind("/canonical/hello.git") + .execute(&pool) + .await + .unwrap(); + let router = crate::server::build_router(state); + let resp = router + .oneshot(unsigned_post( + "/api/v1/sync/notify", + ¬ify_body("z6Mkfoo/hello", &peer_did), + "198.51.100.25:5000", + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::FORBIDDEN); + let queued: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sync_queue") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(queued, 0, "canonical repo sync must not enqueue"); + } + #[sqlx::test] async fn sync_notify_preserves_origin_timestamp_for_sync_lag(pool: PgPool) { let state = test_state(pool).await; diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 325fe65dd..56004b42b 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2878,6 +2878,32 @@ const MIGRATIONS: &[Migration] = &[ "ALTER TABLE model_blocks ADD COLUMN IF NOT EXISTS payer_did TEXT", ], }, + Migration { + // v53 is the next contiguous ledger version. If the in-flight + // ref-update ingest work lands first, this entry must be renumbered + // before merge rather than leaving a gap or editing applied history. + version: 53, + name: "sync_mirror_origin_pin", + stmts: &[ + "ALTER TABLE repos ADD COLUMN IF NOT EXISTS origin_node_did TEXT", + // Existing mirrors predate the column. The only local provenance + // they can have is this node's own successful sync history: the + // earliest done row for the slash-form mirror id. Rows without + // that history stay NULL, and the worker fails closed rather than + // adopting whichever peer asks next. + r#"UPDATE repos + SET origin_node_did = provenance.node_did + FROM ( + SELECT DISTINCT ON (repo) repo, node_did + FROM sync_queue + WHERE status = 'done' + ORDER BY repo, enqueued_at ASC, id ASC + ) AS provenance + WHERE repos.id = provenance.repo + AND position('/' in repos.id) > 0 + AND repos.origin_node_did IS NULL"#, + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -3362,6 +3388,26 @@ impl Db { disk_path: &str, machine_id: Option<&str>, quarantined: bool, + ) -> Result<()> { + self.upsert_mirror_repo_with_origin( + owner_short, + name, + disk_path, + machine_id, + quarantined, + None, + ) + .await + } + + pub(crate) async fn upsert_mirror_repo_with_origin( + &self, + owner_short: &str, + name: &str, + disk_path: &str, + machine_id: Option<&str>, + quarantined: bool, + origin_node_did: Option<&str>, ) -> Result<()> { // Peer-supplied names are bound like the local write paths: an // unbounded name would make reposPage emit a cursor longer than the @@ -3388,9 +3434,10 @@ impl Db { // once, and an operator's later release must not be silently reverted. sqlx::query( "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, - created_at, updated_at, disk_path, machine_id, quarantined) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) - ON CONFLICT (id) DO UPDATE SET updated_at = $8, disk_path = $9, machine_id = $10", + created_at, updated_at, disk_path, machine_id, quarantined, origin_node_did) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) + ON CONFLICT (id) DO UPDATE SET updated_at = $8, disk_path = $9, machine_id = $10, + origin_node_did = COALESCE(repos.origin_node_did, EXCLUDED.origin_node_did)", ) .bind(&id) .bind(name) @@ -3403,6 +3450,7 @@ impl Db { .bind(disk_path) .bind(machine_id) .bind(quarantined) + .bind(origin_node_did) .execute(&mut *tx) .await?; tx.commit().await?; @@ -4531,7 +4579,31 @@ pub struct SyncQueueItem { pub enqueued_at: String, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum MirrorOriginState { + NoMirror, + Unpinned, + Pinned(String), +} + impl Db { + /// Read the exact slash-form mirror row for one sync slug. Canonical rows + /// deliberately do not answer here: they are locally authoritative and are + /// checked separately before peer sync may touch the shared disk path. + pub(crate) async fn mirror_origin_state(&self, mirror_id: &str) -> Result { + let row = sqlx::query("SELECT origin_node_did FROM repos WHERE id = $1") + .bind(mirror_id) + .fetch_optional(&self.pool) + .await?; + Ok(match row { + None => MirrorOriginState::NoMirror, + Some(row) => match row.try_get::, _>("origin_node_did")? { + Some(did) => MirrorOriginState::Pinned(did), + None => MirrorOriginState::Unpinned, + }, + }) + } + pub async fn enqueue_sync( &self, repo: &str, @@ -12187,6 +12259,115 @@ mod migration_tests { assert_eq!(MIGRATIONS[0].name, MIGRATION_V1_NAME); } + #[sqlx::test] + async fn migration_v53_backfills_mirror_origin_from_earliest_done_sync(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + sqlx::query("ALTER TABLE repos DROP COLUMN origin_node_did") + .execute(db.pool()) + .await + .unwrap(); + sqlx::query("DELETE FROM schema_migrations WHERE version = 53") + .execute(db.pool()) + .await + .unwrap(); + + let now = "2026-11-26T00:00:00Z"; + for (id, owner, name, disk) in [ + ("z6Mkfoo/hello", "z6Mkfoo", "hello", "/mirror/hello.git"), + ("z6Mkfoo/orphan", "z6Mkfoo", "orphan", "/mirror/orphan.git"), + ] { + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined) + VALUES ($1, $2, $3, 'mirrored', TRUE, 'main', $4, $4, $5, NULL, FALSE)", + ) + .bind(id) + .bind(name) + .bind(owner) + .bind(now) + .bind(disk) + .execute(db.pool()) + .await + .unwrap(); + } + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined) + VALUES ($1, 'hello', 'did:key:z6Mkfoo', 'canonical', TRUE, 'main', $2, $2, '/canonical/hello.git', NULL, FALSE)", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(now) + .execute(db.pool()) + .await + .unwrap(); + for (id, did, enqueued) in [ + ("late", "did:key:zOriginLate", "2026-11-26T00:02:00Z"), + ("early", "did:key:zOriginEarly", "2026-11-26T00:01:00Z"), + ] { + sqlx::query( + "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, enqueued_at) + VALUES ($1, 'z6Mkfoo/hello', $2, 'refs/heads/main', $3, 'done', $4)", + ) + .bind(id) + .bind(did) + .bind("0".repeat(40)) + .bind(enqueued) + .execute(db.pool()) + .await + .unwrap(); + } + + db.migrate().await.unwrap(); + + let pin: Option = + sqlx::query_scalar("SELECT origin_node_did FROM repos WHERE id = 'z6Mkfoo/hello'") + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(pin.as_deref(), Some("did:key:zOriginEarly")); + let orphan_pin: Option = + sqlx::query_scalar("SELECT origin_node_did FROM repos WHERE id = 'z6Mkfoo/orphan'") + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!( + orphan_pin, None, + "a mirror without sync history stays unpinned" + ); + let canonical_nulls: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM repos WHERE position('/' in id) = 0 AND origin_node_did IS NOT NULL", + ) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!( + canonical_nulls, 0, + "canonical rows must not receive mirror pins" + ); + + db.upsert_mirror_repo_with_origin( + "z6Mkfoo", + "hello", + "/mirror/hello.git", + None, + false, + Some("did:key:zAttacker"), + ) + .await + .unwrap(); + let pin_after: Option = + sqlx::query_scalar("SELECT origin_node_did FROM repos WHERE id = 'z6Mkfoo/hello'") + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!( + pin_after.as_deref(), + Some("did:key:zOriginEarly"), + "an ordinary re-sync must never overwrite the recorded origin" + ); + } + /// Simulate an existing node at v9 with populated received_ref_updates, /// then apply the v11 migration and verify (a) owner_did IS NULL on /// existing rows, (b) the column exists and is nullable TEXT, and diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index b155083e4..8fd5446f5 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -579,6 +579,43 @@ impl NetworkGit { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum SyncOriginRowVerdict { + FirstSync, + PinnedOrigin, + Denied(&'static str), +} + +/// Authorize one peer DID against the locally recorded repo row for a sync +/// slug. This answers only durable row state. The worker additionally treats +/// a pre-existing disk path with no row as an existing mirror without +/// provenance, because the database cannot prove which peer created it. +pub(crate) async fn sync_origin_row_verdict( + db: &Db, + owner_short: &str, + repo_name: &str, + mirror_id: &str, + node_did: &str, +) -> anyhow::Result { + if let Some(row) = db.get_repo(owner_short, repo_name).await? { + if !row.is_mirror_row() { + return Ok(SyncOriginRowVerdict::Denied( + "refusing to sync peer content into a canonical local repo", + )); + } + } + Ok(match db.mirror_origin_state(mirror_id).await? { + crate::db::MirrorOriginState::Pinned(pin) if pin != node_did => { + SyncOriginRowVerdict::Denied("sync peer does not match the mirror's recorded origin") + } + crate::db::MirrorOriginState::Pinned(_) => SyncOriginRowVerdict::PinnedOrigin, + crate::db::MirrorOriginState::Unpinned => { + SyncOriginRowVerdict::Denied("mirror has no recorded sync origin") + } + crate::db::MirrorOriginState::NoMirror => SyncOriginRowVerdict::FirstSync, + }) +} + async fn process_batch( db: &Db, config: &Config, @@ -725,6 +762,40 @@ async fn process_batch( } } + // Repo-specific origin authorization is a local provenance check, not + // proof derived from the peer's wire fields. Rows that have no + // recoverable provenance fail closed: trusting the next caller would + // reproduce the force-fetch this gate exists to stop. + let row_verdict = match sync_origin_row_verdict( + db, + owner_short, + repo_name, + &item.repo, + &item.node_did, + ) + .await + { + Ok(verdict) => verdict, + Err(e) => { + warn!(id = %item.id, repo = %item.repo, err = %e, "cannot read sync origin authorization; leaving the sync row pending"); + crate::metrics::record_sync_processed("deferred"); + continue; + } + }; + let origin_rejection = match row_verdict { + SyncOriginRowVerdict::Denied(reason) => Some(reason), + SyncOriginRowVerdict::FirstSync if local_path.exists() => { + Some("existing mirror path has no recorded sync origin") + } + SyncOriginRowVerdict::FirstSync | SyncOriginRowVerdict::PinnedOrigin => None, + }; + if let Some(reason) = origin_rejection { + warn!(id = %item.id, repo = %item.repo, node_did = %item.node_did, reason, "rejecting unauthorized sync origin"); + let _ = db.mark_sync_failed(&item.id).await; + crate::metrics::record_sync_processed("rejected"); + continue; + } + // The remote matches twigpine-node git smart HTTP route: /{owner}/{repo} // (no .git suffix, the server routes don't include it). Git is handed the // canonical form built here, never the stored peer string. A refusal @@ -807,12 +878,13 @@ async fn process_batch( }; // Register in DB so git smart HTTP can serve the mirrored repo let mirror_visible = match db - .upsert_mirror_repo( + .upsert_mirror_repo_with_origin( owner_short, repo_name, local_path.to_str().unwrap_or(""), machine_id, quarantined, + Some(&item.node_did), ) .await { @@ -1914,6 +1986,15 @@ mod tests { .count() } + fn rev_parse(repo: &Path, rev: &str) -> String { + let out = Command::new("git") + .args(["-C", repo.to_str().unwrap(), "rev-parse", rev]) + .output() + .unwrap(); + assert!(out.status.success()); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + #[tokio::test] async fn promisor_clone_marks_promisor_and_keeps_objects() { let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); @@ -2239,6 +2320,17 @@ mod tests { row.0 } + async fn sync_status_for(pool: &PgPool, repo: &str, did: &str) -> String { + let row: (String,) = + sqlx::query_as("SELECT status FROM sync_queue WHERE repo = $1 AND node_did = $2") + .bind(repo) + .bind(did) + .fetch_one(pool) + .await + .unwrap(); + row.0 + } + async fn enqueue(db: &Db, repo: &str, did: &str) { db.enqueue_sync(repo, did, "refs/heads/main", &"0".repeat(40), None, None) .await @@ -2780,6 +2872,145 @@ mod tests { ); } + #[sqlx::test] + async fn process_batch_refuses_to_repoint_an_existing_mirror(pool: PgPool) { + // Issue #432: knowing the slug and being a known peer is not authority + // to rewrite a mirror another peer created. The first successful sync + // records its origin; a different peer's row is terminally rejected, + // while the recorded origin can still update the mirror. + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + + let (victim_remote, victim_url) = rooted_remote(&["z6Mkfoo/hello"]); + let (attacker_remote, attacker_url) = rooted_remote(&["z6Mkfoo/hello"]); + let victim_did = "did:key:z6MkVictimOrigin"; + let attacker_did = "did:key:z6MkAttackerOrigin"; + seed_local_peer(&pool, victim_did, &victim_url).await; + seed_local_peer(&pool, attacker_did, &attacker_url).await; + + enqueue(&state.db, "z6Mkfoo/hello", victim_did).await; + run_batch(&state, &repos_dir).await; + let mirror = repos_dir.join("z6Mkfoo").join("hello.git"); + assert!(mirror.is_dir(), "first sync did not clone"); + let victim_tip = rev_parse(&mirror, "HEAD"); + + let attacker_origin = attacker_remote.path().join("origin"); + let attacker_bare = attacker_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + std::fs::write(attacker_origin.join("attacker.txt"), b"attacker\n").unwrap(); + g(&["add", "."], &attacker_origin); + g(&["commit", "-qm", "attacker"], &attacker_origin); + g( + &["push", "-q", attacker_bare.to_str().unwrap(), "HEAD"], + &attacker_origin, + ); + let attacker_tip = rev_parse(&attacker_bare, "HEAD"); + assert_ne!(victim_tip, attacker_tip, "fixture tips must differ"); + + enqueue(&state.db, "z6Mkfoo/hello", attacker_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!( + rev_parse(&mirror, "HEAD"), + victim_tip, + "attacker peer rewrote the existing mirror" + ); + assert_eq!( + sync_status_for(&pool, "z6Mkfoo/hello", attacker_did).await, + "failed" + ); + + // Positive control: the recorded origin remains able to update its mirror. + let victim_origin = victim_remote.path().join("origin"); + let victim_bare = victim_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + std::fs::write(victim_origin.join("victim-second.txt"), b"victim\n").unwrap(); + g(&["add", "."], &victim_origin); + g(&["commit", "-qm", "victim second"], &victim_origin); + g( + &["push", "-q", victim_bare.to_str().unwrap(), "HEAD"], + &victim_origin, + ); + let updated_victim_tip = rev_parse(&victim_bare, "HEAD"); + sqlx::query("UPDATE sync_queue SET status = 'pending' WHERE repo = $1 AND node_did = $2") + .bind("z6Mkfoo/hello") + .bind(victim_did) + .execute(&pool) + .await + .unwrap(); + run_batch(&state, &repos_dir).await; + + assert_eq!(rev_parse(&mirror, "HEAD"), updated_victim_tip); + assert_eq!( + sync_status_for(&pool, "z6Mkfoo/hello", victim_did).await, + "done" + ); + } + + #[sqlx::test] + async fn process_batch_fails_closed_for_an_unpinned_existing_mirror(pool: PgPool) { + // Upgrade edge: a mirror row with no backfillable history has no local + // fact that can authorize the next caller. Trusting that caller would + // reopen the original repointing bug. + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + let (_remote, peer_url) = rooted_remote(&["z6Mkfoo/hello"]); + let did = "did:key:z6MkUnknownOrigin"; + seed_local_peer(&pool, did, &peer_url).await; + state + .db + .upsert_mirror_repo("z6Mkfoo", "hello", "/mirror/hello.git", None, false) + .await + .unwrap(); + enqueue(&state.db, "z6Mkfoo/hello", did).await; + + run_batch(&state, &repos_dir).await; + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "failed"); + assert!( + !repos_dir.join("z6Mkfoo").join("hello.git").exists(), + "an unpinned mirror row must not authorize a fetch" + ); + } + + #[sqlx::test] + async fn process_batch_fails_closed_for_a_disk_mirror_without_a_row(pool: PgPool) { + // Crash-recovery ambiguity: the path exists but the DB has no mirror + // row, so neither the queue row nor the wire data can prove which peer + // created it. The safe answer is operator intervention, not adoption. + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + let mirror = repos_dir.join("z6Mkfoo").join("hello.git"); + std::fs::create_dir_all(&mirror).unwrap(); + let (_remote, peer_url) = rooted_remote(&["z6Mkfoo/hello"]); + let did = "did:key:z6MkUnknownOrigin"; + seed_local_peer(&pool, did, &peer_url).await; + enqueue(&state.db, "z6Mkfoo/hello", did).await; + + run_batch(&state, &repos_dir).await; + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "failed"); + assert!( + object_count(&mirror) == 0, + "an unproven disk mirror must not be populated" + ); + } + #[cfg(unix)] #[sqlx::test] async fn process_batch_leaves_the_row_pending_when_the_mirror_cannot_be_inspected( From 486077c5cf0c6cf71dd248ddc518c472fdabc9dc Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:25:42 -0600 Subject: [PATCH 02/12] refactor(node): simplify sync origin checks Keep one representation of the mirror slug through the authorization helper and decode single-column reads directly so the provenance gate stays small without changing its fail-closed behavior. --- crates/twigpine-node/src/api/peers.rs | 19 ++--------- crates/twigpine-node/src/db/mod.rs | 29 +++++------------ crates/twigpine-node/src/sync.rs | 47 ++++++--------------------- 3 files changed, 21 insertions(+), 74 deletions(-) diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index 0a9cb708f..396dc9663 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -527,18 +527,8 @@ pub async fn notify_sync( Err(e) => return Err(AppError::BadRequest(format!("invalid repo field: {e}"))), }; - // The worker remains authoritative because gossip and manual trigger write - // the same queue. This early answer keeps an unauthorized notifier from - // enqueueing work or seeding the feed when durable row state already proves - // the outcome. First-sync ambiguity is left to the worker. - match crate::sync::sync_origin_row_verdict( - &state.db, - owner_short, - repo_name, - &req.repo, - &req.node_did, - ) - .await? + match crate::sync::sync_origin_row_verdict(&state.db, owner_short, repo_name, &req.node_did) + .await? { crate::sync::SyncOriginRowVerdict::Denied(reason) => { return Err(AppError::Forbidden(reason.into())); @@ -1362,9 +1352,6 @@ mod tests { #[sqlx::test] async fn sync_notify_rejects_a_peer_that_is_not_the_recorded_origin(pool: PgPool) { - // Issue #432: HTTP must not enqueue or feed-record a row the worker is - // certain to reject. The wrong peer learns 403; the recorded origin's - // positive control below proves this is not a deny-everything gate. let state = test_state(pool.clone()).await; let attacker_did = seed_peer(&state).await; let origin_did = "did:key:z6MkRecordedOrigin"; @@ -1437,8 +1424,6 @@ mod tests { #[sqlx::test] async fn sync_notify_rejects_peer_sync_into_a_canonical_repo(pool: PgPool) { - // A canonical row is this node's authoritative copy. A peer mirror - // notification must not queue a force-fetch into the shared disk path. let state = test_state(pool.clone()).await; let peer_did = seed_peer(&state).await; let now = chrono::Utc::now().to_rfc3339(); diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 56004b42b..fcfd9ef99 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2879,18 +2879,10 @@ const MIGRATIONS: &[Migration] = &[ ], }, Migration { - // v53 is the next contiguous ledger version. If the in-flight - // ref-update ingest work lands first, this entry must be renumbered - // before merge rather than leaving a gap or editing applied history. version: 53, name: "sync_mirror_origin_pin", stmts: &[ "ALTER TABLE repos ADD COLUMN IF NOT EXISTS origin_node_did TEXT", - // Existing mirrors predate the column. The only local provenance - // they can have is this node's own successful sync history: the - // earliest done row for the slash-form mirror id. Rows without - // that history stay NULL, and the worker fails closed rather than - // adopting whichever peer asks next. r#"UPDATE repos SET origin_node_did = provenance.node_did FROM ( @@ -4587,20 +4579,17 @@ pub(crate) enum MirrorOriginState { } impl Db { - /// Read the exact slash-form mirror row for one sync slug. Canonical rows - /// deliberately do not answer here: they are locally authoritative and are - /// checked separately before peer sync may touch the shared disk path. pub(crate) async fn mirror_origin_state(&self, mirror_id: &str) -> Result { - let row = sqlx::query("SELECT origin_node_did FROM repos WHERE id = $1") - .bind(mirror_id) - .fetch_optional(&self.pool) - .await?; - Ok(match row { + let origin = sqlx::query_scalar::<_, Option>( + "SELECT origin_node_did FROM repos WHERE id = $1", + ) + .bind(mirror_id) + .fetch_optional(&self.pool) + .await?; + Ok(match origin { None => MirrorOriginState::NoMirror, - Some(row) => match row.try_get::, _>("origin_node_did")? { - Some(did) => MirrorOriginState::Pinned(did), - None => MirrorOriginState::Unpinned, - }, + Some(Some(did)) => MirrorOriginState::Pinned(did), + Some(None) => MirrorOriginState::Unpinned, }) } diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index 8fd5446f5..eae26a8eb 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -586,15 +586,10 @@ pub(crate) enum SyncOriginRowVerdict { Denied(&'static str), } -/// Authorize one peer DID against the locally recorded repo row for a sync -/// slug. This answers only durable row state. The worker additionally treats -/// a pre-existing disk path with no row as an existing mirror without -/// provenance, because the database cannot prove which peer created it. pub(crate) async fn sync_origin_row_verdict( db: &Db, owner_short: &str, repo_name: &str, - mirror_id: &str, node_did: &str, ) -> anyhow::Result { if let Some(row) = db.get_repo(owner_short, repo_name).await? { @@ -604,7 +599,8 @@ pub(crate) async fn sync_origin_row_verdict( )); } } - Ok(match db.mirror_origin_state(mirror_id).await? { + let mirror_id = format!("{owner_short}/{repo_name}"); + Ok(match db.mirror_origin_state(&mirror_id).await? { crate::db::MirrorOriginState::Pinned(pin) if pin != node_did => { SyncOriginRowVerdict::Denied("sync peer does not match the mirror's recorded origin") } @@ -762,18 +758,8 @@ async fn process_batch( } } - // Repo-specific origin authorization is a local provenance check, not - // proof derived from the peer's wire fields. Rows that have no - // recoverable provenance fail closed: trusting the next caller would - // reproduce the force-fetch this gate exists to stop. - let row_verdict = match sync_origin_row_verdict( - db, - owner_short, - repo_name, - &item.repo, - &item.node_did, - ) - .await + let row_verdict = match sync_origin_row_verdict(db, owner_short, repo_name, &item.node_did) + .await { Ok(verdict) => verdict, Err(e) => { @@ -2321,14 +2307,12 @@ mod tests { } async fn sync_status_for(pool: &PgPool, repo: &str, did: &str) -> String { - let row: (String,) = - sqlx::query_as("SELECT status FROM sync_queue WHERE repo = $1 AND node_did = $2") - .bind(repo) - .bind(did) - .fetch_one(pool) - .await - .unwrap(); - row.0 + sqlx::query_scalar("SELECT status FROM sync_queue WHERE repo = $1 AND node_did = $2") + .bind(repo) + .bind(did) + .fetch_one(pool) + .await + .unwrap() } async fn enqueue(db: &Db, repo: &str, did: &str) { @@ -2874,10 +2858,6 @@ mod tests { #[sqlx::test] async fn process_batch_refuses_to_repoint_an_existing_mirror(pool: PgPool) { - // Issue #432: knowing the slug and being a known peer is not authority - // to rewrite a mirror another peer created. The first successful sync - // records its origin; a different peer's row is terminally rejected, - // while the recorded origin can still update the mirror. let state = crate::test_support::test_state(pool.clone()).await; let home = TempDir::new().unwrap(); let repos_dir = home.path().join("repos"); @@ -2927,7 +2907,6 @@ mod tests { "failed" ); - // Positive control: the recorded origin remains able to update its mirror. let victim_origin = victim_remote.path().join("origin"); let victim_bare = victim_remote .path() @@ -2961,9 +2940,6 @@ mod tests { #[sqlx::test] async fn process_batch_fails_closed_for_an_unpinned_existing_mirror(pool: PgPool) { - // Upgrade edge: a mirror row with no backfillable history has no local - // fact that can authorize the next caller. Trusting that caller would - // reopen the original repointing bug. let state = crate::test_support::test_state(pool.clone()).await; let home = TempDir::new().unwrap(); let repos_dir = home.path().join("repos"); @@ -2989,9 +2965,6 @@ mod tests { #[sqlx::test] async fn process_batch_fails_closed_for_a_disk_mirror_without_a_row(pool: PgPool) { - // Crash-recovery ambiguity: the path exists but the DB has no mirror - // row, so neither the queue row nor the wire data can prove which peer - // created it. The safe answer is operator intervention, not adoption. let state = crate::test_support::test_state(pool.clone()).await; let home = TempDir::new().unwrap(); let repos_dir = home.path().join("repos"); From d6fe9220323f5a24bbd00328ead60a9bbfb30e71 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:26:23 -0600 Subject: [PATCH 03/12] fix(node): close sync origin review gaps --- crates/twigpine-node/src/api/peers.rs | 133 +++++++++-- crates/twigpine-node/src/db/mod.rs | 231 ++++++++++++++++++- crates/twigpine-node/src/sync.rs | 311 +++++++++++++++++++++++--- 3 files changed, 619 insertions(+), 56 deletions(-) diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index 396dc9663..f8e2613b2 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -527,20 +527,12 @@ pub async fn notify_sync( Err(e) => return Err(AppError::BadRequest(format!("invalid repo field: {e}"))), }; - match crate::sync::sync_origin_row_verdict(&state.db, owner_short, repo_name, &req.node_did) - .await? - { - crate::sync::SyncOriginRowVerdict::Denied(reason) => { - return Err(AppError::Forbidden(reason.into())); - } - crate::sync::SyncOriginRowVerdict::FirstSync - | crate::sync::SyncOriginRowVerdict::PinnedOrigin => {} - } - + let canonical_owner = crate::db::normalize_owner_key(owner_short); + let canonical_repo = format!("{canonical_owner}/{repo_name}"); state .db .enqueue_sync( - &req.repo, + &canonical_repo, &req.node_did, &req.ref_name, &req.new_sha, @@ -1335,6 +1327,14 @@ mod tests { .await .unwrap(); assert_eq!(resp.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + body, + serde_json::json!({"status":"ok","queued":true,"repo":"z6Mkfoo/hello"}) + ); let queued = db.dequeue_pending_syncs(100).await.unwrap(); assert_eq!(queued.len(), 1); assert_eq!(queued[0].repo, "z6Mkfoo/hello"); @@ -1351,7 +1351,7 @@ mod tests { } #[sqlx::test] - async fn sync_notify_rejects_a_peer_that_is_not_the_recorded_origin(pool: PgPool) { + async fn sync_notify_queues_a_wrong_origin_for_the_workers_decision(pool: PgPool) { let state = test_state(pool.clone()).await; let attacker_did = seed_peer(&state).await; let origin_did = "did:key:z6MkRecordedOrigin"; @@ -1376,7 +1376,7 @@ mod tests { )) .await .unwrap(); - assert_eq!(resp.status(), StatusCode::FORBIDDEN); + assert_eq!(resp.status(), StatusCode::OK); let queued: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sync_queue") .fetch_one(&pool) .await @@ -1385,8 +1385,8 @@ mod tests { .fetch_one(&pool) .await .unwrap(); - assert_eq!(queued, 0, "unauthorized notify must not enqueue sync work"); - assert_eq!(feed, 0, "unauthorized notify must not seed the feed"); + assert_eq!(queued, 1, "notify acceptance must not reveal mirror state"); + assert_eq!(feed, 1, "notify acceptance must not reveal mirror state"); } #[sqlx::test] @@ -1423,7 +1423,7 @@ mod tests { } #[sqlx::test] - async fn sync_notify_rejects_peer_sync_into_a_canonical_repo(pool: PgPool) { + async fn sync_notify_queues_canonical_collision_for_the_workers_decision(pool: PgPool) { let state = test_state(pool.clone()).await; let peer_did = seed_peer(&state).await; let now = chrono::Utc::now().to_rfc3339(); @@ -1450,12 +1450,109 @@ mod tests { )) .await .unwrap(); - assert_eq!(resp.status(), StatusCode::FORBIDDEN); + assert_eq!(resp.status(), StatusCode::OK); let queued: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sync_queue") .fetch_one(&pool) .await .unwrap(); - assert_eq!(queued, 0, "canonical repo sync must not enqueue"); + assert_eq!( + queued, 1, + "notify acceptance must not reveal canonical state" + ); + } + + #[sqlx::test] + async fn sync_notify_response_does_not_distinguish_mirror_state(pool: PgPool) { + let state = test_state(pool.clone()).await; + let peer_did = seed_peer(&state).await; + let router = crate::server::build_router(state.clone()); + let mut responses = Vec::new(); + for (i, ip) in [ + "198.51.100.30:5000", + "198.51.100.31:5000", + "198.51.100.32:5000", + ] + .into_iter() + .enumerate() + { + if i == 1 { + state + .db + .upsert_mirror_repo_with_origin( + "z6Mkfoo", + "states", + "/mirror/states.git", + None, + false, + Some("did:key:z6MkOtherOrigin"), + ) + .await + .unwrap(); + } else if i == 2 { + sqlx::query("DELETE FROM repos WHERE id = 'z6Mkfoo/states'") + .execute(&pool) + .await + .unwrap(); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1, 'states', 'did:key:z6Mkfoo', 'canonical', TRUE, 'main', $2, $2, '/canonical/states.git')", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(&now) + .execute(&pool) + .await + .unwrap(); + } + let resp = router + .clone() + .oneshot(unsigned_post( + "/api/v1/sync/notify", + ¬ify_body("z6Mkfoo/states", &peer_did), + ip, + )) + .await + .unwrap(); + let status = resp.status(); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + responses.push((status, body)); + } + assert_eq!(responses[0].0, StatusCode::OK); + assert_eq!(responses[0], responses[1]); + assert_eq!(responses[0], responses[2]); + } + + #[sqlx::test] + async fn sync_notify_canonicalizes_a_full_did_queue_spelling(pool: PgPool) { + let state = test_state(pool.clone()).await; + let db = state.db.clone(); + let peer_did = seed_peer(&state).await; + let router = crate::server::build_router(state); + let resp = router + .oneshot(unsigned_post( + "/api/v1/sync/notify", + ¬ify_body("did:key:z6Mkfoo/hello", &peer_did), + "198.51.100.33:5000", + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let queued = db.dequeue_pending_syncs(100).await.unwrap(); + assert_eq!(queued.len(), 1); + assert_eq!(queued[0].repo, "z6Mkfoo/hello"); + let feed: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM received_ref_updates WHERE repo = $1") + .bind("did:key:z6Mkfoo/hello") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + feed, 1, + "the feed must keep the wire spelling exactly as gossip ingest does" + ); } #[sqlx::test] diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index fcfd9ef99..5e26f3c91 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2883,13 +2883,19 @@ const MIGRATIONS: &[Migration] = &[ name: "sync_mirror_origin_pin", stmts: &[ "ALTER TABLE repos ADD COLUMN IF NOT EXISTS origin_node_did TEXT", + ], + }, + Migration { + version: 54, + name: "sync_mirror_origin_backfill", + stmts: &[ r#"UPDATE repos SET origin_node_did = provenance.node_did FROM ( SELECT DISTINCT ON (repo) repo, node_did FROM sync_queue WHERE status = 'done' - ORDER BY repo, enqueued_at ASC, id ASC + ORDER BY repo, processed_at ASC NULLS LAST, enqueued_at ASC, id ASC ) AS provenance WHERE repos.id = provenance.repo AND position('/' in repos.id) > 0 @@ -3411,6 +3417,7 @@ impl Db { "mirror repo name exceeds {MAX_REPO_NAME_LEN} bytes: refusing to register" ); } + let owner_short = normalize_owner_key(owner_short); let now = Utc::now().to_rfc3339(); let id = format!("{owner_short}/{name}"); // Slug the purge cascade keys on. Take the shared advisory lock on it inside a @@ -4580,10 +4587,11 @@ pub(crate) enum MirrorOriginState { impl Db { pub(crate) async fn mirror_origin_state(&self, mirror_id: &str) -> Result { + let mirror_id = normalize_repo_slug(mirror_id); let origin = sqlx::query_scalar::<_, Option>( "SELECT origin_node_did FROM repos WHERE id = $1", ) - .bind(mirror_id) + .bind(&mirror_id) .fetch_optional(&self.pool) .await?; Ok(match origin { @@ -4593,6 +4601,59 @@ impl Db { }) } + pub(crate) async fn canonical_repo_blocks_sync_owner( + &self, + canonical_sync_owner: &str, + repo_name: &str, + ) -> Result { + let sql = format!( + "SELECT EXISTS( + SELECT 1 FROM repos + WHERE name = $2 + AND position('/' in id) = 0 + AND (({key}) = $1 + OR replace(replace(owner_did, ':', '_'), '/', '_') = $1) + )", + key = OWNER_KEY_CASE_SQL + ); + Ok(sqlx::query_scalar(&sql) + .bind(canonical_sync_owner) + .bind(repo_name) + .fetch_one(&self.pool) + .await?) + } + + pub(crate) async fn repair_mirror_origin_from_history( + &self, + mirror_id: &str, + ) -> Result> { + let mirror_id = normalize_repo_slug(mirror_id); + Ok(sqlx::query_scalar::<_, String>( + r#"UPDATE repos r + SET origin_node_did = repair.node_did + FROM ( + SELECT DISTINCT ON (sq.repo) sq.repo, sq.node_did + FROM sync_queue sq + JOIN repos mirror ON mirror.id = sq.repo + WHERE sq.status = 'done' + AND mirror.id = $1 + AND mirror.origin_node_did IS NULL + AND EXISTS ( + SELECT 1 FROM schema_migrations sm + WHERE sm.version = 53 + AND mirror.created_at >= sm.applied_at + ) + ORDER BY sq.repo, sq.processed_at ASC NULLS LAST, sq.enqueued_at ASC, sq.id ASC + ) AS repair + WHERE r.id = repair.repo + AND r.origin_node_did IS NULL + RETURNING r.origin_node_did"#, + ) + .bind(&mirror_id) + .fetch_optional(&self.pool) + .await?) + } + pub async fn enqueue_sync( &self, repo: &str, @@ -4615,7 +4676,7 @@ impl Db { ON CONFLICT DO NOTHING", ) .bind(Uuid::new_v4().to_string()) - .bind(repo) + .bind(&slug) .bind(node_did) .bind(ref_name) .bind(new_sha) @@ -12249,14 +12310,61 @@ mod migration_tests { } #[sqlx::test] - async fn migration_v53_backfills_mirror_origin_from_earliest_done_sync(pool: sqlx::PgPool) { + async fn canonical_repo_blocks_sync_owner_matches_logical_and_filesystem_collisions( + pool: sqlx::PgPool, + ) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let now = chrono::Utc::now().to_rfc3339(); + for (owner, name) in [ + ("did:key:z6Mkfoo", "keyed"), + ("did:web:squatter.example.com", "webbed"), + ] { + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined) + VALUES ($1, $2, $3, 'canonical', TRUE, 'main', $4, $4, $5, NULL, FALSE)", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(name) + .bind(owner) + .bind(&now) + .bind(format!("/canonical/{name}.git")) + .execute(db.pool()) + .await + .unwrap(); + } + + for (sync_owner, repo_name) in [ + ("z6Mkfoo", "keyed"), + ("did_key_z6Mkfoo", "keyed"), + ("did:web:squatter.example.com", "webbed"), + ("did_web_squatter.example.com", "webbed"), + ] { + assert!( + db.canonical_repo_blocks_sync_owner(sync_owner, repo_name) + .await + .unwrap(), + "{sync_owner}/{repo_name} must be denied as a canonical collision" + ); + } + assert!( + !db.canonical_repo_blocks_sync_owner("did_web_other.example.com", "webbed") + .await + .unwrap(), + "an unrelated owner must not be denied" + ); + } + + #[sqlx::test] + async fn migration_v54_backfills_mirror_origin_from_first_completed_sync(pool: sqlx::PgPool) { let db = super::Db::for_testing(pool); db.migrate().await.unwrap(); sqlx::query("ALTER TABLE repos DROP COLUMN origin_node_did") .execute(db.pool()) .await .unwrap(); - sqlx::query("DELETE FROM schema_migrations WHERE version = 53") + sqlx::query("DELETE FROM schema_migrations WHERE version IN (53, 54)") .execute(db.pool()) .await .unwrap(); @@ -12290,18 +12398,39 @@ mod migration_tests { .execute(db.pool()) .await .unwrap(); - for (id, did, enqueued) in [ - ("late", "did:key:zOriginLate", "2026-11-26T00:02:00Z"), - ("early", "did:key:zOriginEarly", "2026-11-26T00:01:00Z"), + for (id, did, enqueued, status, processed) in [ + ( + "completion-late", + "did:key:zOriginLate", + "2026-11-26T00:01:00Z", + "done", + "2026-11-26T00:03:00Z", + ), + ( + "completion-first", + "did:key:zOriginFirst", + "2026-11-26T00:02:00Z", + "done", + "2026-11-26T00:02:00Z", + ), + ( + "pending-earlier", + "did:key:zOriginPending", + "2026-11-26T00:00:00Z", + "pending", + "2026-11-26T00:01:00Z", + ), ] { sqlx::query( - "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, enqueued_at) - VALUES ($1, 'z6Mkfoo/hello', $2, 'refs/heads/main', $3, 'done', $4)", + "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, enqueued_at, processed_at) + VALUES ($1, 'z6Mkfoo/hello', $2, 'refs/heads/main', $3, $4, $5, $6)", ) .bind(id) .bind(did) .bind("0".repeat(40)) + .bind(status) .bind(enqueued) + .bind(processed) .execute(db.pool()) .await .unwrap(); @@ -12314,7 +12443,7 @@ mod migration_tests { .fetch_one(db.pool()) .await .unwrap(); - assert_eq!(pin.as_deref(), Some("did:key:zOriginEarly")); + assert_eq!(pin.as_deref(), Some("did:key:zOriginFirst")); let orphan_pin: Option = sqlx::query_scalar("SELECT origin_node_did FROM repos WHERE id = 'z6Mkfoo/orphan'") .fetch_one(db.pool()) @@ -12352,11 +12481,89 @@ mod migration_tests { .unwrap(); assert_eq!( pin_after.as_deref(), - Some("did:key:zOriginEarly"), + Some("did:key:zOriginFirst"), "an ordinary re-sync must never overwrite the recorded origin" ); } + #[sqlx::test] + async fn mirror_origin_repair_uses_only_completed_sync_history(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + for name in ["rolling", "legacy", "pendingonly"] { + db.upsert_mirror_repo("z6Mkfoo", name, &format!("/mirror/{name}.git"), None, false) + .await + .unwrap(); + } + sqlx::query( + "UPDATE repos SET created_at = '2000-01-01T00:00:00Z' WHERE id = 'z6Mkfoo/legacy'", + ) + .execute(db.pool()) + .await + .unwrap(); + for (repo, did, status) in [ + ("z6Mkfoo/rolling", "did:key:zRollingOrigin", "done"), + ("z6Mkfoo/legacy", "did:key:zLegacyOrigin", "done"), + ("z6Mkfoo/pendingonly", "did:key:zPendingOrigin", "pending"), + ] { + db.enqueue_sync(repo, did, "refs/heads/main", &"0".repeat(40), None, None) + .await + .unwrap(); + sqlx::query("UPDATE sync_queue SET status = $1, processed_at = $2 WHERE repo = $3") + .bind(status) + .bind(chrono::Utc::now().to_rfc3339()) + .bind(repo) + .execute(db.pool()) + .await + .unwrap(); + } + + let repaired = db + .repair_mirror_origin_from_history("z6Mkfoo/rolling") + .await + .unwrap(); + assert_eq!(repaired.as_deref(), Some("did:key:zRollingOrigin")); + let pin: Option = + sqlx::query_scalar("SELECT origin_node_did FROM repos WHERE id = 'z6Mkfoo/rolling'") + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!(pin.as_deref(), Some("did:key:zRollingOrigin")); + + for (repo, reason) in [ + ( + "z6Mkfoo/legacy", + "a mirror that existed before the pin migration stays fail closed", + ), + ( + "z6Mkfoo/pendingonly", + "a pending sync is not provenance for an unpinned mirror", + ), + ] { + let repaired = db.repair_mirror_origin_from_history(repo).await.unwrap(); + assert_eq!(repaired, None, "{reason}"); + } + } + + #[sqlx::test] + async fn enqueue_sync_stores_the_canonical_owner_spelling(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + db.enqueue_sync( + "did:key:z6Mkfoo/hello", + "did:key:z6MkOrigin", + "refs/heads/main", + &"0".repeat(40), + None, + None, + ) + .await + .unwrap(); + let rows = db.dequeue_pending_syncs(10).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].repo, "z6Mkfoo/hello"); + } + /// Simulate an existing node at v9 with populated received_ref_updates, /// then apply the v11 migration and verify (a) owner_did IS NULL on /// existing rows, (b) the column exists and is nullable TEXT, and diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index eae26a8eb..8c271589b 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -588,25 +588,32 @@ pub(crate) enum SyncOriginRowVerdict { pub(crate) async fn sync_origin_row_verdict( db: &Db, - owner_short: &str, + canonical_owner_short: &str, repo_name: &str, node_did: &str, ) -> anyhow::Result { - if let Some(row) = db.get_repo(owner_short, repo_name).await? { - if !row.is_mirror_row() { - return Ok(SyncOriginRowVerdict::Denied( - "refusing to sync peer content into a canonical local repo", - )); - } + if db + .canonical_repo_blocks_sync_owner(canonical_owner_short, repo_name) + .await? + { + return Ok(SyncOriginRowVerdict::Denied( + "refusing to sync peer content into a canonical local repo", + )); } - let mirror_id = format!("{owner_short}/{repo_name}"); + let mirror_id = format!("{canonical_owner_short}/{repo_name}"); Ok(match db.mirror_origin_state(&mirror_id).await? { crate::db::MirrorOriginState::Pinned(pin) if pin != node_did => { SyncOriginRowVerdict::Denied("sync peer does not match the mirror's recorded origin") } crate::db::MirrorOriginState::Pinned(_) => SyncOriginRowVerdict::PinnedOrigin, crate::db::MirrorOriginState::Unpinned => { - SyncOriginRowVerdict::Denied("mirror has no recorded sync origin") + match db.repair_mirror_origin_from_history(&mirror_id).await? { + Some(pin) if pin == node_did => SyncOriginRowVerdict::PinnedOrigin, + Some(_) => SyncOriginRowVerdict::Denied( + "sync peer does not match the mirror's recorded origin", + ), + None => SyncOriginRowVerdict::Denied("mirror has no recorded sync origin"), + } } crate::db::MirrorOriginState::NoMirror => SyncOriginRowVerdict::FirstSync, }) @@ -672,6 +679,8 @@ async fn process_batch( continue; } }; + let owner_short = crate::db::normalize_owner_key(owner_short); + let canonical_repo_slug = format!("{owner_short}/{repo_name}"); // Local disk path matching the repo_disk_path convention: // {repos_dir}/{owner_slug}/{name}.git let local_path = config @@ -788,7 +797,7 @@ async fn process_batch( // takes the same failure path as a failed clone or fetch. It runs before // any peer HTTP request: the HTTP client dials an IP literal without the // resolver policy, so the literal check here has to come first. - let net = match git_source.prepare(&origin_url, &item.repo).await { + let net = match git_source.prepare(&origin_url, &canonical_repo_slug).await { Ok(net) => net, Err(e) => { handle_sync_item_error(db, &item, &origin_url, e).await; @@ -820,10 +829,18 @@ async fn process_batch( ); } + let staging_path = owner_dir.join(format!(".{repo_name}.sync-{}.git", item.id)); + if !exists && staging_path.exists() { + if let Err(e) = remove_staging_path(&staging_path) { + warn!(id = %item.id, repo = %item.repo, path = %staging_path.display(), err = %e, "cannot clear stale mirror staging; leaving the sync row pending"); + crate::metrics::record_sync_processed("deferred"); + continue; + } + } let result = if exists { fetch_repo(&local_path, &net, mode).await } else { - clone_repo(&net, &local_path, mode).await + clone_repo(&net, &staging_path, mode).await }; match result { @@ -836,11 +853,9 @@ async fn process_batch( // listings until an operator releases it. Re-syncs of an already // admitted repo keep their prior decision (upsert preserves it). // - // "First-time" is keyed on DB-row absence, NOT on-disk presence: a - // prior attempt could have cloned to disk but crashed before the - // upsert, leaving no DB row. Disk-keying would skip admission on the - // retry and admit it unquarantined. On a DB lookup error, default to - // running the gate (fail toward quarantine, never silently admit). + // "First-time" is keyed on DB-row absence because admission is a + // registration decision. On a DB lookup error, default to running + // the gate (fail toward quarantine, never silently admit). let is_new_in_db = db .get_repo(owner_short, repo_name) .await @@ -863,7 +878,7 @@ async fn process_batch( false }; // Register in DB so git smart HTTP can serve the mirrored repo - let mirror_visible = match db + if let Err(e) = db .upsert_mirror_repo_with_origin( owner_short, repo_name, @@ -874,12 +889,28 @@ async fn process_batch( ) .await { - Ok(_) => true, - Err(e) => { - warn!(repo = %item.repo, err = %e, "failed to register mirror repo"); - false + warn!(repo = %item.repo, err = %e, "failed to register mirror repo; leaving the sync row pending"); + if !exists { + let _ = remove_staging_path(&staging_path); } - }; + crate::metrics::record_sync_processed("deferred"); + continue; + } + if !exists { + if local_path.exists() { + warn!(repo = %item.repo, path = %local_path.display(), "mirror path appeared before staged clone installation; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + if let Err(e) = std::fs::rename(&staging_path, &local_path) { + warn!(repo = %item.repo, path = %local_path.display(), err = %e, "failed to install staged mirror clone; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + } + let mirror_visible = true; // The lag is push-to-visible: sample at registration, before // the encrypted-blob tail and mark_sync_done. A quarantined // mirror is admitted but withheld from readers, so it reports @@ -887,20 +918,23 @@ async fn process_batch( // attempt-local one: on a re-sync `quarantined` is false while // `upsert_mirror_repo` preserves an existing quarantine, and // sampling then would record visibility the readers still deny. - let withheld = db.is_repo_quarantined(&item.repo).await.unwrap_or(true); + let withheld = db + .is_repo_quarantined(&canonical_repo_slug) + .await + .unwrap_or(true); observe_sync_lag_if_outcome_visible(&local_path, &item, mirror_visible, withheld) .await; // Option B2: carry the encrypted withheld-blob envelopes too, so an // authorized reader can recover private content from this mirror if - // the origin dies. `item.repo` is the slug "{owner_short}/{name}", - // which is the id upsert_mirror_repo wrote (the local repo_id). + // the origin dies. `canonical_repo_slug` is the id + // upsert_mirror_repo wrote (the local repo_id). replicate_encrypted_blobs( client, &origin_url, owner_short, repo_name, db, - &item.repo, + &canonical_repo_slug, &config.ipfs_api, ) .await; @@ -921,6 +955,9 @@ async fn process_batch( .await; } Err(e) => { + if !exists { + let _ = remove_staging_path(&staging_path); + } // Prune vs terminal classification lives in // `handle_sync_item_error` (defer = stays pending for the // next tick; anything else = failed). @@ -1611,6 +1648,17 @@ async fn handle_sync_item_error( crate::metrics::record_sync_processed("failed"); } +fn remove_staging_path(path: &Path) -> std::io::Result<()> { + match std::fs::symlink_metadata(path) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => { + std::fs::remove_dir_all(path) + } + Ok(_) => std::fs::remove_file(path), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } +} + /// Mirror-clone a repo from a remote URL into a local bare repo. /// `Promisor` mode adds `--filter=blob:limit=10g`, which marks the repo a git /// promisor (so a pack with origin-omitted withheld blobs is accepted) while @@ -2321,6 +2369,21 @@ mod tests { .unwrap(); } + async fn enqueue_raw(pool: &PgPool, repo: &str, did: &str) { + sqlx::query( + "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, enqueued_at) + VALUES ($1, $2, $3, 'refs/heads/main', $4, 'pending', $5)", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(repo) + .bind(did) + .bind("0".repeat(40)) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(pool) + .await + .unwrap(); + } + #[test] fn sync_lag_uses_origin_timestamp_only_when_it_is_in_the_past() { let visible_at = chrono::DateTime::parse_from_rfc3339("2026-08-16T00:00:12Z") @@ -2677,6 +2740,11 @@ mod tests { .await .unwrap(); assert_eq!(disk.0, mirror.to_str().unwrap()); + assert_eq!( + dir_entries(&repos_dir.join("z6Mkfoo")), + vec!["hello.git".to_string()], + "a successful first sync must not leave staging debris" + ); } // ── canonical containment before the git call (issue #272) ─────────────── @@ -2936,6 +3004,197 @@ mod tests { sync_status_for(&pool, "z6Mkfoo/hello", victim_did).await, "done" ); + + std::fs::write(victim_origin.join("victim-third.txt"), b"victim third\n").unwrap(); + g(&["add", "."], &victim_origin); + g(&["commit", "-qm", "victim third"], &victim_origin); + g( + &["push", "-q", victim_bare.to_str().unwrap(), "HEAD"], + &victim_origin, + ); + let third_victim_tip = rev_parse(&victim_bare, "HEAD"); + enqueue_raw(&pool, "did:key:z6Mkfoo/hello", victim_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!(rev_parse(&mirror, "HEAD"), third_victim_tip); + assert_eq!( + sync_status_for(&pool, "did:key:z6Mkfoo/hello", victim_did).await, + "done" + ); + let mirror_rows: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM repos WHERE name = 'hello' AND position('/' in id) > 0", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + mirror_rows, 1, + "alternate spellings must not fork mirror rows" + ); + } + + #[cfg(unix)] + #[sqlx::test] + async fn process_batch_full_did_attacker_cannot_fork_the_mirror(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + + let (_victim_remote, victim_url) = rooted_remote(&["z6Mkfoo/hello"]); + let (attacker_remote, attacker_url) = rooted_remote(&["z6Mkfoo/hello"]); + let victim_did = "did:key:z6MkVictimOrigin"; + let attacker_did = "did:key:z6MkAttackerOrigin"; + seed_local_peer(&pool, victim_did, &victim_url).await; + seed_local_peer(&pool, attacker_did, &attacker_url).await; + + enqueue(&state.db, "z6Mkfoo/hello", victim_did).await; + run_batch(&state, &repos_dir).await; + let mirror = repos_dir.join("z6Mkfoo").join("hello.git"); + let victim_tip = rev_parse(&mirror, "HEAD"); + + let attacker_origin = attacker_remote.path().join("origin"); + let attacker_bare = attacker_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + std::fs::write(attacker_origin.join("attacker.txt"), b"attacker\n").unwrap(); + g(&["add", "."], &attacker_origin); + g(&["commit", "-qm", "attacker"], &attacker_origin); + g( + &["push", "-q", attacker_bare.to_str().unwrap(), "HEAD"], + &attacker_origin, + ); + let full_parent = attacker_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("did:key:z6Mkfoo"); + std::fs::create_dir_all(&full_parent).unwrap(); + g( + &[ + "clone", + "-q", + "--bare", + attacker_bare.to_str().unwrap(), + full_parent.join("hello").to_str().unwrap(), + ], + attacker_remote.path(), + ); + + enqueue_raw(&pool, "did:key:z6Mkfoo/hello", attacker_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!(rev_parse(&mirror, "HEAD"), victim_tip); + assert_eq!( + sync_status_for(&pool, "did:key:z6Mkfoo/hello", attacker_did).await, + "failed" + ); + assert!( + !repos_dir.join("did:key:z6Mkfoo").join("hello.git").exists(), + "the alternate spelling must not fork a parallel mirror" + ); + } + + #[sqlx::test] + async fn process_batch_denies_canonical_disk_collision_before_peer_contact(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1, 'hello', 'did:key:z6Mkfoo', 'canonical', TRUE, 'main', $2, $2, '/canonical/hello.git')", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(&now) + .execute(&pool) + .await + .unwrap(); + + let git_dir = TempDir::new().unwrap(); + let (bin, record) = fake_git(git_dir.path(), "git version 2.43.0"); + let (resolver, calls) = loopback_resolver(); + let (port, accepted) = counting_listener().await; + let did = "did:key:z6MkCollision"; + seed_local_peer(&pool, did, &format!("http://rebind.invalid:{port}")).await; + enqueue(&state.db, "did_key_z6Mkfoo/hello", did).await; + + let source = GitSource::Hardened { + resolver: resolver.clone(), + git_bin: bin, + }; + run_batch_with( + &state, + &repos_dir, + &build_sync_http_client_with(resolver), + &source, + ) + .await; + + assert_eq!(sync_status(&pool, "did_key_z6Mkfoo/hello").await, "failed"); + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "denial happened after resolver use" + ); + assert_eq!( + read_record(&record).invocations, + 0, + "denial happened after git use" + ); + assert_eq!( + accepted.load(Ordering::SeqCst), + 0, + "denial happened after peer contact" + ); + assert!(mirrors_under(&repos_dir).is_empty()); + } + + #[sqlx::test] + async fn process_batch_registration_failure_leaves_first_sync_recoverable(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + sqlx::query( + "ALTER TABLE repos ADD CONSTRAINT reject_this_test_mirror CHECK (id <> 'z6Mkfoo/hello')", + ) + .execute(&pool) + .await + .unwrap(); + + let (_remote, peer_url) = rooted_remote(&["z6Mkfoo/hello"]); + let did = "did:key:z6MkOrigin"; + seed_local_peer(&pool, did, &peer_url).await; + enqueue(&state.db, "z6Mkfoo/hello", did).await; + + run_batch(&state, &repos_dir).await; + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "pending"); + let owner_entries = dir_entries(&repos_dir.join("z6Mkfoo")); + assert!( + owner_entries.is_empty(), + "registration failure must leave neither final nor staged mirror debris: {owner_entries:?}" + ); + + sqlx::query("ALTER TABLE repos DROP CONSTRAINT reject_this_test_mirror") + .execute(&pool) + .await + .unwrap(); + run_batch(&state, &repos_dir).await; + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "done"); + assert!( + repos_dir.join("z6Mkfoo").join("hello.git").is_dir(), + "the pending first sync must recover and install on retry" + ); } #[sqlx::test] From 09683a35bd7392554c08eb25c915f0884173b49b Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:20:23 -0600 Subject: [PATCH 04/12] test(node): prove the first origin pin survives queue history loss --- crates/twigpine-node/src/sync.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index 8c271589b..348ad96f7 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -2943,6 +2943,10 @@ mod tests { let mirror = repos_dir.join("z6Mkfoo").join("hello.git"); assert!(mirror.is_dir(), "first sync did not clone"); let victim_tip = rev_parse(&mirror, "HEAD"); + sqlx::query("DELETE FROM sync_queue WHERE repo = 'z6Mkfoo/hello'") + .execute(&pool) + .await + .unwrap(); let attacker_origin = attacker_remote.path().join("origin"); let attacker_bare = attacker_remote @@ -2991,12 +2995,7 @@ mod tests { &victim_origin, ); let updated_victim_tip = rev_parse(&victim_bare, "HEAD"); - sqlx::query("UPDATE sync_queue SET status = 'pending' WHERE repo = $1 AND node_did = $2") - .bind("z6Mkfoo/hello") - .bind(victim_did) - .execute(&pool) - .await - .unwrap(); + enqueue(&state.db, "z6Mkfoo/hello", victim_did).await; run_batch(&state, &repos_dir).await; assert_eq!(rev_parse(&mirror, "HEAD"), updated_victim_tip); From 51e909b2e24d60a0142395604c1b950963accb43 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:42:02 -0600 Subject: [PATCH 05/12] test(node): name the canonical mirror full-DID assertion --- crates/twigpine-node/src/sync.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index 348ad96f7..ab17516ff 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -3015,7 +3015,11 @@ mod tests { enqueue_raw(&pool, "did:key:z6Mkfoo/hello", victim_did).await; run_batch(&state, &repos_dir).await; - assert_eq!(rev_parse(&mirror, "HEAD"), third_victim_tip); + assert_eq!( + rev_parse(&mirror, "HEAD"), + third_victim_tip, + "the full-DID spelling of the recorded origin must update the canonical mirror" + ); assert_eq!( sync_status_for(&pool, "did:key:z6Mkfoo/hello", victim_did).await, "done" From 61cf64ee24674e86a744f493a27d00ecd8f062bf Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:45:36 -0600 Subject: [PATCH 06/12] fix(node): preserve legacy mirror provenance Canonicalize migration provenance by logical owner key, recognize legacy full-DID mirror rows without letting duplicate spellings authorize a fork, and reuse their recorded disk paths. Cover victim and attacker behavior across legacy rows, repaired pins, staging recovery, and indistinguishable notify responses. --- crates/twigpine-node/src/api/peers.rs | 15 +- crates/twigpine-node/src/db/mod.rs | 176 ++++++++++-- crates/twigpine-node/src/sync.rs | 369 ++++++++++++++++++++++---- 3 files changed, 472 insertions(+), 88 deletions(-) diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index f8e2613b2..5939677dc 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -522,17 +522,14 @@ pub async fn notify_sync( // separator or a traversal segment places the mirror outside repos_dir. Reject // it here, before the queue row and the ref-update row are written. The message // names the field and nothing about where repos live on disk. - let (owner_short, repo_name) = match crate::git::repo_store::validate_repo_slug(&req.repo) { - Ok(parts) => parts, - Err(e) => return Err(AppError::BadRequest(format!("invalid repo field: {e}"))), - }; + if let Err(e) = crate::git::repo_store::validate_repo_slug(&req.repo) { + return Err(AppError::BadRequest(format!("invalid repo field: {e}"))); + } - let canonical_owner = crate::db::normalize_owner_key(owner_short); - let canonical_repo = format!("{canonical_owner}/{repo_name}"); state .db .enqueue_sync( - &canonical_repo, + &req.repo, &req.node_did, &req.ref_name, &req.new_sha, @@ -1483,7 +1480,7 @@ mod tests { "states", "/mirror/states.git", None, - false, + true, Some("did:key:z6MkOtherOrigin"), ) .await @@ -1497,7 +1494,7 @@ mod tests { sqlx::query( "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, created_at, updated_at, disk_path) - VALUES ($1, 'states', 'did:key:z6Mkfoo', 'canonical', TRUE, 'main', $2, $2, '/canonical/states.git')", + VALUES ($1, 'states', 'did:key:z6Mkfoo', 'canonical', FALSE, 'main', $2, $2, '/canonical/states.git')", ) .bind(uuid::Uuid::new_v4().to_string()) .bind(&now) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 5e26f3c91..037641b32 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -2892,13 +2892,26 @@ const MIGRATIONS: &[Migration] = &[ r#"UPDATE repos SET origin_node_did = provenance.node_did FROM ( - SELECT DISTINCT ON (repo) repo, node_did - FROM sync_queue - WHERE status = 'done' - ORDER BY repo, processed_at ASC NULLS LAST, enqueued_at ASC, id ASC + SELECT DISTINCT ON (canonical_repo) canonical_repo, node_did + FROM ( + SELECT CASE WHEN split_part(repo, '/', 1) LIKE 'did:key:%' + AND position(':' in substr(split_part(repo, '/', 1), 9)) = 0 + THEN substr(split_part(repo, '/', 1), 9) + ELSE split_part(repo, '/', 1) + END || '/' || split_part(repo, '/', 2) AS canonical_repo, + node_did, processed_at, enqueued_at, id + FROM sync_queue + WHERE status = 'done' + AND position('/' in repo) > 0 + ) AS completed + ORDER BY canonical_repo, processed_at ASC NULLS LAST, enqueued_at ASC, id ASC ) AS provenance - WHERE repos.id = provenance.repo - AND position('/' in repos.id) > 0 + WHERE position('/' in repos.id) > 0 + AND (CASE WHEN split_part(repos.id, '/', 1) LIKE 'did:key:%' + AND position(':' in substr(split_part(repos.id, '/', 1), 9)) = 0 + THEN substr(split_part(repos.id, '/', 1), 9) + ELSE split_part(repos.id, '/', 1) + END || '/' || split_part(repos.id, '/', 2)) = provenance.canonical_repo AND repos.origin_node_did IS NULL"#, ], }, @@ -3407,6 +3420,29 @@ impl Db { quarantined: bool, origin_node_did: Option<&str>, ) -> Result<()> { + let owner_short = normalize_owner_key(owner_short); + let id = format!("{owner_short}/{name}"); + self.upsert_mirror_repo_with_origin_id( + &id, + disk_path, + machine_id, + quarantined, + origin_node_did, + ) + .await + } + + pub(crate) async fn upsert_mirror_repo_with_origin_id( + &self, + mirror_id: &str, + disk_path: &str, + machine_id: Option<&str>, + quarantined: bool, + origin_node_did: Option<&str>, + ) -> Result<()> { + let Some((owner_did, name)) = mirror_id.split_once('/') else { + anyhow::bail!("mirror repo id must use owner/name form"); + }; // Peer-supplied names are bound like the local write paths: an // unbounded name would make reposPage emit a cursor longer than the // 4096-byte parse limit, dead-ending pagination for every caller past @@ -3417,15 +3453,14 @@ impl Db { "mirror repo name exceeds {MAX_REPO_NAME_LEN} bytes: refusing to register" ); } - let owner_short = normalize_owner_key(owner_short); let now = Utc::now().to_rfc3339(); - let id = format!("{owner_short}/{name}"); + let id = mirror_id; // Slug the purge cascade keys on. Take the shared advisory lock on it inside a // tx so a concurrent `delete_repo_by_id` purge of a colliding row cannot // interleave its sibling-check-then-cascade around this insert and wipe the // mirror we are ingesting. Normalize the owner the same way the cascade does so // both call sites hash the identical slug string. - let slug = format!("{}/{}", normalize_owner_key(owner_short), name); + let slug = format!("{}/{}", normalize_owner_key(owner_did), name); let mut tx = self.pool.begin().await?; lock_repo_slug(&mut tx, &slug).await?; // `quarantined` is set only on first insert (the admission decision). @@ -3438,9 +3473,9 @@ impl Db { ON CONFLICT (id) DO UPDATE SET updated_at = $8, disk_path = $9, machine_id = $10, origin_node_did = COALESCE(repos.origin_node_did, EXCLUDED.origin_node_did)", ) - .bind(&id) + .bind(id) .bind(name) - .bind(owner_short) + .bind(owner_did) .bind("mirrored from peer") .bind(true) .bind("main") @@ -4578,26 +4613,51 @@ pub struct SyncQueueItem { pub enqueued_at: String, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct MirrorOriginRow { + pub(crate) id: String, + pub(crate) disk_path: String, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum MirrorOriginState { NoMirror, - Unpinned, - Pinned(String), + Unpinned(MirrorOriginRow), + Pinned(MirrorOriginRow, String), + Ambiguous, } impl Db { pub(crate) async fn mirror_origin_state(&self, mirror_id: &str) -> Result { - let mirror_id = normalize_repo_slug(mirror_id); - let origin = sqlx::query_scalar::<_, Option>( - "SELECT origin_node_did FROM repos WHERE id = $1", + let canonical_id = normalize_repo_slug(mirror_id); + let legacy_id = canonical_id.split_once('/').and_then(|(owner, name)| { + if owner.contains(':') { + None + } else { + Some(format!("did:key:{owner}/{name}")) + } + }); + let alternate_id = legacy_id.as_deref().unwrap_or(&canonical_id); + let rows = sqlx::query( + "SELECT id, disk_path, origin_node_did FROM repos WHERE id IN ($1, $2) ORDER BY id", ) - .bind(&mirror_id) - .fetch_optional(&self.pool) + .bind(&canonical_id) + .bind(alternate_id) + .fetch_all(&self.pool) .await?; - Ok(match origin { - None => MirrorOriginState::NoMirror, - Some(Some(did)) => MirrorOriginState::Pinned(did), - Some(None) => MirrorOriginState::Unpinned, + if rows.len() > 1 { + return Ok(MirrorOriginState::Ambiguous); + } + let Some(row) = rows.first() else { + return Ok(MirrorOriginState::NoMirror); + }; + let mirror_row = MirrorOriginRow { + id: row.get("id"), + disk_path: row.get("disk_path"), + }; + Ok(match row.get::, _>("origin_node_did") { + Some(did) => MirrorOriginState::Pinned(mirror_row, did), + None => MirrorOriginState::Unpinned(mirror_row), }) } @@ -4627,7 +4687,6 @@ impl Db { &self, mirror_id: &str, ) -> Result> { - let mirror_id = normalize_repo_slug(mirror_id); Ok(sqlx::query_scalar::<_, String>( r#"UPDATE repos r SET origin_node_did = repair.node_did @@ -12373,6 +12432,12 @@ mod migration_tests { for (id, owner, name, disk) in [ ("z6Mkfoo/hello", "z6Mkfoo", "hello", "/mirror/hello.git"), ("z6Mkfoo/orphan", "z6Mkfoo", "orphan", "/mirror/orphan.git"), + ( + "did:key:z6Mkfoo/legacyfull", + "did:key:z6Mkfoo", + "legacyfull", + "/mirror/legacyfull.git", + ), ] { sqlx::query( "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, @@ -12435,6 +12500,14 @@ mod migration_tests { .await .unwrap(); } + sqlx::query( + "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, enqueued_at, processed_at) + VALUES ('legacyfull-completion', 'z6Mkfoo/legacyfull', 'did:key:zLegacyFullOrigin', 'refs/heads/main', $1, 'done', '2026-11-26T00:02:30Z', '2026-11-26T00:02:30Z')", + ) + .bind("0".repeat(40)) + .execute(db.pool()) + .await + .unwrap(); db.migrate().await.unwrap(); @@ -12453,6 +12526,17 @@ mod migration_tests { orphan_pin, None, "a mirror without sync history stays unpinned" ); + let legacy_full_pin: Option = sqlx::query_scalar( + "SELECT origin_node_did FROM repos WHERE id = 'did:key:z6Mkfoo/legacyfull'", + ) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!( + legacy_full_pin.as_deref(), + Some("did:key:zLegacyFullOrigin"), + "a legacy full-DID mirror row must backfill from its canonical queue spelling" + ); let canonical_nulls: i64 = sqlx::query_scalar( "SELECT COUNT(*) FROM repos WHERE position('/' in id) = 0 AND origin_node_did IS NOT NULL", ) @@ -12486,6 +12570,52 @@ mod migration_tests { ); } + #[sqlx::test] + async fn mirror_origin_state_groups_legacy_spellings_and_fails_closed_on_duplicates( + pool: sqlx::PgPool, + ) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined, origin_node_did) + VALUES ('did:key:z6Mkfoo/hello', 'hello', 'did:key:z6Mkfoo', 'mirrored', TRUE, 'main', + $1, $1, '/mirror/legacy.git', NULL, FALSE, 'did:key:zOrigin')", + ) + .bind(&now) + .execute(db.pool()) + .await + .unwrap(); + + let state = db.mirror_origin_state("z6Mkfoo/hello").await.unwrap(); + match state { + super::MirrorOriginState::Pinned(row, did) => { + assert_eq!(row.id, "did:key:z6Mkfoo/hello"); + assert_eq!(row.disk_path, "/mirror/legacy.git"); + assert_eq!(did, "did:key:zOrigin"); + } + other => panic!("expected the legacy full-DID row to supply the pin, got {other:?}"), + } + + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined, origin_node_did) + VALUES ('z6Mkfoo/hello', 'hello', 'z6Mkfoo', 'mirrored', TRUE, 'main', + $1, $1, '/mirror/canonical.git', NULL, FALSE, 'did:key:zOrigin')", + ) + .bind(&now) + .execute(db.pool()) + .await + .unwrap(); + let state = db.mirror_origin_state("z6Mkfoo/hello").await.unwrap(); + assert_eq!( + state, + super::MirrorOriginState::Ambiguous, + "parallel mirror spellings must fail closed even when their pins agree" + ); + } + #[sqlx::test] async fn mirror_origin_repair_uses_only_completed_sync_history(pool: sqlx::PgPool) { let db = super::Db::for_testing(pool); diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index ab17516ff..06d8e05ec 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -591,23 +591,27 @@ pub(crate) async fn sync_origin_row_verdict( canonical_owner_short: &str, repo_name: &str, node_did: &str, -) -> anyhow::Result { +) -> anyhow::Result<(SyncOriginRowVerdict, crate::db::MirrorOriginState)> { + let mirror_id = format!("{canonical_owner_short}/{repo_name}"); + let mirror_state = db.mirror_origin_state(&mirror_id).await?; if db .canonical_repo_blocks_sync_owner(canonical_owner_short, repo_name) .await? { - return Ok(SyncOriginRowVerdict::Denied( - "refusing to sync peer content into a canonical local repo", + return Ok(( + SyncOriginRowVerdict::Denied( + "refusing to sync peer content into a canonical local repo", + ), + mirror_state, )); } - let mirror_id = format!("{canonical_owner_short}/{repo_name}"); - Ok(match db.mirror_origin_state(&mirror_id).await? { - crate::db::MirrorOriginState::Pinned(pin) if pin != node_did => { + let verdict = match &mirror_state { + crate::db::MirrorOriginState::Pinned(_, pin) if pin != node_did => { SyncOriginRowVerdict::Denied("sync peer does not match the mirror's recorded origin") } - crate::db::MirrorOriginState::Pinned(_) => SyncOriginRowVerdict::PinnedOrigin, - crate::db::MirrorOriginState::Unpinned => { - match db.repair_mirror_origin_from_history(&mirror_id).await? { + crate::db::MirrorOriginState::Pinned(_, _) => SyncOriginRowVerdict::PinnedOrigin, + crate::db::MirrorOriginState::Unpinned(row) => { + match db.repair_mirror_origin_from_history(&row.id).await? { Some(pin) if pin == node_did => SyncOriginRowVerdict::PinnedOrigin, Some(_) => SyncOriginRowVerdict::Denied( "sync peer does not match the mirror's recorded origin", @@ -615,8 +619,12 @@ pub(crate) async fn sync_origin_row_verdict( None => SyncOriginRowVerdict::Denied("mirror has no recorded sync origin"), } } + crate::db::MirrorOriginState::Ambiguous => { + SyncOriginRowVerdict::Denied("mirror identity has conflicting recorded spellings") + } crate::db::MirrorOriginState::NoMirror => SyncOriginRowVerdict::FirstSync, - }) + }; + Ok((verdict, mirror_state)) } async fn process_batch( @@ -683,18 +691,62 @@ async fn process_batch( let canonical_repo_slug = format!("{owner_short}/{repo_name}"); // Local disk path matching the repo_disk_path convention: // {repos_dir}/{owner_slug}/{name}.git - let local_path = config + let canonical_local_path = config .repos_dir .join(owner_short) .join(format!("{repo_name}.git")); + let (row_verdict, mirror_state) = match sync_origin_row_verdict( + db, + owner_short, + repo_name, + &item.node_did, + ) + .await + { + Ok(authorized) => authorized, + Err(e) => { + warn!(id = %item.id, repo = %item.repo, err = %e, "cannot read sync origin authorization; leaving the sync row pending"); + crate::metrics::record_sync_processed("deferred"); + continue; + } + }; + let mirror_row = match &mirror_state { + crate::db::MirrorOriginState::Unpinned(row) => Some(row), + crate::db::MirrorOriginState::Pinned(row, _) => Some(row), + _ => None, + }; + let recorded_path = mirror_row + .map(|row| PathBuf::from(&row.disk_path)) + .filter(|path| path.symlink_metadata().is_ok()); + let local_path = recorded_path.unwrap_or_else(|| canonical_local_path.clone()); + let registration_id = mirror_row + .map(|row| row.id.clone()) + .unwrap_or_else(|| canonical_repo_slug.clone()); + let origin_rejection = match row_verdict { + SyncOriginRowVerdict::Denied(reason) => Some(reason), + SyncOriginRowVerdict::FirstSync if local_path.exists() => { + Some("existing mirror path has no recorded sync origin") + } + SyncOriginRowVerdict::FirstSync | SyncOriginRowVerdict::PinnedOrigin => None, + }; + if let Some(reason) = origin_rejection { + warn!(id = %item.id, repo = %item.repo, node_did = %item.node_did, reason, "rejecting unauthorized sync origin"); + let _ = db.mark_sync_failed(&item.id).await; + crate::metrics::record_sync_processed("rejected"); + continue; + } + // Third layer, after the slug's character rules and the component walk: // prove the resolved mirror path really sits inside repos_dir. Only this // sees a symlink standing between the root and the target, at either the // owner directory or the mirror itself (#272). The owner directory is // created first so the clone branch has a parent to canonicalize, and // the check then covers clone and fetch alike. - let owner_dir = config.repos_dir.join(owner_short); + let owner_dir = local_path + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| config.repos_dir.join(owner_short)); if let Err(e) = std::fs::create_dir_all(&owner_dir) { // Split by whether retrying could ever change the answer. A // read-only or briefly unmounted repos_dir is transient, so the row @@ -767,30 +819,6 @@ async fn process_batch( } } - let row_verdict = match sync_origin_row_verdict(db, owner_short, repo_name, &item.node_did) - .await - { - Ok(verdict) => verdict, - Err(e) => { - warn!(id = %item.id, repo = %item.repo, err = %e, "cannot read sync origin authorization; leaving the sync row pending"); - crate::metrics::record_sync_processed("deferred"); - continue; - } - }; - let origin_rejection = match row_verdict { - SyncOriginRowVerdict::Denied(reason) => Some(reason), - SyncOriginRowVerdict::FirstSync if local_path.exists() => { - Some("existing mirror path has no recorded sync origin") - } - SyncOriginRowVerdict::FirstSync | SyncOriginRowVerdict::PinnedOrigin => None, - }; - if let Some(reason) = origin_rejection { - warn!(id = %item.id, repo = %item.repo, node_did = %item.node_did, reason, "rejecting unauthorized sync origin"); - let _ = db.mark_sync_failed(&item.id).await; - crate::metrics::record_sync_processed("rejected"); - continue; - } - // The remote matches twigpine-node git smart HTTP route: /{owner}/{repo} // (no .git suffix, the server routes don't include it). Git is handed the // canonical form built here, never the stored peer string. A refusal @@ -879,9 +907,8 @@ async fn process_batch( }; // Register in DB so git smart HTTP can serve the mirrored repo if let Err(e) = db - .upsert_mirror_repo_with_origin( - owner_short, - repo_name, + .upsert_mirror_repo_with_origin_id( + ®istration_id, local_path.to_str().unwrap_or(""), machine_id, quarantined, @@ -910,7 +937,6 @@ async fn process_batch( continue; } } - let mirror_visible = true; // The lag is push-to-visible: sample at registration, before // the encrypted-blob tail and mark_sync_done. A quarantined // mirror is admitted but withheld from readers, so it reports @@ -919,22 +945,21 @@ async fn process_batch( // `upsert_mirror_repo` preserves an existing quarantine, and // sampling then would record visibility the readers still deny. let withheld = db - .is_repo_quarantined(&canonical_repo_slug) + .is_repo_quarantined(®istration_id) .await .unwrap_or(true); - observe_sync_lag_if_outcome_visible(&local_path, &item, mirror_visible, withheld) - .await; + observe_sync_lag_if_outcome_visible(&local_path, &item, withheld).await; // Option B2: carry the encrypted withheld-blob envelopes too, so an // authorized reader can recover private content from this mirror if - // the origin dies. `canonical_repo_slug` is the id - // upsert_mirror_repo wrote (the local repo_id). + // the origin dies. `registration_id` is the id the mirror + // registration wrote or updated (the local repo_id). replicate_encrypted_blobs( client, &origin_url, owner_short, repo_name, db, - &canonical_repo_slug, + ®istration_id, &config.ipfs_api, ) .await; @@ -1189,10 +1214,9 @@ async fn git_run_net(net: &NetworkGit, args: &[&str]) -> anyhow::Result<()> { async fn observe_sync_lag_if_outcome_visible( local_path: &Path, item: &crate::db::SyncQueueItem, - mirror_visible: bool, withheld: bool, ) { - if !mirror_visible || withheld { + if withheld { return; } let outcome_visible = match mirror_ref_tip(local_path, &item.ref_name).await { @@ -2472,7 +2496,6 @@ mod tests { observe_sync_lag_if_outcome_visible( Path::new("/nonexistent/gitlawb-tip-probe-xyz"), &item, - true, false, ) .await; @@ -2496,14 +2519,14 @@ mod tests { // Confirmed absent on a delete-sentinel row: samples. let gone = lag_item("refs/heads/never-pushed", &"0".repeat(40), Some(&ts)); - observe_sync_lag_if_outcome_visible(&repo, &gone, true, false).await; + observe_sync_lag_if_outcome_visible(&repo, &gone, false).await; count += 1; assert_eq!(crate::metrics::sync_lag_sample_count_for_test(), count); // The ref still resolves, so the mirror carries a different state than // the queued deletion: no sample. let still_there = lag_item("HEAD", &"0".repeat(40), Some(&ts)); - observe_sync_lag_if_outcome_visible(&repo, &still_there, true, false).await; + observe_sync_lag_if_outcome_visible(&repo, &still_there, false).await; assert_eq!(crate::metrics::sync_lag_sample_count_for_test(), count); // A non-delete row samples only when the tip equals the queued sha. @@ -2512,16 +2535,15 @@ mod tests { other => panic!("expected a resolved tip, got {other:?}"), }; let landed = lag_item("HEAD", &tip, Some(&ts)); - observe_sync_lag_if_outcome_visible(&repo, &landed, true, false).await; + observe_sync_lag_if_outcome_visible(&repo, &landed, false).await; count += 1; assert_eq!(crate::metrics::sync_lag_sample_count_for_test(), count); let wrong_sha = lag_item("HEAD", &"f".repeat(40), Some(&ts)); - observe_sync_lag_if_outcome_visible(&repo, &wrong_sha, true, false).await; + observe_sync_lag_if_outcome_visible(&repo, &wrong_sha, false).await; assert_eq!(crate::metrics::sync_lag_sample_count_for_test(), count); - // A quarantined or unregistered mirror never samples. - observe_sync_lag_if_outcome_visible(&repo, &gone, false, false).await; - observe_sync_lag_if_outcome_visible(&repo, &gone, true, true).await; + // A quarantined mirror never samples. + observe_sync_lag_if_outcome_visible(&repo, &gone, true).await; assert_eq!(crate::metrics::sync_lag_sample_count_for_test(), count); } @@ -2740,6 +2762,16 @@ mod tests { .await .unwrap(); assert_eq!(disk.0, mirror.to_str().unwrap()); + let pin: Option = + sqlx::query_scalar("SELECT origin_node_did FROM repos WHERE id = 'z6Mkfoo/hello'") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + pin.as_deref(), + Some(did), + "first mirror registration must persist its successful origin" + ); assert_eq!( dir_entries(&repos_dir.join("z6Mkfoo")), vec!["hello.git".to_string()], @@ -3036,6 +3068,109 @@ mod tests { ); } + #[sqlx::test] + async fn process_batch_reuses_a_legacy_full_did_mirror_row_and_path(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + + let (victim_remote, victim_url) = rooted_remote(&["z6Mkfoo/hello"]); + let (attacker_remote, attacker_url) = rooted_remote(&["z6Mkfoo/hello"]); + let victim_did = "did:key:z6MkVictimOrigin"; + let attacker_did = "did:key:z6MkAttackerOrigin"; + seed_local_peer(&pool, victim_did, &victim_url).await; + seed_local_peer(&pool, attacker_did, &attacker_url).await; + + let victim_bare = victim_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + let legacy_mirror = repos_dir.join("did:key:z6Mkfoo").join("hello.git"); + std::fs::create_dir_all(legacy_mirror.parent().unwrap()).unwrap(); + g( + &[ + "clone", + "-q", + "--mirror", + victim_bare.to_str().unwrap(), + legacy_mirror.to_str().unwrap(), + ], + victim_remote.path(), + ); + let victim_tip = rev_parse(&legacy_mirror, "HEAD"); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined, origin_node_did) + VALUES ('did:key:z6Mkfoo/hello', 'hello', 'did:key:z6Mkfoo', 'mirrored', TRUE, 'main', + $1, $1, $2, NULL, FALSE, $3)", + ) + .bind(&now) + .bind(legacy_mirror.to_str().unwrap()) + .bind(victim_did) + .execute(&pool) + .await + .unwrap(); + + let attacker_origin = attacker_remote.path().join("origin"); + let attacker_bare = attacker_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + std::fs::write(attacker_origin.join("attacker.txt"), b"attacker\n").unwrap(); + g(&["add", "."], &attacker_origin); + g(&["commit", "-qm", "attacker"], &attacker_origin); + g( + &["push", "-q", attacker_bare.to_str().unwrap(), "HEAD"], + &attacker_origin, + ); + enqueue(&state.db, "z6Mkfoo/hello", attacker_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!(rev_parse(&legacy_mirror, "HEAD"), victim_tip); + assert_eq!( + sync_status_for(&pool, "z6Mkfoo/hello", attacker_did).await, + "failed" + ); + + let victim_origin = victim_remote.path().join("origin"); + std::fs::write(victim_origin.join("victim-second.txt"), b"victim\n").unwrap(); + g(&["add", "."], &victim_origin); + g(&["commit", "-qm", "victim second"], &victim_origin); + g( + &["push", "-q", victim_bare.to_str().unwrap(), "HEAD"], + &victim_origin, + ); + let updated_victim_tip = rev_parse(&victim_bare, "HEAD"); + enqueue(&state.db, "z6Mkfoo/hello", victim_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!(rev_parse(&legacy_mirror, "HEAD"), updated_victim_tip); + assert_eq!( + sync_status_for(&pool, "z6Mkfoo/hello", victim_did).await, + "done" + ); + assert!( + !repos_dir.join("z6Mkfoo").join("hello.git").exists(), + "the canonical spelling must not fork a second mirror" + ); + let row: (String, String) = sqlx::query_as( + "SELECT id, disk_path FROM repos WHERE name = 'hello' AND position('/' in id) > 0", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(row.0, "did:key:z6Mkfoo/hello"); + assert_eq!(row.1, legacy_mirror.to_str().unwrap()); + } + #[cfg(unix)] #[sqlx::test] async fn process_batch_full_did_attacker_cannot_fork_the_mirror(pool: PgPool) { @@ -3200,6 +3335,128 @@ mod tests { ); } + #[sqlx::test] + async fn process_batch_replaces_crash_stale_staging_on_first_sync(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + let (_remote, peer_url) = rooted_remote(&["z6Mkfoo/hello"]); + let did = "did:key:z6MkOrigin"; + seed_local_peer(&pool, did, &peer_url).await; + enqueue(&state.db, "z6Mkfoo/hello", did).await; + let item_id: String = + sqlx::query_scalar("SELECT id FROM sync_queue WHERE repo = 'z6Mkfoo/hello'") + .fetch_one(&pool) + .await + .unwrap(); + let owner_dir = repos_dir.join("z6Mkfoo"); + std::fs::create_dir_all(&owner_dir).unwrap(); + let stale = owner_dir.join(format!(".hello.sync-{item_id}.git")); + std::fs::create_dir_all(&stale).unwrap(); + std::fs::write(stale.join("stale"), b"partial\n").unwrap(); + + run_batch(&state, &repos_dir).await; + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "done"); + assert!(repos_dir.join("z6Mkfoo").join("hello.git").is_dir()); + assert!( + !stale.exists(), + "crash-stale staging must not survive beside the installed mirror" + ); + } + + #[sqlx::test] + async fn process_batch_repairs_an_unpinned_mirror_only_for_its_completed_origin(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + + let (victim_remote, victim_url) = rooted_remote(&["z6Mkfoo/hello"]); + let (_attacker_remote, attacker_url) = rooted_remote(&["z6Mkfoo/hello"]); + let victim_did = "did:key:z6MkVictimOrigin"; + let attacker_did = "did:key:z6MkAttackerOrigin"; + seed_local_peer(&pool, victim_did, &victim_url).await; + seed_local_peer(&pool, attacker_did, &attacker_url).await; + + let victim_bare = victim_remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + let mirror = repos_dir.join("z6Mkfoo").join("hello.git"); + std::fs::create_dir_all(mirror.parent().unwrap()).unwrap(); + g( + &[ + "clone", + "-q", + "--mirror", + victim_bare.to_str().unwrap(), + mirror.to_str().unwrap(), + ], + victim_remote.path(), + ); + let victim_tip = rev_parse(&mirror, "HEAD"); + state + .db + .upsert_mirror_repo("z6Mkfoo", "hello", mirror.to_str().unwrap(), None, false) + .await + .unwrap(); + state + .db + .enqueue_sync( + "z6Mkfoo/hello", + victim_did, + "refs/heads/main", + &"0".repeat(40), + None, + None, + ) + .await + .unwrap(); + sqlx::query( + "UPDATE sync_queue SET status = 'done', processed_at = $1 WHERE repo = 'z6Mkfoo/hello'", + ) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(&pool) + .await + .unwrap(); + + enqueue(&state.db, "z6Mkfoo/hello", attacker_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!( + rev_parse(&mirror, "HEAD"), + victim_tip, + "the attacker must not fetch through a mirror repaired to the victim origin" + ); + assert_eq!( + sync_status_for(&pool, "z6Mkfoo/hello", attacker_did).await, + "failed" + ); + + let victim_origin = victim_remote.path().join("origin"); + std::fs::write(victim_origin.join("victim-second.txt"), b"victim\n").unwrap(); + g(&["add", "."], &victim_origin); + g(&["commit", "-qm", "victim second"], &victim_origin); + g( + &["push", "-q", victim_bare.to_str().unwrap(), "HEAD"], + &victim_origin, + ); + let updated_victim_tip = rev_parse(&victim_bare, "HEAD"); + enqueue(&state.db, "z6Mkfoo/hello", victim_did).await; + run_batch(&state, &repos_dir).await; + + assert_eq!(rev_parse(&mirror, "HEAD"), updated_victim_tip); + assert_eq!( + sync_status_for(&pool, "z6Mkfoo/hello", victim_did).await, + "done" + ); + } + #[sqlx::test] async fn process_batch_fails_closed_for_an_unpinned_existing_mirror(pool: PgPool) { let state = crate::test_support::test_state(pool.clone()).await; From 1606fcf959cbf2b37a9f312ba6760707b6555f0a Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:35:09 -0600 Subject: [PATCH 07/12] fix(node): close sync origin upgrade races The rolling-upgrade repair now recognizes only a first sync that was already in flight before the mirror row existed, and first mirror registration re-checks authorization under the canonical repo namespace lock before peer content can land. --- crates/twigpine-node/src/db/mod.rs | 64 +++++++- crates/twigpine-node/src/lib.rs | 1 + crates/twigpine-node/src/sync.rs | 239 ++++++++++++++++++++++++++++- 3 files changed, 294 insertions(+), 10 deletions(-) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 037641b32..358e257c0 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -4697,10 +4697,20 @@ impl Db { WHERE sq.status = 'done' AND mirror.id = $1 AND mirror.origin_node_did IS NULL - AND EXISTS ( - SELECT 1 FROM schema_migrations sm - WHERE sm.version = 53 - AND mirror.created_at >= sm.applied_at + AND ( + EXISTS ( + SELECT 1 FROM schema_migrations sm + WHERE sm.version = 53 + AND mirror.created_at >= sm.applied_at + ) + OR sq.enqueued_at <= mirror.created_at + ) + AND NOT EXISTS ( + SELECT 1 FROM sync_queue other + WHERE other.repo = sq.repo + AND other.status = 'done' + AND other.node_did <> sq.node_did + AND other.enqueued_at <= mirror.created_at ) ORDER BY sq.repo, sq.processed_at ASC NULLS LAST, sq.enqueued_at ASC, sq.id ASC ) AS repair @@ -12620,13 +12630,13 @@ mod migration_tests { async fn mirror_origin_repair_uses_only_completed_sync_history(pool: sqlx::PgPool) { let db = super::Db::for_testing(pool); db.migrate().await.unwrap(); - for name in ["rolling", "legacy", "pendingonly"] { + for name in ["rolling", "legacy", "pendingonly", "inflight", "ambiguous"] { db.upsert_mirror_repo("z6Mkfoo", name, &format!("/mirror/{name}.git"), None, false) .await .unwrap(); } sqlx::query( - "UPDATE repos SET created_at = '2000-01-01T00:00:00Z' WHERE id = 'z6Mkfoo/legacy'", + "UPDATE repos SET created_at = '2000-01-01T00:00:00Z' WHERE id IN ('z6Mkfoo/legacy', 'z6Mkfoo/inflight', 'z6Mkfoo/ambiguous')", ) .execute(db.pool()) .await @@ -12635,6 +12645,7 @@ mod migration_tests { ("z6Mkfoo/rolling", "did:key:zRollingOrigin", "done"), ("z6Mkfoo/legacy", "did:key:zLegacyOrigin", "done"), ("z6Mkfoo/pendingonly", "did:key:zPendingOrigin", "pending"), + ("z6Mkfoo/inflight", "did:key:zInFlightOrigin", "done"), ] { db.enqueue_sync(repo, did, "refs/heads/main", &"0".repeat(40), None, None) .await @@ -12647,6 +12658,31 @@ mod migration_tests { .await .unwrap(); } + sqlx::query( + "UPDATE sync_queue SET enqueued_at = '1999-12-31T23:59:59Z' WHERE repo = 'z6Mkfoo/inflight'", + ) + .execute(db.pool()) + .await + .unwrap(); + for did in ["did:key:zFirstRacingOrigin", "did:key:zSecondRacingOrigin"] { + db.enqueue_sync( + "z6Mkfoo/ambiguous", + did, + "refs/heads/main", + &"0".repeat(40), + None, + None, + ) + .await + .unwrap(); + } + sqlx::query( + "UPDATE sync_queue SET status = 'done', processed_at = $1, enqueued_at = '1999-12-31T23:59:59Z' WHERE repo = 'z6Mkfoo/ambiguous'", + ) + .bind(chrono::Utc::now().to_rfc3339()) + .execute(db.pool()) + .await + .unwrap(); let repaired = db .repair_mirror_origin_from_history("z6Mkfoo/rolling") @@ -12660,15 +12696,29 @@ mod migration_tests { .unwrap(); assert_eq!(pin.as_deref(), Some("did:key:zRollingOrigin")); + let inflight = db + .repair_mirror_origin_from_history("z6Mkfoo/inflight") + .await + .unwrap(); + assert_eq!( + inflight.as_deref(), + Some("did:key:zInFlightOrigin"), + "a first sync already in flight before the mirror row was created must be allowed to finish pinning its origin" + ); + for (repo, reason) in [ ( "z6Mkfoo/legacy", - "a mirror that existed before the pin migration stays fail closed", + "a mirror that existed before the pin migration stays fail closed when its completed sync was not already in flight", ), ( "z6Mkfoo/pendingonly", "a pending sync is not provenance for an unpinned mirror", ), + ( + "z6Mkfoo/ambiguous", + "racing first syncs from different origins never choose a winner after the fact", + ), ] { let repaired = db.repair_mirror_origin_from_history(repo).await.unwrap(); assert_eq!(repaired, None, "{reason}"); diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index a017646d1..4b1a05ea4 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -792,6 +792,7 @@ pub async fn run() -> Result<()> { Arc::clone(&state.db), Arc::clone(&state.config), Arc::clone(&state.node_keypair), + state.repo_store.clone(), state.subscribe_shutdown(), ); info!("auto-sync worker started"); diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index 06d8e05ec..b023be45c 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -144,10 +144,11 @@ pub fn start( db: Arc, config: Arc, keypair: Arc, + repo_store: crate::git::repo_store::RepoStore, mut shutdown_rx: tokio::sync::watch::Receiver, ) { tokio::spawn(async move { - run(db, config, keypair, &mut shutdown_rx).await; + run(db, config, keypair, repo_store, &mut shutdown_rx).await; }); } @@ -183,6 +184,7 @@ async fn run( db: Arc, config: Arc, keypair: Arc, + repo_store: crate::git::repo_store::RepoStore, shutdown_rx: &mut tokio::sync::watch::Receiver, ) { let machine_id = std::env::var("FLY_MACHINE_ID").ok(); @@ -200,6 +202,7 @@ async fn run( machine_id.as_deref(), &client, &git_source, + &repo_store, ) .await; } @@ -253,6 +256,9 @@ enum GitSource { /// Local-path and file:// tests only. No production code can build this. #[cfg(test)] Unhardened, + /// Same local-path test lane, with a test-controlled git binary. + #[cfg(test)] + UnhardenedWithGit(String), } impl GitSource { @@ -270,6 +276,11 @@ impl GitSource { } #[cfg(test)] GitSource::Unhardened => Ok(NetworkGit::unhardened(&format!("{origin_url}/{repo}"))), + #[cfg(test)] + GitSource::UnhardenedWithGit(git_bin) => Ok(NetworkGit::unhardened_with_git( + &format!("{origin_url}/{repo}"), + git_bin, + )), } } } @@ -542,8 +553,13 @@ impl NetworkGit { /// `file://` URLs. It does not exist outside test builds. #[cfg(test)] fn unhardened(remote: &str) -> Self { + Self::unhardened_with_git(remote, "git") + } + + #[cfg(test)] + fn unhardened_with_git(remote: &str, git_bin: &str) -> Self { Self { - git_bin: "git".to_string(), + git_bin: git_bin.to_string(), remote: remote.to_string(), config: Vec::new(), } @@ -634,6 +650,7 @@ async fn process_batch( machine_id: Option<&str>, client: &reqwest::Client, git_source: &GitSource, + repo_store: &crate::git::repo_store::RepoStore, ) { let items = match db.dequeue_pending_syncs(10).await { Ok(v) => v, @@ -723,6 +740,7 @@ async fn process_batch( let registration_id = mirror_row .map(|row| row.id.clone()) .unwrap_or_else(|| canonical_repo_slug.clone()); + let first_sync = row_verdict == SyncOriginRowVerdict::FirstSync; let origin_rejection = match row_verdict { SyncOriginRowVerdict::Denied(reason) => Some(reason), SyncOriginRowVerdict::FirstSync if local_path.exists() => { @@ -731,6 +749,10 @@ async fn process_batch( SyncOriginRowVerdict::FirstSync | SyncOriginRowVerdict::PinnedOrigin => None, }; if let Some(reason) = origin_rejection { + // Denied rows deliberately make no peer contact. The + // non-disclosure contract covers the HTTP acceptance response; + // network-indistinguishable denial would require attacker-controlled + // decoy fetches and would break the pre-contact authorization boundary. warn!(id = %item.id, repo = %item.repo, node_did = %item.node_did, reason, "rejecting unauthorized sync origin"); let _ = db.mark_sync_failed(&item.id).await; crate::metrics::record_sync_processed("rejected"); @@ -834,7 +856,11 @@ async fn process_batch( }; let withheld = fetch_withheld(client, &origin_url, owner_short, repo_name).await; - let exists = local_path.exists(); + // Freeze the first-sync decision made by authorization. A path that + // appears while the peer is being contacted must not turn this item + // into a fetch into whoever won that race; the staged-clone install + // re-authorizes under the repo namespace lock before it can land. + let exists = local_path.exists() && !first_sync; let lookup_unknown = withheld.is_none(); // Only probe the on-disk promisor state when the lookup is unknown and the // repo already exists — the sole case where it changes the resolved mode. @@ -905,6 +931,68 @@ async fn process_batch( } else { false }; + // A first sync authorized while the namespace looked empty has + // to re-prove that decision under the same advisory lock + // create_repo holds. The lock key uses the full did:key spelling + // because that is the owner spelling canonical creation locks; + // the mirror path itself keeps the normalized bare-owner form. + let _first_sync_lock = if first_sync { + let lock_owner = crate::db::canonical_did(owner_short); + match repo_store + .lock_repo_blocking(lock_owner.as_ref(), repo_name) + .await + { + Ok(Some(guard)) => Some(guard), + Ok(None) => { + warn!(repo = %item.repo, "repo namespace is busy before first mirror registration; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + Err(e) => { + warn!(repo = %item.repo, err = %e, "cannot lock repo namespace before first mirror registration; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + } + } else { + None + }; + if first_sync { + let recheck = + sync_origin_row_verdict(db, owner_short, repo_name, &item.node_did).await; + match recheck { + Ok((SyncOriginRowVerdict::FirstSync, _)) if !local_path.exists() => {} + Ok((SyncOriginRowVerdict::PinnedOrigin, _)) if !local_path.exists() => {} + Ok((SyncOriginRowVerdict::PinnedOrigin, _)) => { + warn!(repo = %item.repo, path = %local_path.display(), "mirror completed concurrently before staged clone installation; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + Ok((SyncOriginRowVerdict::FirstSync, _)) => { + warn!(repo = %item.repo, path = %local_path.display(), "unproven mirror path appeared under the namespace lock; rejecting first sync"); + let _ = remove_staging_path(&staging_path); + let _ = db.mark_sync_failed(&item.id).await; + crate::metrics::record_sync_processed("rejected"); + continue; + } + Ok((SyncOriginRowVerdict::Denied(reason), _)) => { + warn!(id = %item.id, repo = %item.repo, node_did = %item.node_did, reason, "sync origin authorization changed before registration"); + let _ = remove_staging_path(&staging_path); + let _ = db.mark_sync_failed(&item.id).await; + crate::metrics::record_sync_processed("rejected"); + continue; + } + Err(e) => { + warn!(id = %item.id, repo = %item.repo, err = %e, "cannot re-read sync origin authorization under the namespace lock; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + } + } // Register in DB so git smart HTTP can serve the mirrored repo if let Err(e) = db .upsert_mirror_repo_with_origin_id( @@ -1864,6 +1952,7 @@ mod tests { use std::process::Command; use std::sync::atomic::{AtomicUsize, Ordering}; use tempfile::TempDir; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[test] fn resolve_promisor_when_withheld_nonempty() { @@ -2610,6 +2699,7 @@ mod tests { None, client, git_source, + &state.repo_store, ) .await; } @@ -3295,6 +3385,149 @@ mod tests { assert!(mirrors_under(&repos_dir).is_empty()); } + #[cfg(unix)] + #[sqlx::test] + async fn process_batch_rechecks_first_sync_namespace_before_registration(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + let (remote, _fixture_url) = rooted_remote(&["z6Mkfoo/hello"]); + let fixture_bare = remote + .path() + .join("r1") + .join("r2") + .join("root") + .join("z6Mkfoo") + .join("hello"); + let did = "did:key:z6MkOrigin"; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + seed_local_peer(&pool, did, &format!("http://127.0.0.1:{port}")).await; + enqueue(&state.db, "z6Mkfoo/hello", did).await; + + let git_dir = TempDir::new().unwrap(); + let request_seen = git_dir.path().join("request-seen"); + let release_response = git_dir.path().join("release-response"); + let server_seen = request_seen.clone(); + let server_release = release_response.clone(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buf = [0_u8; 1024]; + let _ = socket.read(&mut buf).await.unwrap(); + std::fs::write(&server_seen, b"request").unwrap(); + for _ in 0..400 { + if server_release.exists() { + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + socket + .write_all(b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n") + .await + .unwrap(); + }); + + let bin = git_dir.path().join("git-under-test"); + let record = git_dir.path().join("record"); + write_fake_git( + &bin, + &format!( + r##"#!/bin/sh +echo "INVOKED $*" >> '{}' +if [ "$1" = "clone" ]; then +for last; do :; done +git clone --mirror -- '{}' "$last" +exit $? +fi +git "$@" +"##, + record.display(), + fixture_bare.display() + ), + ); + + let insert_pool = pool.clone(); + let mirror = repos_dir.join("z6Mkfoo").join("hello.git"); + let racer_mirror = mirror.clone(); + let racer_fixture = fixture_bare.clone(); + let racer_seen = request_seen.clone(); + let racer_release = release_response.clone(); + let racer_repos_dir = repos_dir.clone(); + let racer = tokio::spawn(async move { + for _ in 0..200 { + if racer_seen.exists() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!( + racer_seen.exists(), + "the withheld lookup did not reach the injected race window" + ); + g( + &[ + "clone", + "-q", + "--mirror", + racer_fixture.to_str().unwrap(), + racer_mirror.to_str().unwrap(), + ], + &racer_repos_dir, + ); + let now = chrono::Utc::now().to_rfc3339(); + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path) + VALUES ($1, 'hello', 'z6Mkfoo', 'canonical', TRUE, 'main', $2, $2, $3)", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(&now) + .bind(racer_mirror.to_str().unwrap()) + .execute(&insert_pool) + .await + .unwrap(); + std::fs::write(&racer_release, b"created").unwrap(); + }); + + run_batch_with( + &state, + &repos_dir, + &reqwest::Client::new(), + &GitSource::UnhardenedWithGit(bin.to_str().unwrap().to_string()), + ) + .await; + racer.await.unwrap(); + server.await.unwrap(); + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "failed"); + let invoked = std::fs::read_to_string(&record).unwrap(); + assert!( + invoked.contains("INVOKED clone"), + "the first sync must keep its staged-clone decision: {invoked}" + ); + assert!( + !invoked.lines().any(|line| line.contains(" fetch")), + "a canonical path that appears during peer contact must not be fetched into: {invoked}" + ); + let mirror_rows: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM repos WHERE id = 'z6Mkfoo/hello'") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + mirror_rows, 0, + "the first sync must be re-authorized before mirror registration" + ); + let owner_entries = dir_entries(&repos_dir.join("z6Mkfoo")); + assert_eq!( + owner_entries, + vec!["hello.git".to_string()], + "the rejected race must remove its staged clone and leave only the canonical path" + ); + } + #[sqlx::test] async fn process_batch_registration_failure_leaves_first_sync_recoverable(pool: PgPool) { let state = crate::test_support::test_state(pool.clone()).await; From 45c056ad4e51173f445d18bf297067c27cced1c8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:40:39 -0600 Subject: [PATCH 08/12] fix(node): bound the first-sync namespace lock hold The mirror registration critical section ends once the staged clone is installed; holding the repo advisory lock through blob replication would let peer-controlled network work starve canonical repo creation. --- crates/twigpine-node/src/sync.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index b023be45c..7617dc130 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -1025,6 +1025,7 @@ async fn process_batch( continue; } } + drop(_first_sync_lock); // The lag is push-to-visible: sample at registration, before // the encrypted-blob tail and mark_sync_done. A quarantined // mirror is admitted but withheld from readers, so it reports From 1a9e6ee278c67d8e8f6928fcce514f6c84f3f8c1 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:18:55 -0600 Subject: [PATCH 09/12] test(node): cover historical full-DID sync provenance The migration proof now exercises the pre-canonicalization queue spelling its owner normalization exists to repair, so removing that normalization cannot pass as an equivalent no-op. --- crates/twigpine-node/src/db/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 358e257c0..2c8540fb4 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -12512,7 +12512,7 @@ mod migration_tests { } sqlx::query( "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, enqueued_at, processed_at) - VALUES ('legacyfull-completion', 'z6Mkfoo/legacyfull', 'did:key:zLegacyFullOrigin', 'refs/heads/main', $1, 'done', '2026-11-26T00:02:30Z', '2026-11-26T00:02:30Z')", + VALUES ('legacyfull-completion', 'did:key:z6Mkfoo/legacyfull', 'did:key:zLegacyFullOrigin', 'refs/heads/main', $1, 'done', '2026-11-26T00:02:30Z', '2026-11-26T00:02:30Z')", ) .bind("0".repeat(40)) .execute(db.pool()) From 9f3174432dcd2991f585b173e93b00c79eb7c94b Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:40:35 -0600 Subject: [PATCH 10/12] refactor(node): pass mirror id without a borrow --- crates/twigpine-node/src/db/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 2c8540fb4..116d06704 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -4718,7 +4718,7 @@ impl Db { AND r.origin_node_did IS NULL RETURNING r.origin_node_did"#, ) - .bind(&mirror_id) + .bind(mirror_id) .fetch_optional(&self.pool) .await?) } From 01b5e3a503b271ede20ae9644b58c8e47eb71729 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:51:23 -0600 Subject: [PATCH 11/12] fix(node): repair mirror origin across both slug spellings The history repair joined queue rows to the mirror by exact id, so a legacy full-DID mirror never matched rows stored in the normalized spelling, and a competing origin under the other spelling was not counted. Competitors were also counted only up to the mirror's creation while the repaired row could come from after it, so two post-migration origins resolved to one pin. Read both spellings as the v54 backfill does, repair only when every eligible completed row names one origin, and write the pin to the mirror's physical id. --- crates/twigpine-node/src/db/mod.rs | 147 ++++++++++++++++++++++++----- 1 file changed, 123 insertions(+), 24 deletions(-) diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 116d06704..42e25819d 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -4687,38 +4687,49 @@ impl Db { &self, mirror_id: &str, ) -> Result> { + // History rows may carry either spelling of the slug: `enqueue_sync` + // stored it verbatim before it normalized, and a purge of one spelling + // keeps the shared rows while a sibling survives. Read both, as the v54 + // backfill does, and write the pin to the mirror's physical id. + let canonical = normalize_repo_slug(mirror_id); + let spellings: Vec = match canonical.split_once('/') { + Some((owner, name)) if !owner.contains(':') => { + vec![canonical.clone(), format!("did:key:{owner}/{name}")] + } + _ => vec![canonical.clone()], + }; Ok(sqlx::query_scalar::<_, String>( - r#"UPDATE repos r + r#"WITH mirror AS ( + SELECT id, created_at, + EXISTS ( + SELECT 1 FROM schema_migrations sm + WHERE sm.version = 53 + AND repos.created_at >= sm.applied_at + ) AS after_pin_migration + FROM repos + WHERE id = $1 AND origin_node_did IS NULL + ), + eligible AS ( + SELECT sq.node_did, sq.processed_at, sq.enqueued_at, sq.id + FROM sync_queue sq, mirror + WHERE sq.repo = ANY($2) + AND sq.status = 'done' + AND (mirror.after_pin_migration OR sq.enqueued_at <= mirror.created_at) + ) + UPDATE repos r SET origin_node_did = repair.node_did FROM ( - SELECT DISTINCT ON (sq.repo) sq.repo, sq.node_did - FROM sync_queue sq - JOIN repos mirror ON mirror.id = sq.repo - WHERE sq.status = 'done' - AND mirror.id = $1 - AND mirror.origin_node_did IS NULL - AND ( - EXISTS ( - SELECT 1 FROM schema_migrations sm - WHERE sm.version = 53 - AND mirror.created_at >= sm.applied_at - ) - OR sq.enqueued_at <= mirror.created_at - ) - AND NOT EXISTS ( - SELECT 1 FROM sync_queue other - WHERE other.repo = sq.repo - AND other.status = 'done' - AND other.node_did <> sq.node_did - AND other.enqueued_at <= mirror.created_at - ) - ORDER BY sq.repo, sq.processed_at ASC NULLS LAST, sq.enqueued_at ASC, sq.id ASC + SELECT node_did FROM eligible + WHERE (SELECT count(DISTINCT node_did) FROM eligible) = 1 + ORDER BY processed_at ASC NULLS LAST, enqueued_at ASC, id ASC + LIMIT 1 ) AS repair - WHERE r.id = repair.repo + WHERE r.id = $1 AND r.origin_node_did IS NULL RETURNING r.origin_node_did"#, ) .bind(mirror_id) + .bind(&spellings) .fetch_optional(&self.pool) .await?) } @@ -12725,6 +12736,94 @@ mod migration_tests { } } + #[sqlx::test] + async fn mirror_origin_repair_reads_both_slug_spellings_and_every_eligible_competitor( + pool: sqlx::PgPool, + ) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + let created = "2030-01-01T00:00:00Z"; + let later = "2030-01-01T00:00:01Z"; + for id in [ + "did:key:z6Mkfoo/legacyspell", + "z6Mkfoo/rollingpair", + "z6Mkfoo/crossspell", + ] { + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, machine_id, quarantined) + VALUES ($1, split_part($1, '/', 2), split_part($1, '/', 1), 'mirrored', TRUE, + 'main', $2, $2, '/mirror/' || split_part($1, '/', 2) || '.git', NULL, FALSE)", + ) + .bind(id) + .bind(created) + .execute(db.pool()) + .await + .unwrap(); + } + // Rows inserted directly, so each keeps the spelling it was written + // with: before this change `enqueue_sync` stored the slug verbatim. + for (repo, did) in [ + ("z6Mkfoo/legacyspell", "did:key:zLegacySpellOrigin"), + ("z6Mkfoo/rollingpair", "did:key:zRollingFirst"), + ("z6Mkfoo/rollingpair", "did:key:zRollingSecond"), + ("z6Mkfoo/crossspell", "did:key:zCrossFirst"), + ("did:key:z6Mkfoo/crossspell", "did:key:zCrossSecond"), + ] { + sqlx::query( + "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, status, + enqueued_at, processed_at) + VALUES ($1, $2, $3, 'refs/heads/main', $4, 'done', $5, $5)", + ) + .bind(uuid::Uuid::new_v4().to_string()) + .bind(repo) + .bind(did) + .bind("0".repeat(40)) + .bind(later) + .execute(db.pool()) + .await + .unwrap(); + } + + let repaired = db + .repair_mirror_origin_from_history("did:key:z6Mkfoo/legacyspell") + .await + .unwrap(); + assert_eq!( + repaired.as_deref(), + Some("did:key:zLegacySpellOrigin"), + "history in the normalized spelling is provenance for a legacy full-DID mirror" + ); + let legacy: (String, Option) = sqlx::query_as( + "SELECT disk_path, origin_node_did FROM repos WHERE id = 'did:key:z6Mkfoo/legacyspell'", + ) + .fetch_one(db.pool()) + .await + .unwrap(); + assert_eq!( + legacy, + ( + "/mirror/legacyspell.git".to_string(), + Some("did:key:zLegacySpellOrigin".to_string()) + ), + "the pin lands on the legacy row, which keeps its id and path" + ); + + for (repo, reason) in [ + ( + "z6Mkfoo/rollingpair", + "two completed origins admitted after a post-migration mirror was created are ambiguous", + ), + ( + "z6Mkfoo/crossspell", + "a competing origin recorded under the other slug spelling still makes history ambiguous", + ), + ] { + let repaired = db.repair_mirror_origin_from_history(repo).await.unwrap(); + assert_eq!(repaired, None, "{reason}"); + } + } + #[sqlx::test] async fn enqueue_sync_stores_the_canonical_owner_spelling(pool: sqlx::PgPool) { let db = super::Db::for_testing(pool); From 5399d588b8e9b19f8e46ec8ac101cb98a5c68d8e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:51:23 -0600 Subject: [PATCH 12/12] fix(node): install a first-sync clone before registering it Registration ran before the staged clone was renamed into place, so a failed install left a registered mirror pointing at a missing path. Install first under the namespace lock, then register; if registration fails, remove the installed directory so the retry does not read it as an unproven path. --- crates/twigpine-node/src/sync.rs | 82 ++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 15 deletions(-) diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index 7617dc130..c7c026e2d 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -993,6 +993,23 @@ async fn process_batch( } } } + // Install the staged clone before registering it, still under + // the namespace lock, so a registered row always names an + // installed directory. + if !exists { + if local_path.exists() { + warn!(repo = %item.repo, path = %local_path.display(), "mirror path appeared before staged clone installation; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + if let Err(e) = std::fs::rename(&staging_path, &local_path) { + warn!(repo = %item.repo, path = %local_path.display(), err = %e, "failed to install staged mirror clone; leaving the sync row pending"); + let _ = remove_staging_path(&staging_path); + crate::metrics::record_sync_processed("deferred"); + continue; + } + } // Register in DB so git smart HTTP can serve the mirrored repo if let Err(e) = db .upsert_mirror_repo_with_origin_id( @@ -1006,25 +1023,13 @@ async fn process_batch( { warn!(repo = %item.repo, err = %e, "failed to register mirror repo; leaving the sync row pending"); if !exists { - let _ = remove_staging_path(&staging_path); + // An installed directory with no row would read as an + // unproven path to the retry's first-sync check. + let _ = remove_staging_path(&local_path); } crate::metrics::record_sync_processed("deferred"); continue; } - if !exists { - if local_path.exists() { - warn!(repo = %item.repo, path = %local_path.display(), "mirror path appeared before staged clone installation; leaving the sync row pending"); - let _ = remove_staging_path(&staging_path); - crate::metrics::record_sync_processed("deferred"); - continue; - } - if let Err(e) = std::fs::rename(&staging_path, &local_path) { - warn!(repo = %item.repo, path = %local_path.display(), err = %e, "failed to install staged mirror clone; leaving the sync row pending"); - let _ = remove_staging_path(&staging_path); - crate::metrics::record_sync_processed("deferred"); - continue; - } - } drop(_first_sync_lock); // The lag is push-to-visible: sample at registration, before // the encrypted-blob tail and mark_sync_done. A quarantined @@ -3600,6 +3605,53 @@ git "$@" ); } + #[sqlx::test] + async fn process_batch_registers_a_first_sync_only_after_its_clone_is_installed(pool: PgPool) { + let state = crate::test_support::test_state(pool.clone()).await; + let home = TempDir::new().unwrap(); + let repos_dir = home.path().join("repos"); + std::fs::create_dir_all(&repos_dir).unwrap(); + let (_remote, peer_url) = rooted_remote(&["z6Mkfoo/hello"]); + let did = "did:key:z6MkOrigin"; + seed_local_peer(&pool, did, &peer_url).await; + enqueue(&state.db, "z6Mkfoo/hello", did).await; + // Fail the registration insert, the step that now runs after install. + sqlx::query( + "CREATE FUNCTION fail_mirror_registration() RETURNS trigger AS $$ + BEGIN RAISE EXCEPTION 'registration refused by test'; END $$ LANGUAGE plpgsql", + ) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "CREATE TRIGGER fail_mirror_registration BEFORE INSERT ON repos + FOR EACH ROW EXECUTE FUNCTION fail_mirror_registration()", + ) + .execute(&pool) + .await + .unwrap(); + + run_batch(&state, &repos_dir).await; + + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "pending"); + let local_path = repos_dir.join("z6Mkfoo").join("hello.git"); + assert!( + local_path.symlink_metadata().is_err(), + "a clone installed for a registration that failed must be removed, or the retry reads it as an unproven path" + ); + + sqlx::query("DROP TRIGGER fail_mirror_registration ON repos") + .execute(&pool) + .await + .unwrap(); + run_batch(&state, &repos_dir).await; + assert_eq!(sync_status(&pool, "z6Mkfoo/hello").await, "done"); + assert!( + local_path.is_dir(), + "the retried first sync installs and registers" + ); + } + #[sqlx::test] async fn process_batch_repairs_an_unpinned_mirror_only_for_its_completed_origin(pool: PgPool) { let state = crate::test_support::test_state(pool.clone()).await;