diff --git a/crates/twigpine-node/src/api/events.rs b/crates/twigpine-node/src/api/events.rs index 697f0bca8..7d89f3536 100644 --- a/crates/twigpine-node/src/api/events.rs +++ b/crates/twigpine-node/src/api/events.rs @@ -66,21 +66,29 @@ async fn collect_visible_ref_updates_inner( return Ok(visible); } - // Gate inputs loaded once; DB errors abort (fail closed, never serve). - let deduped = db.list_all_repos_deduped().await?; - // Quarantined mirrors are excluded from the deduped set, and quarantine must - // be withheld from every surface INCLUDING the owner: it's a status decided - // at admission, checked separately from the mirror's (untrustworthy) - // visibility fields. A folded is_public=false cannot enforce that here — + // Gate inputs are loaded per page, only for the repo names the page's rows + // name, so an anonymous request costs work in proportion to the rows it + // scans rather than to the repo table. They accumulate for the whole request: + // each name is loaded once, and the stores below only ever grow. A store + // rebuilt from one page's loads would lose an earlier page's records or + // rules, and a row whose local repo is missing is served as remote, so that + // would fail open. DB errors abort (fail closed, never serve), on any page. + // + // Quarantined repos are excluded from the deduped set, and quarantine must be + // withheld from every surface INCLUDING the owner: it's a status decided at + // admission, checked separately from the mirror's (untrustworthy) visibility + // fields. A folded is_public=false cannot enforce that here, because // visibility_check short-circuits to Allow for the owner before is_public is - // read, so an owner-matched row would leak. Instead, the loop below calls - // RefUpdateRepoIndex::row_visible, which vetoes any row that names a - // quarantined repo before it checks visibility, so the drop bypasses that - // owner short-circuit entirely. - let quarantined = db.list_quarantined_repos().await?; - let ids: Vec = deduped.iter().map(|r| r.id.clone()).collect(); - let rules = db.list_visibility_rules_for_repos(&ids).await?; - let repos = crate::visibility::RefUpdateRepoIndex::new(&deduped, &quarantined); + // read. Instead RefUpdateRepoIndex::row_visible vetoes any row that names a + // quarantined repo before it checks visibility. + // + // Each name is gated against the database as it was when that name was first + // loaded in this walk, never older than the request's start. + let mut requested: std::collections::HashSet = std::collections::HashSet::new(); + let mut active: Vec = Vec::new(); + let mut quarantined: Vec = Vec::new(); + let mut rules: std::collections::HashMap> = + std::collections::HashMap::new(); // Never scan fewer rows than the caller asked for (no regression vs the old // single LIMIT), but cap the walk so a feed of newest-private rows can't @@ -111,6 +119,30 @@ async fn collect_visible_ref_updates_inner( if let Some(last) = rows.last() { after = Some((last.received_at.clone(), last.id.clone())); } + let mut new_names: Vec = rows + .iter() + .filter_map(|u| crate::visibility::ref_update_slug_name(&u.repo)) + .filter(|name| !requested.contains(*name)) + .map(str::to_string) + .collect(); + new_names.sort_unstable(); + new_names.dedup(); + if !new_names.is_empty() { + let loaded = db.list_ref_update_gate_repos_by_names(&new_names).await?; + let ids: Vec = loaded.active.iter().map(|r| r.id.clone()).collect(); + let new_rules = db.list_visibility_rules_for_repos(&ids).await?; + #[cfg(test)] + note_gate_rows( + loaded.active.len() + + loaded.quarantined.len() + + new_rules.values().map(Vec::len).sum::(), + ); + active.extend(loaded.active); + quarantined.extend(loaded.quarantined); + rules.extend(new_rules); + requested.extend(new_names); + } + let repos = crate::visibility::RefUpdateRepoIndex::new(&active, &quarantined); for u in rows { if repos.row_visible(&rules, caller, &u.repo) { visible.push(u); @@ -127,6 +159,26 @@ async fn collect_visible_ref_updates_inner( Ok(visible) } +// Test-only cost counter: how many repo and visibility-rule rows the feed gate +// loaded this request (active and quarantined records plus rule rows). A query +// counter cannot see the cost it guards, since one unbounded SELECT is a single +// query; counting rows is what goes red if the load widens back to the whole +// table. Thread-local because `#[sqlx::test]` runs tests in one process. +#[cfg(test)] +thread_local! { + static GATE_ROWS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +fn note_gate_rows(n: usize) { + GATE_ROWS.with(|c| c.set(c.get() + n)); +} + +#[cfg(test)] +fn take_gate_rows() -> usize { + GATE_ROWS.with(|c| c.replace(0)) +} + /// GET /api/v1/events/ref-updates?limit=50 pub async fn list_ref_updates( State(state): State, @@ -1083,9 +1135,9 @@ mod ref_updates_feed_tests { } // Scenario 10 — a quarantined mirror is withheld from every listing surface. - // Its rows are excluded from list_all_repos_deduped, so without folding them - // into the match universe the gate would misclassify the row as remote and - // serve it to anon. + // Quarantined rows are excluded from the deduped survivors, so without loading + // them into the match universe the gate would misclassify the row as remote + // and serve it to anon. #[sqlx::test] async fn feed_quarantined_mirror_withheld_from_anon(pool: PgPool) { let state = test_state(pool).await; @@ -1765,6 +1817,672 @@ mod ref_updates_feed_tests { "a DB error in the cert fetch must fail closed (500), never an empty 200" ); } + + // --- the feed gate loads only the repos its scanned rows name --- + + const READER: &str = "did:key:z6MkReader"; + const STRANGER: &str = "did:key:z6MkStranger"; + + /// Insert feed rows newest first: `slugs[0]` is the newest row, so with a + /// small page size the position in this list decides which page a row is on. + /// A slash-free slug is written with raw SQL: insert validation rejects it + /// today, but stored rows from before that validation can carry one, and it + /// names no repo, so it is the one row shape that loads nothing. + async fn seed_feed(db: &crate::db::Db, slugs: &[&str]) { + let n = slugs.len(); + for (i, slug) in slugs.iter().enumerate() { + let mut r = ref_row(&format!("row{i:03}"), slug); + let age = n - i; + r.received_at = format!("2026-07-01T10:{:02}:{:02}+00:00", age / 60, age % 60); + if slug.contains('/') { + db.insert_ref_update(&r).await.unwrap(); + } else { + sqlx::query( + "INSERT INTO received_ref_updates + (id, node_did, pusher_did, repo, ref_name, old_sha, new_sha, timestamp, + cert_id, received_at, from_peer, owner_did) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)", + ) + .bind(&r.id) + .bind(&r.node_did) + .bind(&r.pusher_did) + .bind(&r.repo) + .bind(&r.ref_name) + .bind(&r.old_sha) + .bind(&r.new_sha) + .bind(&r.timestamp) + .bind(&r.cert_id) + .bind(&r.received_at) + .bind(&r.from_peer) + .bind(&r.owner_did) + .execute(db.pool()) + .await + .unwrap(); + } + } + } + + /// Many private repos, each with a root rule, that no feed row names. + async fn seed_unrelated_repos_with_rules(pool: &PgPool, n: i32) { + sqlx::query( + "INSERT INTO repos (id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, forked_from, machine_id, quarantined) + SELECT 'unrel-' || g, 'unrel-name-' || g, 'did:key:z6MkUnrel' || g, NULL, + false, 'main', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', + '/tmp/unrel-' || g, NULL, NULL, false + FROM generate_series(1, $1) AS g", + ) + .bind(n) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO visibility_rules + (id, repo_id, path_glob, mode, reader_dids, created_by, created_at) + SELECT 'unrel-rule-' || g, 'unrel-' || g, '/**', 'b', '[]', + 'did:key:z6MkUnrel' || g, '2026-01-01T00:00:00Z' + FROM generate_series(1, $1) AS g", + ) + .bind(n) + .execute(pool) + .await + .unwrap(); + } + + async fn collect_slugs(db: &crate::db::Db, caller: Option<&str>, page: i64) -> Vec { + super::collect_visible_ref_updates_inner(db, None, 50, caller, page) + .await + .unwrap() + .into_iter() + .map(|u| u.repo) + .collect() + } + + // Cost: an anonymous feed request must load only the repos its rows name. + // Five hundred unrelated private repos with rules sit in the table; the feed + // names one public repo, so the gate loads exactly that one record. + #[sqlx::test] + async fn feed_gate_loads_only_the_repos_its_rows_name(pool: PgPool) { + let state = test_state(pool.clone()).await; + seed_unrelated_repos_with_rules(&pool, 500).await; + state + .db + .create_repo(&repo("pub", OWNER, "openrepo", true)) + .await + .unwrap(); + seed_feed(&state.db, &["z6MkOwner/openrepo"]).await; + + super::take_gate_rows(); + let got = collect_slugs(&state.db, None, 2).await; + assert_eq!(got, vec!["z6MkOwner/openrepo"]); + let loaded = super::take_gate_rows(); + assert_eq!( + loaded, 1, + "the gate must load only the named repo, not the inventory; loaded {loaded} rows" + ); + } + + // Cost: a request whose rows name no local repo, an empty feed, and a zero + // limit load nothing at all. + #[sqlx::test] + async fn feed_gate_loads_nothing_when_no_row_names_a_repo(pool: PgPool) { + let state = test_state(pool.clone()).await; + seed_unrelated_repos_with_rules(&pool, 500).await; + + super::take_gate_rows(); + assert!(collect_slugs(&state.db, None, 2).await.is_empty()); + assert_eq!( + super::take_gate_rows(), + 0, + "an empty feed must load no repo rows" + ); + + seed_feed(&state.db, &["noslash", "alsonoslash"]).await; + assert_eq!(collect_slugs(&state.db, None, 2).await.len(), 2); + assert_eq!( + super::take_gate_rows(), + 0, + "slash-free slugs name no repo and must load no repo rows" + ); + + let none = super::collect_visible_ref_updates_inner(&state.db, None, 0, None, 2) + .await + .unwrap(); + assert!(none.is_empty()); + assert_eq!(super::take_gate_rows(), 0, "limit 0 must load nothing"); + } + + // Cost: a name repeated across pages is loaded once per request, not once + // per page. + #[sqlx::test] + async fn feed_gate_loads_each_name_once_per_request(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("pub", OWNER, "openrepo", true)) + .await + .unwrap(); + seed_feed(&state.db, &["z6MkOwner/openrepo"; 6]).await; + + super::take_gate_rows(); + let got = collect_slugs(&state.db, None, 2).await; + assert_eq!(got.len(), 6); + assert_eq!( + super::take_gate_rows(), + 1, + "a name seen on three pages must be loaded once" + ); + } + + // Must-not: a public repo whose root rule restricts it to one reader keeps + // that rule on every page. If later pages lost the rule, the gate would fall + // back to is_public and serve the repo's rows to anyone. Page 2 also names a + // new repo, so it runs a fresh load that must add to the rules, not replace + // them. + #[sqlx::test] + async fn feed_root_rule_holds_on_every_page(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("ruled", OWNER, "ruled", true)) + .await + .unwrap(); + state + .db + .set_visibility_rule( + "ruled", + "/**", + crate::db::VisibilityMode::B, + &[READER.to_string()], + OWNER, + ) + .await + .unwrap(); + seed_feed( + &state.db, + &[ + "z6MkOwner/ruled", + "z6MkOwner/ruled", + "z6MkRemote/a", + "z6MkOwner/ruled", + ], + ) + .await; + + assert_eq!( + collect_slugs(&state.db, None, 2).await, + vec!["z6MkRemote/a"], + "anonymous caller must get no ruled row on any page" + ); + assert_eq!( + collect_slugs(&state.db, Some(STRANGER), 2).await, + vec!["z6MkRemote/a"], + "a stranger must get no ruled row on any page" + ); + assert_eq!(collect_slugs(&state.db, Some(READER), 2).await.len(), 4); + } + + // Must-not: a private repo first named on page 2 is still withheld. + #[sqlx::test] + async fn feed_private_repo_first_named_on_a_later_page_is_withheld(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("priv", OWNER, "secret", false)) + .await + .unwrap(); + seed_feed( + &state.db, + &[ + "z6MkRemote/a", + "z6MkRemote/b", + "z6MkOwner/secret", + "z6MkRemote/c", + ], + ) + .await; + assert_eq!( + collect_slugs(&state.db, None, 2).await, + vec!["z6MkRemote/a", "z6MkRemote/b", "z6MkRemote/c"], + "a private repo first named on page 2 must be withheld" + ); + } + + // Must-not: a private repo named on several pages is withheld on each one, + // including the pages after its records were first loaded. + #[sqlx::test] + async fn feed_private_repo_named_on_several_pages_is_withheld_on_each(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("priv", OWNER, "secret", false)) + .await + .unwrap(); + seed_feed( + &state.db, + &[ + "z6MkOwner/secret", + "z6MkRemote/a", + "z6MkOwner/secret", + "z6MkRemote/b", + "z6MkOwner/secret", + ], + ) + .await; + assert_eq!( + collect_slugs(&state.db, None, 2).await, + vec!["z6MkRemote/a", "z6MkRemote/b"], + "a private repo named on several pages must be withheld on each" + ); + } + + // Must-not: quarantine vetoes a row named only on a later page, for the + // owner in both the bare-key and full did:key forms. + #[sqlx::test] + async fn feed_quarantine_on_a_later_page_is_withheld_from_owner(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .upsert_mirror_repo("z6MkQuar", "jail", "/tmp/q", None, true) + .await + .unwrap(); + state + .db + .create_repo(&repo("q2", "did:key:z6MkQuarTwo", "cell", false)) + .await + .unwrap(); + state.db.set_repo_quarantine("q2", true).await.unwrap(); + seed_feed( + &state.db, + &[ + "z6MkRemote/a", + "z6MkRemote/b", + "z6MkQuar/jail", + "z6MkQuarTwo/cell", + ], + ) + .await; + for caller in [ + None, + Some("z6MkQuar"), + Some("did:key:z6MkQuar"), + Some("z6MkQuarTwo"), + Some("did:key:z6MkQuarTwo"), + ] { + assert_eq!( + collect_slugs(&state.db, caller, 2).await, + vec!["z6MkRemote/a", "z6MkRemote/b"], + "quarantined rows must be withheld from {caller:?}" + ); + } + } + + // Must-not: a public mirror row does not unlock its private canonical twin + // when the pair is first named on a later page. + #[sqlx::test] + async fn feed_public_mirror_on_a_later_page_does_not_unlock_private_canonical(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("canon", "did:key:z6MkPair", "pair", false)) + .await + .unwrap(); + state + .db + .upsert_mirror_repo("z6MkPair", "pair", "/tmp/m", None, false) + .await + .unwrap(); + seed_feed( + &state.db, + &["z6MkRemote/a", "z6MkRemote/b", "z6MkPair/pair"], + ) + .await; + assert_eq!( + collect_slugs(&state.db, None, 2).await, + vec!["z6MkRemote/a", "z6MkRemote/b"] + ); + } + + // Must-not: two owners sharing a repo name are gated per owner on a later + // page; the public owner's row passes and the private owner's row drops. + #[sqlx::test] + async fn feed_shared_name_on_a_later_page_is_gated_per_owner(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("alice", "did:key:z6MkAlice", "shared", true)) + .await + .unwrap(); + state + .db + .create_repo(&repo("bob", "did:key:z6MkBob", "shared", false)) + .await + .unwrap(); + seed_feed( + &state.db, + &[ + "z6MkRemote/a", + "z6MkRemote/b", + "z6MkAlice/shared", + "z6MkBob/shared", + ], + ) + .await; + assert_eq!( + collect_slugs(&state.db, None, 2).await, + vec!["z6MkRemote/a", "z6MkRemote/b", "z6MkAlice/shared"] + ); + } + + // Names match byte for byte, as on main: a row naming a different case of a + // private local repo's name names no local repo and passes as remote. + #[sqlx::test] + async fn feed_name_match_is_exact_bytes(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("priv", OWNER, "widget", false)) + .await + .unwrap(); + seed_feed(&state.db, &["x/WIDGET", "z6MkOwner/widget"]).await; + assert_eq!(collect_slugs(&state.db, None, 2).await, vec!["x/WIDGET"]); + } + + // Must-not-over-drop: loading one page's names never suppresses unrelated + // rows on another page. + #[sqlx::test] + async fn feed_later_page_rows_are_not_over_dropped(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("pub", OWNER, "openrepo", true)) + .await + .unwrap(); + state + .db + .upsert_mirror_repo("z6MkQuar", "jail", "/tmp/q", None, true) + .await + .unwrap(); + seed_feed( + &state.db, + &[ + "z6MkOwner/openrepo", + "z6MkQuar/jail", + "z6MkRemote/a", + "noslash", + ], + ) + .await; + assert_eq!( + collect_slugs(&state.db, None, 2).await, + vec!["z6MkOwner/openrepo", "z6MkRemote/a", "noslash"] + ); + } + + /// Page 1 names no repo, so nothing is loaded until page 2, which names a + /// local public repo. A gate-load failure there must fail the request, not + /// return the page 1 rows already collected. + async fn seed_late_failure_feed(db: &crate::db::Db) { + db.create_repo(&repo("pub", OWNER, "openrepo", true)) + .await + .unwrap(); + seed_feed(db, &["noslash1", "noslash2", "z6MkOwner/openrepo"]).await; + } + + #[sqlx::test] + async fn feed_repo_load_error_on_a_later_page_fails_closed(pool: PgPool) { + let state = test_state(pool.clone()).await; + seed_late_failure_feed(&state.db).await; + sqlx::query("ALTER TABLE repos DROP COLUMN is_public") + .execute(&pool) + .await + .unwrap(); + let got = super::collect_visible_ref_updates_inner(&state.db, None, 50, None, 2).await; + assert!( + got.is_err(), + "a repo-load error on page 2 must fail the request, got {:?}", + got.map(|v| v.len()) + ); + } + + #[sqlx::test] + async fn feed_rule_load_error_on_a_later_page_fails_closed(pool: PgPool) { + let state = test_state(pool.clone()).await; + seed_late_failure_feed(&state.db).await; + sqlx::query("ALTER TABLE visibility_rules DROP COLUMN reader_dids") + .execute(&pool) + .await + .unwrap(); + let got = super::collect_visible_ref_updates_inner(&state.db, None, 50, None, 2).await; + assert!( + got.is_err(), + "a rule-load error on page 2 must fail the request, got {:?}", + got.map(|v| v.len()) + ); + } + + #[sqlx::test] + async fn feed_gate_load_error_is_an_opaque_500(pool: PgPool) { + let state = test_state(pool.clone()).await; + seed_late_failure_feed(&state.db).await; + sqlx::query("ALTER TABLE repos DROP COLUMN is_public") + .execute(&pool) + .await + .unwrap(); + let resp = router(state).oneshot(anon_get()).await.unwrap(); + assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!( + body_json(resp).await, + serde_json::json!({ + "error": "db_error", + "message": crate::error::DB_ERROR_MESSAGE, + }) + ); + } + + /// The gate as it ran before the per-page load: every deduped repo, every + /// quarantined repo, and every rule, loaded once before the walk. The new + /// collector must agree with it row for row on a database that does not + /// change during the request. + async fn reference_collect( + db: &crate::db::Db, + limit: i64, + caller: Option<&str>, + page: i64, + ) -> Vec { + let want = limit.clamp(0, super::MAX_VISIBLE_REF_UPDATES) as usize; + let deduped = db.list_all_repos_deduped().await.unwrap(); + let quarantined_ids: Vec = + sqlx::query_scalar("SELECT id FROM repos WHERE quarantined = TRUE") + .fetch_all(db.pool()) + .await + .unwrap(); + let mut quarantined = Vec::new(); + for id in quarantined_ids { + quarantined.push(db.get_repo_by_id(&id).await.unwrap().unwrap()); + } + let ids: Vec = deduped.iter().map(|r| r.id.clone()).collect(); + let rules = db.list_visibility_rules_for_repos(&ids).await.unwrap(); + let index = crate::visibility::RefUpdateRepoIndex::new(&deduped, &quarantined); + let mut out = Vec::new(); + let mut after: Option<(String, String)> = None; + loop { + let rows = db + .list_ref_updates_keyset( + None, + page, + after.as_ref().map(|(t, i)| (t.as_str(), i.as_str())), + ) + .await + .unwrap(); + if rows.is_empty() { + return out; + } + let last = rows.last().unwrap(); + after = Some((last.received_at.clone(), last.id.clone())); + let fetched = rows.len() as i64; + for u in rows { + if index.row_visible(&rules, caller, &u.repo) { + out.push(u.id); + if out.len() == want { + return out; + } + } + } + if fetched < page { + return out; + } + } + } + + // Differential: on a mixed corpus, the per-page gate serves exactly the rows + // the full preload served, for every caller class and page size. + #[sqlx::test] + async fn feed_gate_matches_the_full_preload(pool: PgPool) { + let state = test_state(pool).await; + let db = &state.db; + db.create_repo(&repo("pub", OWNER, "openrepo", true)) + .await + .unwrap(); + db.create_repo(&repo("priv", OWNER, "secret", false)) + .await + .unwrap(); + db.create_repo(&repo("ruled", OWNER, "ruled", true)) + .await + .unwrap(); + db.set_visibility_rule( + "ruled", + "/**", + crate::db::VisibilityMode::B, + &[READER.to_string()], + OWNER, + ) + .await + .unwrap(); + db.create_repo(&repo("canon", "did:key:z6MkPair", "pair", false)) + .await + .unwrap(); + db.upsert_mirror_repo("z6MkPair", "pair", "/tmp/m", None, false) + .await + .unwrap(); + db.upsert_mirror_repo("z6MkLone", "lonely", "/tmp/l", None, false) + .await + .unwrap(); + db.upsert_mirror_repo("z6MkQuar", "jail", "/tmp/q", None, true) + .await + .unwrap(); + db.create_repo(&repo("alice", "did:key:z6MkAlice", "shared", true)) + .await + .unwrap(); + db.create_repo(&repo("bob", "did:key:z6MkBob", "shared", false)) + .await + .unwrap(); + let slugs = [ + "z6MkOwner/secret", + "z6MkRemote/a", + "z6MkOwner/ruled", + "z6MkPair/pair", + "noslash", + "z6MkOwner/openrepo", + "z6MkQuar/jail", + "z6MkAlice/shared", + "z6MkBob/shared", + "z6MkLone/lonely", + "x/SECRET", + "z6MkOwner/ruled", + "z6MkOwner/secret", + "z6MkRemote/b", + "did:key:z6MkOwner/secret", + "z6MkOwn/secret", + "z6MkQuar/jail", + "z6MkOwner/openrepo", + ]; + seed_feed(db, &slugs).await; + + for caller in [ + None, + Some("z6MkOwner"), + Some(OWNER), + Some(READER), + Some(STRANGER), + Some("did:key:z6MkQuar"), + Some("did:key:z6MkBob"), + ] { + for page in [1, 2, 128] { + for limit in [3, 50] { + let expect = reference_collect(db, limit, caller, page).await; + let got: Vec = + super::collect_visible_ref_updates_inner(db, None, limit, caller, page) + .await + .unwrap() + .into_iter() + .map(|u| u.id) + .collect(); + assert_eq!(got, expect, "caller {caller:?}, page {page}, limit {limit}"); + } + } + } + } + + // The collector must not load the whole deduped repo listing. The row + // counter only sees loads made at the gate's counted call site, so this + // catches the listing being called anywhere else in the collector body. + #[test] + fn collector_does_not_preload_the_whole_inventory() { + let src = include_str!("events.rs"); + let prod = src + .split("\n#[cfg(test)]\nmod ref_updates_feed_tests {") + .next() + .unwrap(); + assert_ne!(prod.len(), src.len(), "test module marker not found"); + let start = prod + .find("async fn collect_visible_ref_updates_inner") + .expect("collector present"); + let body = &prod[start..]; + let body = &body[..body.find("\n}\n").expect("collector end")]; + assert!( + !body.contains("list_all_repos_deduped"), + "the feed collector must not call list_all_repos_deduped" + ); + } + + // The repo-scoped path (list_repo_events, GraphQL refUpdates with a repo) + // walks one slug across pages. A private repo's rows stay withheld on every + // page, its owner still sees them all, and the repo is loaded once. + #[sqlx::test] + async fn feed_repo_scoped_walk_gates_every_page_and_loads_once(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("priv", OWNER, "secret", false)) + .await + .unwrap(); + seed_feed(&state.db, &["z6MkOwner/secret"; 5]).await; + + super::take_gate_rows(); + let anon = super::collect_visible_ref_updates_inner( + &state.db, + Some("z6MkOwner/secret"), + 50, + None, + 2, + ) + .await + .unwrap(); + assert!(anon.is_empty(), "repo-scoped walk must withhold every page"); + assert_eq!(super::take_gate_rows(), 1, "the repo must be loaded once"); + + let owner = super::collect_visible_ref_updates_inner( + &state.db, + Some("z6MkOwner/secret"), + 50, + Some(OWNER), + 2, + ) + .await + .unwrap(); + assert_eq!(owner.len(), 5, "the owner sees every page"); + } } #[cfg(test)] diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index cb6a59f01..51ea1bc98 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -88,6 +88,15 @@ pub struct RepoRecord { pub machine_id: Option, } +/// Repo records the ref-update feed gate needs for a set of names: deduped +/// active survivors and quarantined rows, kept apart because quarantine vetoes a +/// row before visibility is checked. +#[derive(Debug, Default)] +pub struct RefUpdateGateRepos { + pub active: Vec, + pub quarantined: Vec, +} + impl RepoRecord { /// Whether this row is a peer-mirror row: `upsert_mirror_repo` writes ids in /// the `{owner_short}/{name}` slash form (canonical ids are UUIDs), with @@ -4041,7 +4050,8 @@ impl Db { /// The canonical row wins (mirror rows carry a slash-form `id` written only by /// `upsert_mirror_repo`), ties broken by earliest `created_at` then `id` so a /// full tie still picks a deterministic survivor. `list_all_repos_deduped_with_stars`, - /// `list_all_repos_deduped`, and the marker logic in + /// `list_all_repos_deduped`, `scoped_dedup_sql`, `ref_update_gate_by_names_sql`, + /// and the marker logic in /// `crate::api::repos::dedupe_canonical_repos` must stay in sync. fn dedup_cte() -> String { format!( @@ -4118,6 +4128,42 @@ impl Db { ) } + /// SQL for `list_ref_update_gate_repos_by_names`: the `dedup_cte` survivor + /// rule with the name filter inside the CTE (`name` is part of every group + /// key, so the filter keeps or drops whole groups and never changes a + /// survivor), plus the quarantined rows with those names, tagged by + /// `gate_quarantined`. `$1` is a `text[]` of names, matched by the + /// `idx_repos_name` index. + pub fn ref_update_gate_by_names_sql() -> String { + format!( + "WITH deduped AS ( + SELECT DISTINCT ON ({key}, name) + id, name, owner_did, description, is_public, default_branch, + created_at, + MAX(updated_at) OVER ( + PARTITION BY {key}, name + ) AS updated_at, + disk_path, forked_from, machine_id + FROM repos + WHERE quarantined = FALSE AND name = ANY($1) + ORDER BY {key}, name, + CASE WHEN position('/' in id) > 0 THEN 1 ELSE 0 END, + created_at ASC, id ASC + ) + SELECT id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, forked_from, machine_id, + FALSE AS gate_quarantined + FROM deduped + UNION ALL + SELECT id, name, owner_did, description, is_public, default_branch, + created_at, updated_at, disk_path, forked_from, machine_id, + TRUE AS gate_quarantined + FROM repos + WHERE quarantined = TRUE AND name = ANY($1)", + key = OWNER_KEY_CASE_SQL + ) + } + /// All repos with star counts, mirror-deduplicated via `DEDUP_CTE` and /// ordered newest-first with ties broken by repo ID, optionally filtered to /// one owner. Returns the full set (no SQL pagination): the listing surface @@ -4299,20 +4345,36 @@ impl Db { Ok(rows.into_iter().map(row_to_repo).collect()) } - /// Repos currently quarantined (admitted as mirrors but withheld from every - /// listing surface). `list_all_repos_deduped` excludes these (its `DEDUP_CTE` - /// filters `quarantined = FALSE`), so a gate that resolves a slug against the - /// deduped set must also match against these and fail closed, or a quarantined - /// repo's row is misclassified as remote/gossip-only and served. - pub async fn list_quarantined_repos(&self) -> Result> { - let rows = sqlx::query( - "SELECT id, name, owner_did, description, is_public, default_branch, - created_at, updated_at, disk_path, forked_from, machine_id - FROM repos WHERE quarantined = TRUE", - ) - .fetch_all(&self.pool) - .await?; - Ok(rows.into_iter().map(row_to_repo).collect()) + /// The ref-update feed gate's repo inputs for the given repo names, in one + /// statement: the deduped active survivors with those names (the same rule as + /// `list_all_repos_deduped`) and the quarantined rows with those names. + /// Quarantined rows are excluded from the deduped set, so the gate must also + /// match a slug against them and fail closed, or a quarantined repo's row is + /// misclassified as remote/gossip-only and served. A record this leaves out is + /// served as remote rather than denied, so the result must equal the full sets + /// restricted to `names`. Empty input returns empty without a query. + pub async fn list_ref_update_gate_repos_by_names( + &self, + names: &[String], + ) -> Result { + let mut out = RefUpdateGateRepos::default(); + if names.is_empty() { + return Ok(out); + } + let rows = sqlx::query(&Self::ref_update_gate_by_names_sql()) + .bind(names) + .fetch_all(&self.pool) + .await?; + for row in rows { + let quarantined: bool = row.get("gate_quarantined"); + let record = row_to_repo(row); + if quarantined { + out.quarantined.push(record); + } else { + out.active.push(record); + } + } + Ok(out) } /// Count of distinct logical repos (mirror + canonical collapsed). Uses the @@ -18316,6 +18378,270 @@ mod scoped_repo_lookup_plan_tests { let generic_plan = explain_scoped_repo_lookup(&pool, true).await; assert_scoped_repo_plan(&generic_plan, "generic-plan"); } + + /// The ref-update feed gate loads repos by the names a page of feed rows + /// names, on an anonymous route. Its cost claim holds only if the database + /// reaches those rows through the name index rather than reading the whole + /// table, which a count of returned rows cannot see. + #[sqlx::test] + async fn ref_update_gate_lookup_uses_the_name_index(pool: PgPool) { + let db = Db::for_testing(pool.clone()); + db.migrate().await.unwrap(); + seed_populated_repos(&pool).await; + + for force_generic in [false, true] { + let mut conn = pool.acquire().await.unwrap(); + let mode = if force_generic { + "force_generic_plan" + } else { + "force_custom_plan" + }; + sqlx::query(&format!("SET plan_cache_mode = {mode}")) + .execute(&mut *conn) + .await + .unwrap(); + let sql = format!( + "PREPARE gate_plan(text[]) AS {}", + Db::ref_update_gate_by_names_sql() + ); + sqlx::query(&sql).execute(&mut *conn).await.unwrap(); + let explained = sqlx::query_scalar::<_, Value>( + "EXPLAIN (ANALYZE, FORMAT JSON) EXECUTE gate_plan(ARRAY['repo-name-1']::text[])", + ) + .fetch_one(&mut *conn) + .await + .unwrap(); + sqlx::query("DEALLOCATE gate_plan") + .execute(&mut *conn) + .await + .unwrap(); + sqlx::query("RESET plan_cache_mode") + .execute(&mut *conn) + .await + .unwrap(); + let plan = explained + .as_array() + .and_then(|a| a.first()) + .and_then(|o| o.get("Plan")) + .cloned() + .expect("EXPLAIN (FORMAT JSON) returns [{\"Plan\": ...}]"); + // Both halves of the query (survivors and quarantined rows) must reach + // `repos` through the name index, as a plain or bitmap index scan, and + // must not filter away a meaningful number of unrelated rows. + let mut seqscan = false; + let mut name_index_scans = 0; + let mut discarded = 0.0_f64; + plan_walk(&plan, &mut |node| { + let node_type = node.get("Node Type").and_then(Value::as_str).unwrap_or(""); + let relation = node + .get("Relation Name") + .and_then(Value::as_str) + .unwrap_or(""); + if node_type == "Seq Scan" && relation == "repos" { + seqscan = true; + } + if node.get("Index Name").and_then(Value::as_str) == Some("idx_repos_name") { + name_index_scans += 1; + } + discarded += node + .get("Rows Removed by Filter") + .and_then(Value::as_f64) + .unwrap_or(0.0); + }); + assert!(!seqscan, "{mode}: gate lookup scanned all of repos: {plan}"); + assert_eq!( + name_index_scans, 2, + "{mode}: both halves must use idx_repos_name: {plan}" + ); + assert!( + discarded < 100.0, + "{mode}: gate lookup discarded unrelated rows: {discarded}: {plan}" + ); + } + } +} + +#[cfg(test)] +mod ref_update_gate_repo_tests { + use super::{Db, RepoRecord}; + use chrono::{DateTime, Utc}; + use sqlx::PgPool; + use std::collections::BTreeSet; + + async fn db(pool: PgPool) -> Db { + let db = Db::for_testing(pool); + db.run_migrations().await.unwrap(); + db + } + + fn at(s: &str) -> DateTime { + DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc) + } + + fn repo(id: &str, owner_did: &str, name: &str, is_public: bool, created: &str) -> RepoRecord { + RepoRecord { + id: id.to_string(), + name: name.to_string(), + owner_did: owner_did.to_string(), + description: None, + is_public, + default_branch: "main".to_string(), + created_at: at(created), + updated_at: at(created), + disk_path: format!("/srv/{id}"), + forked_from: None, + machine_id: None, + } + } + + fn key(r: &RepoRecord) -> (String, bool, DateTime) { + (r.id.clone(), r.is_public, r.updated_at) + } + + /// A corpus covering every survivor rule the dedup applies: canonical and + /// mirror pairs, a private canonical with a public mirror twin, bare and full + /// did:key owners, two owners sharing one name, a mirror with no twin, and + /// quarantined mirrors (one sharing a name with an active repo). + async fn seed(db: &Db) { + for r in [ + repo( + "c-widget-a", + "did:key:z6MkA", + "widget", + true, + "2026-01-01T00:00:00Z", + ), + repo( + "c-widget-b", + "did:web:host:team", + "widget", + false, + "2026-01-02T00:00:00Z", + ), + repo( + "c-secret", + "did:key:z6MkPriv", + "secret", + false, + "2026-01-03T00:00:00Z", + ), + repo( + "c-other", + "did:key:z6MkA", + "other", + true, + "2026-01-04T00:00:00Z", + ), + ] { + db.create_repo(&r).await.unwrap(); + } + // Public mirror twins: the private canonical must still win its group. + db.upsert_mirror_repo("z6MkPriv", "secret", "/srv/m1", None, false) + .await + .unwrap(); + db.upsert_mirror_repo("z6MkA", "widget", "/srv/m2", None, false) + .await + .unwrap(); + // Mirror with no canonical twin. + db.upsert_mirror_repo("z6MkLone", "lonely", "/srv/m3", None, false) + .await + .unwrap(); + // Quarantined mirrors, one sharing the name "widget". + db.upsert_mirror_repo("z6MkQuar", "widget", "/srv/q1", None, true) + .await + .unwrap(); + db.upsert_mirror_repo("z6MkQuar", "jail", "/srv/q2", None, true) + .await + .unwrap(); + } + + async fn all_quarantined(db: &Db) -> Vec { + let ids: Vec = sqlx::query_scalar("SELECT id FROM repos WHERE quarantined = TRUE") + .fetch_all(db.pool()) + .await + .unwrap(); + let mut out = Vec::new(); + for id in ids { + out.push(db.get_repo_by_id(&id).await.unwrap().unwrap()); + } + out + } + + /// The name-scoped load must return exactly the full deduped and quarantined + /// sets restricted to the requested names. A record it leaves out is not + /// denied by the feed gate but treated as remote and served, so any drift + /// from the full dedup (survivor order, a leftover owner filter, a missing + /// quarantined half) fails open. + #[sqlx::test] + async fn gate_lookup_matches_full_sets_filtered_by_name(pool: PgPool) { + let db = db(pool).await; + seed(&db).await; + let full_active = db.list_all_repos_deduped().await.unwrap(); + let full_quarantined = all_quarantined(&db).await; + + let name_sets: [&[&str]; 6] = [ + &["widget"], + &["secret"], + &["lonely", "jail"], + &["widget", "secret", "other", "lonely", "jail"], + &["absent"], + &["WIDGET"], + ]; + for names in name_sets { + let wanted: Vec = names.iter().map(|n| n.to_string()).collect(); + let got = db + .list_ref_update_gate_repos_by_names(&wanted) + .await + .unwrap(); + let expect_active: BTreeSet<_> = full_active + .iter() + .filter(|r| names.contains(&r.name.as_str())) + .map(key) + .collect(); + let expect_quarantined: BTreeSet<_> = full_quarantined + .iter() + .filter(|r| names.contains(&r.name.as_str())) + .map(|r| r.id.clone()) + .collect(); + let got_active: BTreeSet<_> = got.active.iter().map(key).collect(); + let got_quarantined: BTreeSet<_> = + got.quarantined.iter().map(|r| r.id.clone()).collect(); + assert_eq!(got_active, expect_active, "active set for {names:?}"); + assert_eq!( + got_quarantined, expect_quarantined, + "quarantined set for {names:?}" + ); + } + + // Spot-check the corpus actually exercises the rules the differential + // relies on, so a corpus edit cannot make it vacuous. + let secret = db + .list_ref_update_gate_repos_by_names(&["secret".to_string()]) + .await + .unwrap(); + assert_eq!(secret.active.len(), 1); + assert_eq!( + secret.active[0].id, "c-secret", + "private canonical beats public mirror" + ); + assert!(!secret.active[0].is_public); + let widget = db + .list_ref_update_gate_repos_by_names(&["widget".to_string()]) + .await + .unwrap(); + assert_eq!(widget.active.len(), 2, "two owners share the name"); + assert_eq!(widget.quarantined.len(), 1); + assert!(widget.active.iter().all(|r| r.id != "z6MkQuar/widget")); + } + + #[sqlx::test] + async fn gate_lookup_with_no_names_returns_empty(pool: PgPool) { + let db = db(pool).await; + seed(&db).await; + let got = db.list_ref_update_gate_repos_by_names(&[]).await.unwrap(); + assert!(got.active.is_empty()); + assert!(got.quarantined.is_empty()); + } } /// Exercises the iCaptcha single-use proof ledger (`icaptcha_consumed_proofs`), diff --git a/crates/twigpine-node/src/graphql/query.rs b/crates/twigpine-node/src/graphql/query.rs index 341ae53b1..76d33adc0 100644 --- a/crates/twigpine-node/src/graphql/query.rs +++ b/crates/twigpine-node/src/graphql/query.rs @@ -153,9 +153,9 @@ impl QueryRoot { } // Complexity is additive with a base reflecting the collector's fixed scan: - // every request loads the full deduped repo set, the quarantined set, and - // the visibility rules, then walks up to max(limit, 2048) event rows past - // withheld ones, regardless of `limit`. A multiplicative price both + // every request walks up to max(limit, 2048) event rows past withheld ones, + // regardless of `limit`, loading the repos and visibility rules those rows + // name as it goes. A multiplicative price both // undercharged limit:1 (51 for that fixed work) and made a request at the // documented maximum unreachable (two fields at max limit cost 450 > 400). // diff --git a/crates/twigpine-node/src/visibility.rs b/crates/twigpine-node/src/visibility.rs index 5da973915..840cbe8ec 100644 --- a/crates/twigpine-node/src/visibility.rs +++ b/crates/twigpine-node/src/visibility.rs @@ -166,7 +166,7 @@ impl<'a> RefUpdateRepoIndex<'a> { caller: Option<&str>, row_repo: &str, ) -> bool { - let Some((_, name)) = row_repo.rsplit_once('/') else { + let Some(name) = ref_update_slug_name(row_repo) else { return true; }; let Some(candidates) = self.by_name.get(name) else { @@ -195,6 +195,14 @@ impl<'a> RefUpdateRepoIndex<'a> { } } +/// The repo-name half of a ref-update slug: everything after its last `/`, or +/// `None` when the slug has no `/`. The feed gate buckets local repos by this +/// name, and the feed collector loads gate inputs by it, so both must split a +/// slug the same way or a local repo's rows would be treated as remote. +pub(crate) fn ref_update_slug_name(slug: &str) -> Option<&str> { + slug.rsplit_once('/').map(|(_, name)| name) +} + /// Whether `row_repo`'s peer-supplied slug names the local `record`. The single /// match predicate shared by the visibility check and quarantine veto in /// [`RefUpdateRepoIndex::row_visible`], so they cannot diverge about which rows a @@ -853,6 +861,18 @@ mod tests { assert!(!ref_update_row_names_repo(&bare, "noslash")); } + /// The ref-update feed loads gate inputs by the name this helper returns, and the + /// index matches on the same split. A different split on either side (owner half + /// included, first `/` instead of last) would load nothing for a local repo and + /// pass its rows through as remote. + #[test] + fn ref_update_slug_name_takes_the_last_segment() { + assert_eq!(ref_update_slug_name("a/b/c"), Some("c")); + assert_eq!(ref_update_slug_name("did:key:z6Mk/x"), Some("x")); + assert_eq!(ref_update_slug_name("owner/"), Some("")); + assert_eq!(ref_update_slug_name("noslash"), None); + } + #[test] fn feed_checks_every_same_name_candidate() { let deduped = [