diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 79c9e218..18dd57b4 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -1,3 +1,4 @@ +use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result}; @@ -47,6 +48,13 @@ pub struct RecordedOrphanMigration { /// Maximum visible repositories per page, plus one internal look-ahead row. pub(crate) const MAX_VISIBLE_REPO_PAGE_SIZE: usize = 200; +/// Postgres regex matching exactly the visibility-rule globs that cover the +/// repository root, i.e. the globs for which `visibility::glob_prefix` returns +/// `"/"`: a run of slashes followed by zero or more `**` pairs (the empty string +/// included). Every SQL query that applies the root visibility decision uses this +/// one constant; a differential test pins it to the Rust matcher. +pub(crate) const ROOT_GLOB_SQL_REGEX: &str = "^/*([*][*])*$"; + /// Maximum repository name length in bytes. `repo_cursor` embeds the name in /// a base64(JSON) cursor that `parse_repo_cursor` rejects over 4096 bytes, so /// every write path must bound the name: a cursor the server emits must @@ -1203,6 +1211,16 @@ pub struct ProfileRecord { #[derive(Clone)] pub struct Db { pool: PgPool, + /// Last anonymously listable repo count, shared by clones. See + /// `anonymously_listable_repo_count_cached`. + anon_listable_count: Arc>, +} + +#[derive(Default)] +struct AnonListableCount { + cached: Option<(std::time::Instant, i64)>, + #[cfg(test)] + recounts: u64, } impl Db { @@ -1219,7 +1237,10 @@ impl Db { #[cfg(any(test, feature = "test-harness"))] pub fn for_testing(pool: PgPool) -> Self { - Self { pool } + Self { + pool, + anon_listable_count: Arc::default(), + } } /// Test-only: apply the full schema to a fresh pool. `#[sqlx::test]` @@ -1252,7 +1273,10 @@ impl Db { .connect(database_url) .await .context("connecting to postgres")?; - let db = Self { pool }; + let db = Self { + pool, + anon_listable_count: Arc::default(), + }; db.migrate().await?; Ok(db) } @@ -4190,6 +4214,60 @@ impl Db { Ok(rows.into_iter().map(row_to_repo).collect()) } + /// Number of logical repos an anonymous caller may list, computed in one + /// aggregate so no repo or rule row leaves the database. For a caller with no + /// identity the root decision reduces to: the deduped survivor is public and + /// none of its rules covers `/` (a root rule denies anonymous readers whatever + /// its reader list). Survivor selection and quarantine exclusion come from the + /// shared dedup CTE, so this agrees with `listable_at_root` over + /// `list_all_repos_deduped`. + pub async fn count_anonymously_listable_repos(&self) -> Result { + let sql = format!( + "{} + SELECT COUNT(*) AS cnt FROM deduped d + WHERE d.is_public + AND NOT EXISTS ( + SELECT 1 FROM visibility_rules v + WHERE v.repo_id = d.id AND v.path_glob ~ $2 + )", + Self::dedup_cte() + ); + let row = sqlx::query(&sql) + .bind(None::<&str>) + .bind(ROOT_GLOB_SQL_REGEX) + .fetch_one(&self.pool) + .await?; + Ok(row.get::("cnt")) + } + + /// `count_anonymously_listable_repos`, reused for `ttl` after a successful + /// count. The lock is held across the query, so concurrent misses share one + /// count instead of each running it; an anonymous flood therefore costs at most + /// one aggregate per window. The refresh runs in its own task that owns the + /// lock, so a caller dropped mid-count (client reset) neither releases the lock + /// early nor discards the result. A failed count is returned and never cached. + pub async fn anonymously_listable_repo_count_cached(&self, ttl: Duration) -> Result { + let mut slot = self.anon_listable_count.clone().lock_owned().await; + if let Some((at, count)) = slot.cached { + if at.elapsed() < ttl { + return Ok(count); + } + } + #[cfg(test)] + { + slot.recounts += 1; + } + let db = self.clone(); + tokio::spawn(async move { + let started = std::time::Instant::now(); + let count = db.count_anonymously_listable_repos().await?; + slot.cached = Some((started, count)); + Ok(count) + }) + .await + .context("anonymous repo count task")? + } + /// Resolve only the requested repository ids through the same canonical /// survivor and quarantine rules as `list_all_repos_deduped`. pub async fn list_repos_deduped_by_ids(&self, repo_ids: &[String]) -> Result> { @@ -4269,7 +4347,7 @@ impl Db { FROM deduped d LEFT JOIN LATERAL ( SELECT reader_dids FROM visibility_rules v - WHERE v.repo_id = d.id AND v.path_glob ~ '^/*([*][*])*$' + WHERE v.repo_id = d.id AND v.path_glob ~ '{root}' ORDER BY v.path_glob DESC LIMIT 1 ) root_rule ON TRUE WHERE ( @@ -4289,6 +4367,7 @@ impl Db { LIMIT $6", Self::dedup_cte(), key = OWNER_KEY_CASE_SQL, + root = ROOT_GLOB_SQL_REGEX, ); let rows = sqlx::query(&sql) .bind(None::<&str>) @@ -22851,6 +22930,349 @@ mod policy_fence_tests { } } +#[cfg(test)] +mod anon_listable_count_tests { + use super::{Db, RepoRecord, VisibilityMode, VisibilityRule, ROOT_GLOB_SQL_REGEX}; + use chrono::Utc; + use sqlx::PgPool; + use std::time::Duration; + + const OWNER: &str = "did:key:z6MkAnonCountOwnerAAAAAAAAAAAAAAAAAAAAAA"; + + async fn db(pool: PgPool) -> Db { + let db = Db::for_testing(pool); + db.run_migrations().await.unwrap(); + db + } + + fn repo(id: &str, owner_did: &str, name: &str, is_public: bool) -> 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: Utc::now(), + updated_at: Utc::now(), + disk_path: format!("/srv/{id}"), + forked_from: None, + machine_id: None, + } + } + + fn rule(glob: &str) -> VisibilityRule { + VisibilityRule { + id: "r".to_string(), + repo_id: "x".to_string(), + path_glob: glob.to_string(), + mode: VisibilityMode::B, + reader_dids: Vec::new(), + created_by: OWNER.to_string(), + created_at: Utc::now(), + } + } + + /// Every string of length 0..=5 over the characters the root decision cares + /// about. The SQL predicate must agree with the Rust matcher on each one. + fn glob_corpus() -> Vec { + let alphabet = ['/', '*', 'a', ' ']; + let mut out = vec![String::new()]; + let mut layer = vec![String::new()]; + for _ in 0..5 { + let mut next = Vec::new(); + for prefix in &layer { + for c in alphabet { + next.push(format!("{prefix}{c}")); + } + } + out.extend(next.iter().cloned()); + layer = next; + } + out + } + + #[sqlx::test] + async fn root_glob_sql_regex_matches_rust_matcher(pool: PgPool) { + let db = db(pool).await; + let corpus = glob_corpus(); + assert_eq!(corpus.len(), 1365); + let rows: Vec<(String, bool)> = + sqlx::query_as("SELECT g, g ~ $1 FROM unnest($2::text[]) AS g") + .bind(ROOT_GLOB_SQL_REGEX) + .bind(&corpus) + .fetch_all(db.pool()) + .await + .unwrap(); + assert_eq!(rows.len(), corpus.len()); + for (glob, sql_matches_root) in rows { + let rust_hides = + !crate::visibility::listable_at_root(&[rule(&glob)], true, OWNER, None); + assert_eq!( + sql_matches_root, rust_hides, + "SQL root predicate and listable_at_root disagree on glob {glob:?}" + ); + } + } + + #[sqlx::test] + async fn anon_count_root_rule_with_readers_hides(pool: PgPool) { + let db = db(pool).await; + let r = repo("uuid-root-readers", OWNER, "hidden", true); + db.create_repo(&r).await.unwrap(); + db.set_visibility_rule( + &r.id, + "/", + VisibilityMode::A, + &["did:key:z6MkSomeReaderBBBBBBBBBBBBBBBBBBBBBBBBBB".to_string()], + OWNER, + ) + .await + .unwrap(); + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 0); + } + + #[sqlx::test] + async fn anon_count_non_root_rule_does_not_hide(pool: PgPool) { + let db = db(pool).await; + let r = repo("uuid-subpath", OWNER, "open", true); + db.create_repo(&r).await.unwrap(); + let readers: Vec = (0..500) + .map(|i| format!("did:key:z6MkReader{i:040}")) + .collect(); + db.set_visibility_rule(&r.id, "/secret", VisibilityMode::A, &readers, OWNER) + .await + .unwrap(); + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 1); + } + + #[sqlx::test] + async fn anon_count_excludes_quarantined(pool: PgPool) { + let db = db(pool).await; + let r = repo("uuid-quarantined", OWNER, "quarantined", true); + db.create_repo(&r).await.unwrap(); + db.set_repo_quarantine(&r.id, true).await.unwrap(); + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 0); + } + + #[sqlx::test] + async fn anon_count_mirror_pair_uses_survivor_rules(pool: PgPool) { + let db = db(pool).await; + let short = "z6MkAnonCountMirrorCCCCCCCCCCCCCCCCCCCCCC"; + let canonical = repo("uuid-canonical", &format!("did:key:{short}"), "pair", true); + db.create_repo(&canonical).await.unwrap(); + db.upsert_mirror_repo(short, "pair", "/srv/mirror", None, false) + .await + .unwrap(); + assert_eq!( + db.count_anonymously_listable_repos().await.unwrap(), + 1, + "a mirror and canonical pair is one logical repo" + ); + + // A root rule on the non-surviving mirror row leaves the survivor listable, + // exactly as the per-row filter did. + db.set_visibility_rule(&format!("{short}/pair"), "/", VisibilityMode::B, &[], OWNER) + .await + .unwrap(); + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 1); + + db.set_visibility_rule(&canonical.id, "/**", VisibilityMode::B, &[], OWNER) + .await + .unwrap(); + assert_eq!( + db.count_anonymously_listable_repos().await.unwrap(), + 0, + "a root rule on the survivor hides the group" + ); + } + + const LONG: Duration = Duration::from_secs(3600); + + #[sqlx::test] + async fn anon_count_cached_within_ttl(pool: PgPool) { + let db = db(pool).await; + db.create_repo(&repo("uuid-a", OWNER, "a", true)) + .await + .unwrap(); + assert_eq!( + db.anonymously_listable_repo_count_cached(LONG) + .await + .unwrap(), + 1 + ); + db.create_repo(&repo("uuid-b", OWNER, "b", true)) + .await + .unwrap(); + assert_eq!( + db.anonymously_listable_repo_count_cached(LONG) + .await + .unwrap(), + 1, + "a second request inside the window must be served without a recount" + ); + assert_eq!(db.anon_listable_count.lock().await.recounts, 1); + } + + #[sqlx::test] + async fn anon_count_recomputes_after_ttl(pool: PgPool) { + let db = db(pool).await; + db.create_repo(&repo("uuid-a", OWNER, "a", true)) + .await + .unwrap(); + assert_eq!( + db.anonymously_listable_repo_count_cached(Duration::ZERO) + .await + .unwrap(), + 1 + ); + db.create_repo(&repo("uuid-b", OWNER, "b", true)) + .await + .unwrap(); + assert_eq!( + db.anonymously_listable_repo_count_cached(Duration::ZERO) + .await + .unwrap(), + 2, + "an expired value must be recounted" + ); + } + + #[sqlx::test] + async fn anon_count_concurrent_misses_share_one_query(pool: PgPool) { + let db = std::sync::Arc::new(db(pool).await); + db.create_repo(&repo("uuid-a", OWNER, "a", true)) + .await + .unwrap(); + let calls: Vec<_> = (0..16) + .map(|_| { + let db = db.clone(); + tokio::spawn(async move { db.anonymously_listable_repo_count_cached(LONG).await }) + }) + .collect(); + for call in calls { + assert_eq!(call.await.unwrap().unwrap(), 1); + } + assert_eq!( + db.anon_listable_count.lock().await.recounts, + 1, + "concurrent cold requests must share one count query" + ); + } + + /// A caller dropped mid-count (client reset) must not release the + /// single-flight lock with nothing cached, or a request-then-reset loop runs + /// one count per request. + #[sqlx::test] + async fn anon_count_cancelled_caller_still_fills_cache(pool: PgPool) { + let db = std::sync::Arc::new(db(pool.clone()).await); + db.create_repo(&repo("uuid-a", OWNER, "a", true)) + .await + .unwrap(); + // Block the count query on a table lock so the cold call is mid-query. + let mut blocker = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE repos IN ACCESS EXCLUSIVE MODE") + .execute(&mut *blocker) + .await + .unwrap(); + let cold = { + let db = db.clone(); + tokio::spawn(async move { db.anonymously_listable_repo_count_cached(LONG).await }) + }; + while db.anon_listable_count.try_lock().is_ok() { + tokio::task::yield_now().await; + } + cold.abort(); + let _ = cold.await; + blocker.commit().await.unwrap(); + assert_eq!( + db.anonymously_listable_repo_count_cached(LONG) + .await + .unwrap(), + 1 + ); + assert_eq!( + db.anon_listable_count.lock().await.recounts, + 1, + "a cancelled caller must not cause a second count" + ); + } + + #[sqlx::test] + async fn anon_count_ttl_anchors_at_refresh_start(pool: PgPool) { + let db = std::sync::Arc::new(db(pool.clone()).await); + db.create_repo(&repo("uuid-a", OWNER, "a", true)) + .await + .unwrap(); + let ttl = Duration::from_millis(100); + let mut blocker = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE repos IN ACCESS EXCLUSIVE MODE") + .execute(&mut *blocker) + .await + .unwrap(); + let cold = { + let db = db.clone(); + tokio::spawn(async move { db.anonymously_listable_repo_count_cached(ttl).await }) + }; + while db.anon_listable_count.try_lock().is_ok() { + tokio::task::yield_now().await; + } + tokio::time::sleep(Duration::from_millis(200)).await; + blocker.commit().await.unwrap(); + assert_eq!(cold.await.unwrap().unwrap(), 1); + let elapsed = db + .anon_listable_count + .lock() + .await + .cached + .expect("a successful count is cached") + .0 + .elapsed(); + assert!( + elapsed >= Duration::from_millis(150), + "the cached timestamp must include the blocked refresh duration, elapsed was {elapsed:?}" + ); + db.create_repo(&repo("uuid-b", OWNER, "b", true)) + .await + .unwrap(); + assert_eq!( + db.anonymously_listable_repo_count_cached(ttl) + .await + .unwrap(), + 2, + "a value cached for longer than the TTL must be recounted immediately" + ); + } + + #[sqlx::test] + async fn anon_count_error_not_cached(pool: PgPool) { + let db = db(pool).await; + db.pool().close().await; + assert!(db + .anonymously_listable_repo_count_cached(LONG) + .await + .is_err()); + assert!( + db.anon_listable_count.lock().await.cached.is_none(), + "a failed count must not be cached" + ); + } + + #[sqlx::test] + async fn anon_count_private_and_empty(pool: PgPool) { + let db = db(pool).await; + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 0); + db.create_repo(&repo("uuid-private", OWNER, "private", false)) + .await + .unwrap(); + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 0); + db.create_repo(&repo("uuid-public", OWNER, "public", true)) + .await + .unwrap(); + assert_eq!(db.count_anonymously_listable_repos().await.unwrap(), 1); + } +} + #[cfg(test)] mod did_point_read_tests { use super::Db; diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index d24eae07..2bcf5810 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -1069,31 +1069,25 @@ async fn node_info(State(state): State) -> Json { Json(body) } +/// How long the anonymous stats repo count is reused before a recount. +const STATS_REPO_COUNT_TTL: std::time::Duration = std::time::Duration::from_secs(30); + pub(crate) async fn stats(State(state): State) -> Json { // Count only the repos an anonymous caller could list, so the aggregate does - // not leak the existence of private/mode-A repos (#104 count oracle). Mirror - // the listing seam (api/repos.rs): over-fetch the deduped set, batch-load the - // visibility rules, and keep rows that pass listable_at_root. The caller is - // always None — meta_routes carries no auth layer (see the route group in this - // file). Fail closed: any DB error collapses the whole count to 0 (an - // under-count never leaks existence), preserving the prior `.unwrap_or(0)`. - let repos = async { - // stats only needs the count, so use the no-stars deduped list (same - // DEDUP_CTE) and skip the repo_stars aggregation the listing path needs. - let rows = state.db.list_all_repos_deduped().await?; - let ids: Vec = rows.iter().map(|r| r.id.clone()).collect(); - let rules_by_repo = state.db.list_visibility_rules_for_repos(&ids).await?; - let count = rows - .iter() - .filter(|r| { - let rules = rules_by_repo.get(&r.id).map(Vec::as_slice).unwrap_or(&[]); - crate::visibility::listable_at_root(rules, r.is_public, &r.owner_did, None) - }) - .count() as i64; - Ok::(count) - } - .await - .unwrap_or(0); + // not leak the existence of private, hide-existence or root-denied repos + // (#104 count oracle). meta_routes carries no auth layer, so the caller is + // always anonymous, and the count is computed in one SQL aggregate rather than + // by loading the inventory and every visibility rule per request (#485). The + // value is reused for STATS_REPO_COUNT_TTL and concurrent misses share one + // query, so an anonymous flood costs at most one count per window. A warm + // hit is served without touching Postgres, including during an outage; the + // TTL bounds that reuse. After expiry a failed refresh renders 0, since an + // under-count never leaks existence. + let repos = state + .db + .anonymously_listable_repo_count_cached(STATS_REPO_COUNT_TTL) + .await + .unwrap_or(0); let agents = state.db.count_agents().await.unwrap_or(0); let pushes = state.db.count_pushes().await.unwrap_or(0); Json(json!({ diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index a2b5fae8..4cc3ff46 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -7996,6 +7996,77 @@ mod tests { ); } + /// A cold-cache DB failure must render as 0, never as an over-count, so the + /// endpoint cannot leak withheld repos while degraded. + #[sqlx::test] + async fn stats_repos_count_fails_closed_on_db_error_with_cold_cache(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&seed_repo( + "did:key:zSTATSFAILAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "pub-repo", + )) + .await + .expect("seed public"); + state.db.pool().close().await; + assert_eq!( + stats_repos_count(state).await, + 0, + "a failed count must fail closed to 0" + ); + } + + /// A warm hit inside the TTL does not touch Postgres, so it survives an + /// outage with the last successful count. + #[sqlx::test] + async fn stats_repos_count_serves_warm_cache_during_db_outage(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&seed_repo( + "did:key:zSTATSWARMAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + "pub-repo", + )) + .await + .expect("seed public"); + assert_eq!( + stats_repos_count(state.clone()).await, + 1, + "the first count primes the cache" + ); + state.db.pool().close().await; + assert_eq!( + stats_repos_count(state).await, + 1, + "inside the TTL the cached count is served without a database refresh" + ); + } + + /// The anonymous stats handler must take its repo count from the cached + /// aggregate. Loading the inventory and every rule per request produces the + /// same number, so only a source check can see that regression. + #[test] + fn stats_handler_uses_cached_count_only() { + let src = include_str!("server.rs"); + let start = src + .find("pub(crate) async fn stats(") + .expect("stats handler present"); + let body = &src[start..]; + let end = body.find("\n}\n").expect("end of stats handler"); + let body = &body[..end]; + assert!( + body.contains("anonymously_listable_repo_count_cached"), + "stats must use the cached anonymous count" + ); + for forbidden in ["list_all_repos_deduped", "list_visibility_rules_for_repos"] { + assert!( + !body.contains(forbidden), + "stats must not call {forbidden}: it loads the whole inventory per request" + ); + } + } + // ---- #110: GET /ipfs/{cid} per-caller visibility gate ---- /// Seed a SHA-256 source repo (public/a.txt + secret/b.txt), bare-clone it