diff --git a/crates/twigpine-node/src/api/events.rs b/crates/twigpine-node/src/api/events.rs index 3c00eb491..4e619d6a7 100644 --- a/crates/twigpine-node/src/api/events.rs +++ b/crates/twigpine-node/src/api/events.rs @@ -43,7 +43,7 @@ pub(crate) async fn collect_visible_ref_updates( caller: Option<&str>, ) -> Result> { // 128 rows per DB round-trip. The page size is a parameter on the inner fn - // only so tests can force multi-page offset paging over a small dataset. + // only so tests can force a multi-page keyset walk over a small dataset. collect_visible_ref_updates_inner(db, repo, limit, caller, 128).await } @@ -85,7 +85,7 @@ async fn collect_visible_ref_updates_inner( // force an unbounded scan. The cap only fails safe (may return fewer). let max_scan = bounded_limit.max(2_048); let mut scanned: i64 = 0; - // Keyset cursor: the (timestamp, id) of the last row fetched so far. Paging + // Keyset cursor: the (received_at, id) of the last row fetched so far. Paging // by this instead of OFFSET keeps one multi-page scan stable when // received_ref_updates is written concurrently (a newer row sorts above the // window and cannot shift it, so no page duplicates or skips a row). It is @@ -107,7 +107,7 @@ async fn collect_visible_ref_updates_inner( // Advance the cursor to the last row of this page BEFORE the filter loop // consumes `rows`. if let Some(last) = rows.last() { - after = Some((last.timestamp.clone(), last.id.clone())); + after = Some((last.received_at.clone(), last.id.clone())); } for u in rows { // Quarantine denies unconditionally, before the visibility gate, so @@ -324,12 +324,18 @@ pub async fn list_repo_events( let mut all_events: Vec = cert_events; all_events.extend(gossip_events); - // Sort by timestamp descending - all_events.sort_by(|a, b| { - let ts_a = a.get("timestamp").and_then(|v| v.as_str()).unwrap_or(""); - let ts_b = b.get("timestamp").and_then(|v| v.as_str()).unwrap_or(""); - ts_b.cmp(ts_a) - }); + // Sort on server-stamped time descending. A gossip row's `timestamp` is + // peer-supplied even when well formed, so its server-stamped `received_at` + // is the ordering key; a local cert has no receipt column, but its + // `timestamp` is this node's own `issued_at`. + fn sort_ts(event: &serde_json::Value) -> &str { + event + .get("received_at") + .and_then(|v| v.as_str()) + .or_else(|| event.get("timestamp").and_then(|v| v.as_str())) + .unwrap_or("") + } + all_events.sort_by(|a, b| sort_ts(b).cmp(sort_ts(a))); // Apply limit all_events.truncate(limit as usize); @@ -997,7 +1003,7 @@ mod ref_updates_feed_tests { // Scenario 8b — the collector's repo-filtered path across a page boundary: // repo=Some AND a keyset continuation (after=Some) in one collect, exercising - // the four-bind `WHERE repo=$1 AND (timestamp,id)<($2,$3)` query end to end + // the four-bind `WHERE repo=$1 AND (received_at,id)<($2,$3)` query end to end // through the collector, not just the DB primitive. #[sqlx::test] async fn collect_visible_repo_filtered_pages_across_boundary(pool: PgPool) { @@ -1566,6 +1572,43 @@ mod ref_updates_feed_tests { ); } + #[sqlx::test] + async fn repo_events_order_gossip_by_received_at_not_wire_timestamp(pool: PgPool) { + let state = test_state(pool).await; + state + .db + .create_repo(&repo("pub", OWNER, "openrepo", true)) + .await + .unwrap(); + + let mut pinned = ref_row("pinned", "z6MkOwner/openrepo"); + pinned.timestamp = "2030-01-01T00:00:00Z".into(); + pinned.received_at = "2026-07-01T10:00:01Z".into(); + let mut recent = ref_row("recent", "z6MkOwner/openrepo"); + recent.timestamp = "2020-01-01T00:00:00Z".into(); + recent.received_at = "2026-07-01T10:00:02Z".into(); + state.db.insert_ref_update(&pinned).await.unwrap(); + state.db.insert_ref_update(&recent).await.unwrap(); + + let resp = repo_events_router(state) + .oneshot(anon_repo_events("z6MkOwner", "openrepo")) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = body_json(resp).await; + let ids: Vec<&str> = body["events"] + .as_array() + .expect("events array") + .iter() + .filter_map(|e| e["id"].as_str()) + .collect(); + assert_eq!( + ids, + vec!["recent", "pinned"], + "server receipt order must beat the attacker-chosen wire timestamps" + ); + } + // An oversized limit is clamped at this handler (parity with the global feed). #[sqlx::test] async fn repo_events_oversized_limit_clamped(pool: PgPool) { diff --git a/crates/twigpine-node/src/api/peers.rs b/crates/twigpine-node/src/api/peers.rs index 5939677dc..7eb123646 100644 --- a/crates/twigpine-node/src/api/peers.rs +++ b/crates/twigpine-node/src/api/peers.rs @@ -495,13 +495,50 @@ pub async fn notify_sync( auth: Option>, Json(req): Json, ) -> Result> { + let unsigned = auth.is_none(); if let Some(Extension(auth)) = auth { if auth.0 != req.node_did { return Err(AppError::BadRequest( "Signature keyid must match notification node_did".into(), )); } - } else { + } + + // Validate every peer-supplied stored field, including the repo slug whose + // traversal shape is the #272 guard, before the peer lookup and + // before either write. The effective row values are what get validated: + // omitted legacy provenance stays empty, while an omitted timestamp is the + // server-stamped fallback the row will actually carry. An explicitly empty + // optional string is malformed input, not legacy omission. + for (field, value) in [ + ("pusher_did", req.pusher_did.as_deref()), + ("old_sha", req.old_sha.as_deref()), + ] { + if matches!(value, Some("")) { + return Err(AppError::BadRequest(format!( + "{field} must not be empty when present" + ))); + } + } + let now = chrono::Utc::now().to_rfc3339(); + let effective_timestamp = req.timestamp.as_deref().unwrap_or(now.as_str()); + let wire = crate::db::RefUpdateTransportFields { + repo: &req.repo, + node_did: &req.node_did, + pusher_did: req.pusher_did.as_deref().unwrap_or(""), + owner_did: req.owner_did.as_deref(), + ref_name: &req.ref_name, + old_sha: req.old_sha.as_deref().unwrap_or(""), + new_sha: &req.new_sha, + timestamp: effective_timestamp, + cert_id: req.cert_id.as_deref(), + lag_origin: req.lag_origin.as_deref(), + cid: None, + }; + if let Err(e) = crate::db::validate_ref_update_transport_fields(&wire) { + return Err(AppError::BadRequest(e)); + } + if unsigned { tracing::warn!( did = %req.node_did, "accepted unsigned sync notify; set TWIGPINE_REQUIRE_SIGNED_PEER_WRITES=true after all peers upgrade" @@ -518,14 +555,6 @@ pub async fn notify_sync( ))); } - // #272: the slug reaches a PathBuf::join in the sync worker, where an extra - // 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}"))); - } - state .db .enqueue_sync( @@ -541,7 +570,6 @@ pub async fn notify_sync( // Mirror the gossipsub-receive handler: insert the same record we'd // get from the libp2p path, so /api/v1/events/ref-updates reflects // pushes that arrive over either transport. - let now = chrono::Utc::now().to_rfc3339(); let update = crate::db::ReceivedRefUpdate { id: uuid::Uuid::new_v4().to_string(), node_did: req.node_did.clone(), @@ -551,7 +579,7 @@ pub async fn notify_sync( ref_name: req.ref_name.clone(), old_sha: req.old_sha.clone().unwrap_or_default(), new_sha: req.new_sha.clone(), - timestamp: req.timestamp.clone().unwrap_or_else(|| now.clone()), + timestamp: effective_timestamp.to_string(), cert_id: req.cert_id.clone(), received_at: now, from_peer: format!("http:{}", req.node_did), @@ -1599,9 +1627,11 @@ mod tests { } #[sqlx::test] - async fn sync_notify_unknown_peer_wins_over_malformed_slug(pool: PgPool) { - // Ordering: the slug check sits after the peer gate, so an unknown peer - // still gets the unknown-peer message rather than a slug complaint. + async fn sync_notify_field_validation_precedes_the_peer_lookup(pool: PgPool) { + // Ordering: wire-field validation is deliberately cheaper than the peer + // database lookup, so malformed input is refused before the known-peer + // decision even when the DID is unknown. Both answers are the same 400 + // class; this test pins only which validation owns the reason. let state = test_state(pool).await; let stranger = Keypair::generate().did().to_string(); let router = crate::server::build_router(state); @@ -1619,8 +1649,167 @@ mod tests { .unwrap(); let body = String::from_utf8(bytes.to_vec()).unwrap(); assert!( - body.contains("unknown peer DID"), - "peer gate must still fire first: {body}" + body.contains("repo"), + "structural validation must fire before the peer lookup: {body}" + ); + } + + #[sqlx::test] + async fn sync_notify_rejects_malformed_or_oversized_ref_update_fields(pool: PgPool) { + let state = test_state(pool.clone()).await; + let peer_did = seed_peer(&state).await; + let router = crate::server::build_router(state); + let oversized_ref = format!("refs/heads/{}", "x".repeat(2_000)); + let oversized_did = format!("did:key:{}", "z".repeat(300)); + let oversized_cert = "c".repeat(129); + let cases: Vec<(&str, serde_json::Value)> = vec![ + ( + "oversized ref_name", + serde_json::json!({ "ref_name": oversized_ref }), + ), + ( + "malformed ref_name", + serde_json::json!({ "ref_name": "refs/heads/a..b" }), + ), + ( + "malformed new_sha", + serde_json::json!({ "new_sha": "not-a-sha" }), + ), + ("malformed old_sha", serde_json::json!({ "old_sha": "0" })), + ("empty old_sha", serde_json::json!({ "old_sha": "" })), + ("empty pusher_did", serde_json::json!({ "pusher_did": "" })), + ( + "oversized pusher_did", + serde_json::json!({ "pusher_did": oversized_did }), + ), + ( + "unsupported owner_did", + serde_json::json!({ "owner_did": "did:unsupported:x" }), + ), + ( + "malformed timestamp", + serde_json::json!({ "timestamp": "not-a-time" }), + ), + ( + "malformed lag_origin", + serde_json::json!({ "lag_origin": "not-a-time" }), + ), + ( + "oversized cert_id", + serde_json::json!({ "cert_id": oversized_cert }), + ), + ]; + + for (i, (label, patch)) in cases.iter().enumerate() { + let mut body = serde_json::json!({ + "repo": "z6Mkfoo/hello", + "ref_name": "refs/heads/main", + "new_sha": "0000000000000000000000000000000000000000", + "node_did": peer_did, + }); + let object = body.as_object_mut().expect("notify body object"); + for (key, value) in patch.as_object().expect("patch object") { + object.insert(key.clone(), value.clone()); + } + let ip = format!("198.51.100.{}:5000", 60 + i); + let resp = router + .clone() + .oneshot(unsigned_post("/api/v1/sync/notify", &body.to_string(), &ip)) + .await + .unwrap(); + assert_eq!( + resp.status(), + StatusCode::BAD_REQUEST, + "{label} must reject before either write" + ); + } + + 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, "malformed input must not enqueue sync work"); + assert_eq!(feed, 0, "malformed input must not seed the ref-update feed"); + } + + #[sqlx::test] + async fn sync_notify_rejects_a_padded_body_before_json_parse(pool: PgPool) { + let state = test_state(pool.clone()).await; + let peer_did = seed_peer(&state).await; + let body = serde_json::json!({ + "repo": "z6Mkfoo/hello", + "ref_name": "refs/heads/main", + "new_sha": "0000000000000000000000000000000000000000", + "node_did": peer_did, + "padding": "x".repeat(crate::db::MAX_REF_UPDATE_WIRE_BYTES), + }) + .to_string(); + assert!(body.len() > crate::db::MAX_REF_UPDATE_WIRE_BYTES); + let router = crate::server::build_router(state); + + let resp = router + .oneshot(unsigned_post( + "/api/v1/sync/notify", + &body, + "198.51.100.81:5000", + )) + .await + .unwrap(); + assert_eq!( + resp.status(), + StatusCode::PAYLOAD_TOO_LARGE, + "padded body must be refused before JSON parsing" + ); + 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, "a padded frame must not enqueue sync work"); + assert_eq!(feed, 0, "a padded frame must not seed the ref-update feed"); + } + + #[sqlx::test] + async fn sync_notify_accepts_sha256_object_ids_and_omitted_legacy_fields(pool: PgPool) { + let state = test_state(pool).await; + let db = state.db.clone(); + let peer_did = seed_peer(&state).await; + let body = serde_json::json!({ + "repo": "z6Mkfoo/sha256repo", + "ref_name": "refs/heads/main", + "new_sha": "a".repeat(64), + "node_did": peer_did, + }) + .to_string(); + let router = crate::server::build_router(state); + let resp = router + .oneshot(unsigned_post( + "/api/v1/sync/notify", + &body, + "198.51.100.80:5000", + )) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let queued = db.dequeue_pending_syncs(10).await.unwrap(); + assert_eq!(queued.len(), 1, "the sha256 object id must queue"); + let feed = db + .list_ref_updates_keyset(Some("z6Mkfoo/sha256repo"), 10, None) + .await + .unwrap(); + assert_eq!(feed.len(), 1); + assert_eq!(feed[0].new_sha.len(), 64); + assert_eq!(feed[0].old_sha, "", "omitted legacy old_sha stays empty"); + assert_eq!( + feed[0].pusher_did, "", + "omitted legacy pusher_did stays empty" ); } diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index 42e25819d..b2651a73e 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -8,6 +8,8 @@ use sqlx::{postgres::PgPoolOptions, PgPool, Row}; use tracing::{info, warn}; use uuid::Uuid; +use twigpine_core::cid::is_hex_oid; + use crate::webhook_secret::WebhookSecret; /// A migration version this build defines is already recorded in the database @@ -52,6 +54,19 @@ pub(crate) const MAX_VISIBLE_REPO_PAGE_SIZE: usize = 200; /// cursor an order of magnitude under the parse limit. pub(crate) const MAX_REPO_NAME_LEN: usize = 100; +/// Wire/persistence bounds for peer-supplied ref-update fields. These are +/// byte bounds, not character counts: the amplification being bounded is the +/// row size a peer can make this node store and later serialize. +const MAX_REF_UPDATE_REF_NAME_LEN: usize = 1024; +const MAX_REF_UPDATE_DID_LEN: usize = 256; +const MAX_REF_UPDATE_TIMESTAMP_LEN: usize = 64; +const MAX_REF_UPDATE_CERT_ID_LEN: usize = 128; +const MAX_REF_UPDATE_CID_LEN: usize = 128; +/// Ceiling for one encoded ref-update notification. Every legitimate field +/// sums to only a few KiB; this leaves generous JSON overhead without letting +/// padding force multi-megabyte parse and signature-verification work. +pub(crate) const MAX_REF_UPDATE_WIRE_BYTES: usize = 16 * 1024; + /// Maximum agent tasks returned per query. Shared by the GraphQL `tasks` /// complexity meter and the resolver clamp so they can't drift. pub(crate) const MAX_VISIBLE_TASK_PAGE_SIZE: i64 = 200; @@ -867,6 +882,232 @@ pub struct ReceivedRefUpdate { pub owner_did: Option, } +/// The peer-supplied fields one ref-update notification carries before either +/// transport writes anything. References rather than clones: validation runs +/// before storage precisely so an oversized field never gets copied into a row. +#[derive(Debug, Clone, Copy)] +pub(crate) struct RefUpdateTransportFields<'a> { + pub repo: &'a str, + pub node_did: &'a str, + pub pusher_did: &'a str, + pub owner_did: Option<&'a str>, + pub ref_name: &'a str, + pub old_sha: &'a str, + pub new_sha: &'a str, + pub timestamp: &'a str, + pub cert_id: Option<&'a str>, + pub lag_origin: Option<&'a str>, + pub cid: Option<&'a str>, +} + +fn validate_sha(field: &str, value: &str, allow_empty: bool) -> Result<(), String> { + if value.is_empty() && allow_empty { + return Ok(()); + } + if is_hex_oid(value) { + Ok(()) + } else { + Err(format!( + "{field} must be a 40- or 64-character hexadecimal object id" + )) + } +} + +fn validate_rfc3339(field: &str, value: &str) -> Result<(), String> { + if value.len() > MAX_REF_UPDATE_TIMESTAMP_LEN { + return Err(format!( + "{field} exceeds {MAX_REF_UPDATE_TIMESTAMP_LEN} bytes" + )); + } + DateTime::parse_from_rfc3339(value) + .map(|_| ()) + .map_err(|_| format!("{field} must be an RFC 3339 timestamp")) +} + +fn validate_did_shape(field: &str, value: &str, allow_empty: bool) -> Result<(), String> { + if value.is_empty() { + return if allow_empty { + Ok(()) + } else { + Err(format!("{field} must not be empty")) + }; + } + if value.len() > MAX_REF_UPDATE_DID_LEN { + return Err(format!("{field} exceeds {MAX_REF_UPDATE_DID_LEN} bytes")); + } + let mut parts = value.splitn(3, ':'); + let scheme = parts.next().unwrap_or_default(); + let method = parts.next().unwrap_or_default(); + let method_id = parts.next().unwrap_or_default(); + if scheme != "did" || method_id.is_empty() { + return Err(format!("{field} must be a DID")); + } + if !matches!(method, "key" | "web" | "gitlawb") { + return Err(format!("{field} uses an unsupported DID method")); + } + // DID Core method-specific-id: colon-separated portions of idchars, with + // at least one final idchar. `%` is not itself an idchar; it is legal only + // as the introducer of a two-hex-digit percent escape. + let bytes = method_id.as_bytes(); + let mut i = 0; + let mut ends_in_idchar = false; + while i < bytes.len() { + match bytes[i] { + b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'.' | b'-' | b'_' => { + ends_in_idchar = true; + i += 1; + } + b':' => { + ends_in_idchar = false; + i += 1; + } + b'%' if i + 2 < bytes.len() + && bytes[i + 1].is_ascii_hexdigit() + && bytes[i + 2].is_ascii_hexdigit() => + { + ends_in_idchar = true; + i += 3; + } + _ => return Err(format!("{field} contains a non-DID character")), + } + } + if !ends_in_idchar { + return Err(format!("{field} must end in a DID id character")); + } + Ok(()) +} + +/// Whether `ref_name` is a full git ref under `refs/` and follows the rules of +/// `git check-ref-format`. Unicode scalar values above ASCII remain allowed, +/// matching git; ASCII control bytes, ASCII space, and git's punctuation +/// exclusions do not. The byte cap is the amplification bound git itself does +/// not provide. +fn validate_ref_name(ref_name: &str) -> Result<(), String> { + if ref_name.is_empty() { + return Err("ref_name must not be empty".to_string()); + } + if ref_name.len() > MAX_REF_UPDATE_REF_NAME_LEN { + return Err(format!( + "ref_name exceeds {MAX_REF_UPDATE_REF_NAME_LEN} bytes" + )); + } + if !ref_name.starts_with("refs/") { + return Err("ref_name must be a full ref under refs/".to_string()); + } + if ref_name == "@" + || ref_name.contains("@{") + || ref_name.contains("..") + || ref_name.starts_with('/') + || ref_name.ends_with('/') + || ref_name.ends_with('.') + || ref_name.contains("//") + { + return Err("ref_name is not a valid git ref".to_string()); + } + for ch in ref_name.chars() { + let ascii_control = ch.is_ascii_control(); + if ascii_control || ch == ' ' || matches!(ch, '~' | '^' | ':' | '?' | '*' | '[' | '\\') { + return Err("ref_name contains a character git refuses".to_string()); + } + } + for component in ref_name.split('/') { + if component.is_empty() || component.starts_with('.') || component.ends_with(".lock") { + return Err("ref_name contains an invalid git ref component".to_string()); + } + } + Ok(()) +} + +fn validate_optional_capped(field: &str, value: Option<&str>, cap: usize) -> Result<(), String> { + if let Some(value) = value { + if value.is_empty() { + return Err(format!("{field} must not be empty when present")); + } + if value.len() > cap { + return Err(format!("{field} exceeds {cap} bytes")); + } + } + Ok(()) +} + +fn validate_stored_ref_update_fields(fields: &RefUpdateTransportFields<'_>) -> Result<(), String> { + crate::git::repo_store::validate_repo_slug(fields.repo) + .map_err(|e| format!("invalid repo field: {e}"))?; + validate_did_shape("node_did", fields.node_did, false)?; + // Empty is the legacy HTTP omission sentinel for pusher_did/old_sha, not a + // peer-supplied DID or object id. Present values must still be well formed. + validate_did_shape("pusher_did", fields.pusher_did, true)?; + if let Some(owner) = fields.owner_did { + validate_did_shape("owner_did", owner, false)?; + } + validate_ref_name(fields.ref_name)?; + validate_sha("old_sha", fields.old_sha, true)?; + validate_sha("new_sha", fields.new_sha, false)?; + validate_rfc3339("timestamp", fields.timestamp)?; + validate_optional_capped("cert_id", fields.cert_id, MAX_REF_UPDATE_CERT_ID_LEN)?; + Ok(()) +} + +/// Validate the wire fields before either transport pays for authentication, +/// database work, or a write. `lag_origin` and `cid` are included here because +/// they do not land in `received_ref_updates`; they land in `sync_queue`, and +/// leaving them free-form would preserve the same oversized-storage bypass. +pub(crate) fn validate_ref_update_transport_fields( + fields: &RefUpdateTransportFields<'_>, +) -> Result<(), String> { + validate_stored_ref_update_fields(fields)?; + if let Some(lag_origin) = fields.lag_origin { + validate_rfc3339("lag_origin", lag_origin)?; + } + validate_optional_capped("cid", fields.cid, MAX_REF_UPDATE_CID_LEN)?; + Ok(()) +} + +/// Defense in depth at the row insert. Every transport is expected to validate +/// before side effects; this second check is what keeps a future caller from +/// bypassing that boundary and persisting an oversized or malformed row. +fn validate_received_ref_update(update: &ReceivedRefUpdate) -> Result<(), String> { + let fields = RefUpdateTransportFields { + repo: &update.repo, + node_did: &update.node_did, + pusher_did: &update.pusher_did, + owner_did: update.owner_did.as_deref(), + ref_name: &update.ref_name, + old_sha: &update.old_sha, + new_sha: &update.new_sha, + timestamp: &update.timestamp, + cert_id: update.cert_id.as_deref(), + lag_origin: None, + cid: None, + }; + validate_stored_ref_update_fields(&fields)?; + validate_rfc3339("received_at", &update.received_at)?; + Ok(()) +} + +/// Defense in depth for the queue half of the same ingest. The row feed and +/// the queue are separate writes, so validating only `insert_ref_update` would +/// leave a future caller able to store the same attacker-controlled bytes here. +fn validate_sync_queue_write( + repo: &str, + node_did: &str, + ref_name: &str, + new_sha: &str, + cid: Option<&str>, + origin_timestamp: Option<&str>, +) -> Result<(), String> { + crate::git::repo_store::validate_repo_slug(repo) + .map_err(|e| format!("invalid repo field: {e}"))?; + validate_did_shape("node_did", node_did, false)?; + validate_ref_name(ref_name)?; + validate_sha("new_sha", new_sha, false)?; + if let Some(origin) = origin_timestamp { + validate_rfc3339("origin_timestamp", origin)?; + } + validate_optional_capped("cid", cid, MAX_REF_UPDATE_CID_LEN)?; + Ok(()) +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BountyRecord { pub id: String, @@ -2915,6 +3156,48 @@ const MIGRATIONS: &[Migration] = &[ AND repos.origin_node_did IS NULL"#, ], }, + Migration { + version: 55, + name: "ref_updates_received_at_keyset", + stmts: &[ + // Rows written before ingest validation do not become harmless at + // upgrade. Delete the rows whose byte widths violate the storage + // contract; exact small malformed rows are bounded and no longer + // control ordering, while oversized rows are the durable + // amplification this migration must retire. The legacy empty + // pusher_did and old_sha sentinels are inside these bounds. + "DELETE FROM received_ref_updates + WHERE octet_length(repo) > 356 + OR octet_length(node_did) > 256 + OR octet_length(pusher_did) > 256 + OR COALESCE(octet_length(owner_did), 0) > 256 + OR octet_length(ref_name) > 1024 + OR octet_length(old_sha) > 64 + OR octet_length(new_sha) > 64 + OR octet_length(timestamp) > 64 + OR COALESCE(octet_length(cert_id), 0) > 128 + OR octet_length(received_at) > 64", + "DELETE FROM sync_queue + WHERE octet_length(repo) > 356 + OR octet_length(node_did) > 256 + OR octet_length(ref_name) > 1024 + OR octet_length(new_sha) > 64 + OR COALESCE(octet_length(cid), 0) > 128 + OR COALESCE(octet_length(origin_timestamp), 0) > 64", + // Feed pagination orders on the server-stamped receipt column, not + // the event's self-asserted timestamp. These composite indexes are + // the row-value keyset orders the unfiltered and repo-filtered + // collectors walk. + "CREATE INDEX IF NOT EXISTS idx_ref_updates_received_keyset ON received_ref_updates(received_at DESC, id DESC)", + "CREATE INDEX IF NOT EXISTS idx_ref_updates_repo_received_keyset ON received_ref_updates(repo, received_at DESC, id DESC)", + // No read orders on the attacker-supplied event timestamp any + // longer; keeping the index would tax every write for a scan shape + // the feed deliberately no longer uses. The composite repo keyset + // index also covers the old repo-only equality lookups. + "DROP INDEX IF EXISTS idx_ref_updates_ts", + "DROP INDEX IF EXISTS idx_ref_updates_repo", + ], + }, ]; // ── HTTP-signature replay ledger ────────────────────────────────────────────── @@ -4743,6 +5026,8 @@ impl Db { cid: Option<&str>, origin_timestamp: Option<&str>, ) -> Result<()> { + validate_sync_queue_write(repo, node_did, ref_name, new_sha, cid, origin_timestamp) + .map_err(|e| anyhow::anyhow!(e))?; // `sync_queue` is slug-scoped and cascaded by `delete_repo_by_id`; take the // shared advisory lock on the same normalized slug so an enqueue cannot // interleave with the purge's sibling-check-then-cascade (same shape and @@ -10003,6 +10288,7 @@ fn row_to_repo_push_event(r: sqlx::postgres::PgRow) -> RepoPushEvent { impl Db { pub async fn insert_ref_update(&self, update: &ReceivedRefUpdate) -> Result<()> { + validate_received_ref_update(update).map_err(|e| anyhow::anyhow!(e))?; // `received_ref_updates` is slug-scoped and cascaded by `delete_repo_by_id`; // take the shared advisory lock on the same normalized slug so a peer-fed // insert cannot land inside the purge's sibling-check-then-cascade window @@ -10162,20 +10448,15 @@ impl Db { Ok(results) } - /// One page of ref updates (newest first), optionally scoped to one repo. - /// The `(timestamp DESC, id DESC)` order gives a stable tiebreak so offset - /// paging does not skip or duplicate rows when timestamps collide. Used by - /// the visibility-gated feed collector, which pages past dropped private rows - /// so a small limit still returns the latest visible events (#114). /// One page of ref updates for the visibility collector, ordered - /// `timestamp DESC, id DESC`, using a **keyset** cursor rather than + /// `received_at DESC, id DESC`, using a **keyset** cursor rather than /// `LIMIT/OFFSET`. /// - /// `after` is the `(timestamp, id)` of the last row of the previous page; + /// `after` is the `(received_at, id)` of the last row of the previous page; /// the next page reads rows strictly older than it via the row-value - /// predicate `(timestamp, id) < (after_ts, after_id)`, which matches the + /// predicate `(received_at, id) < (after_ts, after_id)`, which matches the /// `ORDER BY` exactly (same id tie-break). Because a concurrently inserted - /// row is newer (larger `timestamp`) and so sorts to the front, it lands + /// row is newer (larger `received_at`) and so sorts to the front, it lands /// *above* the window we are paging through and cannot shift it. That keeps /// a single multi-page scan free of the duplicate/skip that OFFSET paging /// suffers when `received_ref_updates` is written between page reads. @@ -10198,7 +10479,7 @@ impl Db { if after.is_some() { let (a, b) = (n + 1, n + 2); n += 2; - conds.push(format!("(timestamp, id) < (${a}, ${b})")); + conds.push(format!("(received_at, id) < (${a}, ${b})")); } let where_clause = if conds.is_empty() { String::new() @@ -10207,7 +10488,7 @@ impl Db { }; let sql = format!( "SELECT {COLS} FROM received_ref_updates{where_clause} \ - ORDER BY timestamp DESC, id DESC LIMIT ${}", + ORDER BY received_at DESC, id DESC LIMIT ${}", n + 1 ); @@ -14325,6 +14606,183 @@ mod migration_tests { db.migrate().await.unwrap(); } + #[sqlx::test] + async fn migration_v55_creates_ref_update_received_at_keyset_indexes(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + assert_ref_update_v55_index_shape(&db.pool).await; + } + + /// The fresh-database assertion above does not exercise the upgrade path: + /// v55 must also replace the pre-keyset timestamp ordering on a node that + /// already carries the old index. Recreate that shape, roll the migration + /// record back, and apply v55 again. + #[sqlx::test] + async fn migration_v55_replaces_timestamp_ordering_on_upgrade(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + for index in [ + "idx_ref_updates_received_keyset", + "idx_ref_updates_repo_received_keyset", + ] { + sqlx::query(&format!("DROP INDEX IF EXISTS {index}")) + .execute(&db.pool) + .await + .unwrap(); + } + sqlx::query( + "CREATE INDEX IF NOT EXISTS idx_ref_updates_ts ON received_ref_updates(timestamp DESC)", + ) + .execute(&db.pool) + .await + .unwrap(); + sqlx::query("DELETE FROM schema_migrations WHERE version = 55") + .execute(&db.pool) + .await + .unwrap(); + + db.migrate().await.unwrap(); + + assert_ref_update_v55_index_shape(&db.pool).await; + } + + /// Rows already present when a node upgrades must not carry the pre-fix + /// byte amplification forward. Seed raw rows because the validating insert + /// choke point would correctly refuse the bad ones now. + #[sqlx::test] + async fn migration_v55_deletes_oversized_preexisting_ref_update_rows(pool: sqlx::PgPool) { + let db = super::Db::for_testing(pool); + db.migrate().await.unwrap(); + + async fn raw_ref_update(db: &super::Db, id: &str, ref_name: &str, cert_id: Option) { + 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(id) + .bind("did:key:z6MkgAnvkP45uNxwCKeNdt6wrYkEjpYX4f7Nrd8MQqFL8Fbn") + .bind("") + .bind("z6Mkfoo/hello") + .bind(ref_name) + .bind("") + .bind("a".repeat(64)) + .bind("2026-07-01T12:00:00Z") + .bind(cert_id) + .bind("2026-07-01T12:00:01Z") + .bind("12D3KooWPeer") + .bind::>(None) + .execute(db.pool()) + .await + .unwrap(); + } + raw_ref_update(&db, "valid", "refs/heads/main", None).await; + raw_ref_update(&db, "oversized-ref", &"r".repeat(1025), None).await; + raw_ref_update( + &db, + "oversized-cert", + "refs/heads/main", + Some("c".repeat(129)), + ) + .await; + for (id, cid) in [ + ("valid-queue", None), + ("oversized-queue", Some("c".repeat(129))), + ] { + sqlx::query( + "INSERT INTO sync_queue + (id, repo, node_did, ref_name, new_sha, cid, origin_timestamp, status, enqueued_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,'pending',$8)", + ) + .bind(id) + .bind("z6Mkfoo/hello") + .bind("did:key:z6MkgAnvkP45uNxwCKeNdt6wrYkEjpYX4f7Nrd8MQqFL8Fbn") + .bind("refs/heads/main") + .bind("a".repeat(64)) + .bind(cid) + .bind(Some("2026-07-01T12:00:00Z")) + .bind("2026-07-01T12:00:01Z") + .execute(db.pool()) + .await + .unwrap(); + } + + sqlx::query("DELETE FROM schema_migrations WHERE version = 55") + .execute(db.pool()) + .await + .unwrap(); + db.migrate().await.unwrap(); + + let ref_ids: Vec = + sqlx::query_scalar("SELECT id FROM received_ref_updates ORDER BY id") + .fetch_all(db.pool()) + .await + .unwrap(); + assert_eq!( + ref_ids, + vec!["valid".to_string()], + "oversized pre-upgrade rows must be deleted while the bounded legacy row survives" + ); + let queue_ids: Vec = sqlx::query_scalar("SELECT id FROM sync_queue ORDER BY id") + .fetch_all(db.pool()) + .await + .unwrap(); + assert_eq!( + queue_ids, + vec!["valid-queue".to_string()], + "oversized pre-upgrade queue rows must be deleted while bounded work survives" + ); + } + + async fn assert_ref_update_v55_index_shape(pool: &sqlx::PgPool) { + for index in [ + "idx_ref_updates_received_keyset", + "idx_ref_updates_repo_received_keyset", + ] { + let exists = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS( + SELECT 1 FROM pg_indexes + WHERE tablename = 'received_ref_updates' + AND indexname = $1 + )", + ) + .bind(index) + .fetch_one(pool) + .await + .unwrap(); + assert!(exists, "{index} must exist after migration v55"); + } + let timestamp_index_exists = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS( + SELECT 1 FROM pg_indexes + WHERE tablename = 'received_ref_updates' + AND indexname = 'idx_ref_updates_ts' + )", + ) + .fetch_one(pool) + .await + .unwrap(); + assert!( + !timestamp_index_exists, + "migration v55 must retire the attacker-controlled timestamp ordering" + ); + let repo_index_exists = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS( + SELECT 1 FROM pg_indexes + WHERE tablename = 'received_ref_updates' + AND indexname = 'idx_ref_updates_repo' + )", + ) + .fetch_one(pool) + .await + .unwrap(); + assert!( + !repo_index_exists, + "migration v55 must retire the redundant repo-only index" + ); + } + #[sqlx::test] async fn dequeue_stamps_attempted_at_on_every_row_it_hands_out(pool: sqlx::PgPool) { // The stamp is what stops a deferred row from holding the window, and @@ -18355,6 +18813,230 @@ mod icaptcha_quarantine_tests { } } +#[cfg(test)] +mod ref_update_validation_tests { + use super::{ + validate_received_ref_update, validate_ref_name, validate_ref_update_transport_fields, Db, + ReceivedRefUpdate, RefUpdateTransportFields, + }; + use sqlx::PgPool; + + fn valid_update() -> ReceivedRefUpdate { + ReceivedRefUpdate { + id: "r1".into(), + node_did: "did:key:zNode".into(), + pusher_did: "did:key:zPusher".into(), + repo: "zOwner/myrepo".into(), + ref_name: "refs/heads/main".into(), + old_sha: "0".repeat(40), + new_sha: "a".repeat(40), + timestamp: "2026-07-02T12:00:00Z".into(), + cert_id: None, + received_at: "2026-07-02T12:00:01Z".into(), + from_peer: "peer".into(), + owner_did: None, + } + } + + #[test] + fn ref_name_validation_matches_git_edges_and_bounds() { + let at_cap = format!("refs/heads/{}", "x".repeat(1013)); + assert_eq!(at_cap.len(), 1024); + assert!(validate_ref_name(&at_cap).is_ok()); + assert!(validate_ref_name("refs/heads/féat").is_ok()); + assert!(validate_ref_name("refs/heads/x./y").is_ok()); + assert!(validate_ref_name(&format!("refs/heads/{}", "x".repeat(1014))).is_err()); + + for bad in [ + "heads/main", + "refs/heads/a b", + "refs/heads/a..b", + "refs/heads/.x", + "refs/heads/x.lock", + "refs/heads/x.", + "refs/heads/x@{y", + "refs/heads//x", + "refs/heads/x/", + "refs/heads/a\\b", + "refs/heads/a*b", + "refs/heads/a?b", + "refs/heads/a[b", + "refs/heads/a:b", + "refs/heads/a^b", + "refs/heads/a~b", + ] { + assert!(validate_ref_name(bad).is_err(), "{bad:?} must reject"); + } + } + + #[test] + fn stored_ref_update_validation_accepts_valid_and_legacy_empty_fields() { + let valid = valid_update(); + assert!(validate_received_ref_update(&valid).is_ok()); + + let mut sha256_format = valid_update(); + sha256_format.old_sha = "0".repeat(64); + sha256_format.new_sha = "a".repeat(64); + assert!(validate_received_ref_update(&sha256_format).is_ok()); + + let mut escaped_did = valid_update(); + escaped_did.node_did = "did:key:z%41abc".into(); + assert!(validate_received_ref_update(&escaped_did).is_ok()); + + let mut legacy = valid_update(); + legacy.pusher_did.clear(); + legacy.old_sha.clear(); + assert!( + validate_received_ref_update(&legacy).is_ok(), + "omitted legacy HTTP provenance may remain empty because it is bounded" + ); + } + + #[test] + fn stored_ref_update_validation_rejects_malformed_or_oversized_fields() { + fn expect_invalid(edit: impl Fn(&mut ReceivedRefUpdate)) { + let mut update = valid_update(); + edit(&mut update); + assert!(validate_received_ref_update(&update).is_err()); + } + + expect_invalid(|u| u.repo = "../x".into()); + expect_invalid(|u| u.node_did = "not-a-did".into()); + expect_invalid(|u| u.pusher_did = format!("did:key:{}", "z".repeat(300))); + expect_invalid(|u| u.owner_did = Some("did:unsupported:x".into())); + expect_invalid(|u| u.ref_name = format!("refs/heads/{}", "x".repeat(2000))); + expect_invalid(|u| u.old_sha = "not-a-sha".into()); + expect_invalid(|u| u.new_sha = "z".repeat(40)); + expect_invalid(|u| u.node_did = "did:key:z%".into()); + expect_invalid(|u| u.node_did = "did:key:z%1".into()); + expect_invalid(|u| u.node_did = "did:key:z:".into()); + expect_invalid(|u| u.timestamp = "not-a-time".into()); + expect_invalid(|u| u.timestamp = format!("2026-07-02T12:00:00.{}Z", "1".repeat(80))); + expect_invalid(|u| u.cert_id = Some("c".repeat(129))); + expect_invalid(|u| u.received_at = "yesterday".into()); + } + + #[test] + fn transport_validation_covers_sync_queue_only_fields() { + let update = valid_update(); + let fields = RefUpdateTransportFields { + repo: &update.repo, + node_did: &update.node_did, + pusher_did: &update.pusher_did, + owner_did: update.owner_did.as_deref(), + ref_name: &update.ref_name, + old_sha: &update.old_sha, + new_sha: &update.new_sha, + timestamp: &update.timestamp, + cert_id: update.cert_id.as_deref(), + lag_origin: Some("2026-07-02T11:59:59Z"), + cid: Some("bafycid"), + }; + assert!(validate_ref_update_transport_fields(&fields).is_ok()); + + let mut bad_lag = fields; + bad_lag.lag_origin = Some("not-a-time"); + assert!(validate_ref_update_transport_fields(&bad_lag).is_err()); + + let mut bad_cid = fields; + let oversized_cid = "c".repeat(129); + bad_cid.cid = Some(&oversized_cid); + assert!(validate_ref_update_transport_fields(&bad_cid).is_err()); + } + + #[sqlx::test] + async fn insert_ref_update_is_a_validating_choke_point(pool: PgPool) { + let db = Db::for_testing(pool.clone()); + db.run_migrations().await.unwrap(); + db.insert_ref_update(&valid_update()).await.unwrap(); + + let mut bad = valid_update(); + bad.id = "oversized".into(); + bad.ref_name = format!("refs/heads/{}", "x".repeat(2000)); + assert!( + db.insert_ref_update(&bad).await.is_err(), + "oversized ref_name must reject" + ); + let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM received_ref_updates") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 1, "only the valid control row may land"); + } + + #[sqlx::test] + async fn enqueue_sync_is_a_validating_choke_point(pool: PgPool) { + let db = Db::for_testing(pool); + db.run_migrations().await.unwrap(); + assert!( + db.enqueue_sync( + "zOwner/myrepo", + "did:key:zNode", + "refs/heads/main", + &"a".repeat(40), + Some(&"c".repeat(129)), + None, + ) + .await + .is_err(), + "oversized cid must reject" + ); + assert!( + db.enqueue_sync( + "zOwner/myrepo", + "did:key:zNode", + "refs/heads/main", + &"a".repeat(40), + None, + Some("not-a-time"), + ) + .await + .is_err(), + "malformed origin timestamp must reject" + ); + assert!( + db.enqueue_sync( + "../x", + "did:key:zNode", + "refs/heads/main", + &"a".repeat(40), + None, + None, + ) + .await + .is_err(), + "traversal repo must reject" + ); + assert!( + db.enqueue_sync( + "zOwner/myrepo", + "did:key:zNode", + "refs/heads/a..b", + &"a".repeat(40), + None, + None, + ) + .await + .is_err(), + "malformed ref_name must reject" + ); + assert!( + db.enqueue_sync( + "zOwner/myrepo", + "did:key:zNode", + "refs/heads/main", + "not-a-sha", + None, + None, + ) + .await + .is_err(), + "malformed new_sha must reject" + ); + assert!(db.dequeue_pending_syncs(10).await.unwrap().is_empty()); + } +} + #[cfg(test)] mod ref_update_keyset_paging_tests { use super::{Db, ReceivedRefUpdate}; @@ -18367,8 +19049,8 @@ mod ref_update_keyset_paging_tests { pusher_did: "did:key:zP".into(), repo: "z6MkOwner/openrepo".into(), ref_name: "refs/heads/main".into(), - old_sha: "0".into(), - new_sha: "1".into(), + old_sha: "0".repeat(40), + new_sha: "1".repeat(40), timestamp: ts.into(), cert_id: None, received_at: ts.into(), @@ -18401,7 +19083,7 @@ mod ref_update_keyset_paging_tests { async move { sqlx::query_scalar::<_, String>( "SELECT id FROM received_ref_updates \ - ORDER BY timestamp DESC, id DESC LIMIT $1 OFFSET $2", + ORDER BY received_at DESC, id DESC LIMIT $1 OFFSET $2", ) .bind(limit) .bind(offset) @@ -18424,8 +19106,27 @@ mod ref_update_keyset_paging_tests { ); } - // The fix: keyset paging on (timestamp, id) reads strictly older rows each - // page, so a concurrent newer insert cannot duplicate or skip a row. + #[sqlx::test] + async fn keyset_order_follows_received_at_not_attacker_timestamp(pool: PgPool) { + let db = Db::for_testing(pool); + db.run_migrations().await.unwrap(); + + let mut older_receipt = rru("older-receipt", "2026-07-01T10:00:01+00:00"); + older_receipt.timestamp = "2026-07-01T12:00:00+00:00".into(); + let mut newer_receipt = rru("newer-receipt", "2026-07-01T10:00:02+00:00"); + newer_receipt.timestamp = "2026-07-01T09:00:00+00:00".into(); + db.insert_ref_update(&older_receipt).await.unwrap(); + db.insert_ref_update(&newer_receipt).await.unwrap(); + + let rows = db.list_ref_updates_keyset(None, 10, None).await.unwrap(); + let ids: Vec<&str> = rows.iter().map(|u| u.id.as_str()).collect(); + assert_eq!( + ids, + vec!["newer-receipt", "older-receipt"], + "feed ordering must follow server receipt order even when the wire timestamps invert it" + ); + } + #[sqlx::test] async fn keyset_paging_is_stable_under_concurrent_insert(pool: PgPool) { let db = Db::for_testing(pool); @@ -18436,7 +19137,7 @@ mod ref_update_keyset_paging_tests { let p1_ids: Vec = p1.iter().map(|u| u.id.clone()).collect(); assert_eq!(p1_ids, vec!["r4", "r3"], "keyset page 1"); let last = p1.last().unwrap(); - let cursor = (last.timestamp.clone(), last.id.clone()); + let cursor = (last.received_at.clone(), last.id.clone()); // concurrent insert of a newer row between page reads db.insert_ref_update(&rru("r5", "2026-07-01T10:00:09+00:00")) @@ -18476,8 +19177,8 @@ mod ref_update_keyset_repo_filtered_tests { pusher_did: "did:key:zP".into(), repo: repo.into(), ref_name: "refs/heads/main".into(), - old_sha: "0".into(), - new_sha: "1".into(), + old_sha: "0".repeat(40), + new_sha: "1".repeat(40), timestamp: ts.into(), cert_id: None, received_at: ts.into(), @@ -18486,10 +19187,6 @@ mod ref_update_keyset_repo_filtered_tests { } } - // Exercises the (Some(repo), Some(after)) keyset branch: a repo-filtered - // multi-page continuation that emits `WHERE repo=$1 AND (timestamp,id)<($2,$3)` - // with four binds. Also confirms the repo filter holds across pages, noise - // rows are excluded, and a concurrent insert does not duplicate or skip. #[sqlx::test] async fn keyset_repo_filtered_multipage_stable_under_concurrent_insert(pool: PgPool) { let db = Db::for_testing(pool); @@ -18534,7 +19231,7 @@ mod ref_update_keyset_repo_filtered_tests { "no noise rows on page 1" ); let last = p1.last().unwrap(); - let cursor = (last.timestamp.clone(), last.id.clone()); + let cursor = (last.received_at.clone(), last.id.clone()); // concurrent insert of a newer TARGET row between page reads db.insert_ref_update(&rru_repo("T4", "2026-07-01T10:00:06+00:00", target)) @@ -18583,8 +19280,8 @@ mod ref_update_keyset_same_timestamp_tests { pusher_did: "did:key:zP".into(), repo: "z6MkOwner/openrepo".into(), ref_name: "refs/heads/main".into(), - old_sha: "0".into(), - new_sha: "1".into(), + old_sha: "0".repeat(40), + new_sha: "1".repeat(40), timestamp: ts.into(), cert_id: None, received_at: ts.into(), @@ -18593,12 +19290,12 @@ mod ref_update_keyset_same_timestamp_tests { } } - // Load-bearing for the `id` half of the (timestamp, id) keyset cursor: all - // rows share ONE timestamp, so ordering and the page boundary fall entirely - // on `id DESC`. A timestamp-only cursor would return nothing for page 2 and - // silently skip b and a; the (timestamp, id) tie-break must advance instead. + // Load-bearing for the `id` half of the (received_at, id) keyset cursor: all + // rows share ONE receipt timestamp, so ordering and the page boundary fall + // entirely on `id DESC`. A cursor without the id half would return nothing + // for page 2 and silently skip b and a; the tie-break must advance instead. #[sqlx::test] - async fn keyset_advances_within_an_equal_timestamp_run(pool: PgPool) { + async fn keyset_advances_within_an_equal_received_at_run(pool: PgPool) { let db = Db::for_testing(pool); db.run_migrations().await.unwrap(); let ts = "2026-07-01T10:00:00+00:00"; @@ -18606,22 +19303,22 @@ mod ref_update_keyset_same_timestamp_tests { db.insert_ref_update(&row(id, ts)).await.unwrap(); } - // id DESC over equal timestamps: d, c, b, a + // id DESC over equal receipt timestamps: d, c, b, a let p1 = db.list_ref_updates_keyset(None, 2, None).await.unwrap(); let p1_ids: Vec = p1.iter().map(|u| u.id.clone()).collect(); assert_eq!(p1_ids, vec!["d", "c"], "page 1 by id DESC"); let last = p1.last().unwrap(); - // page boundary lands INSIDE the equal-timestamp group (cursor = (ts, "c")) + // page boundary lands INSIDE the equal-receipt group (cursor = (ts, "c")) let p2 = db - .list_ref_updates_keyset(None, 2, Some((last.timestamp.as_str(), last.id.as_str()))) + .list_ref_updates_keyset(None, 2, Some((last.received_at.as_str(), last.id.as_str()))) .await .unwrap(); let p2_ids: Vec = p2.iter().map(|u| u.id.clone()).collect(); assert_eq!( p2_ids, vec!["b", "a"], - "keyset must advance by id within an equal-timestamp run (a timestamp-only cursor would skip these)" + "keyset must advance by id within an equal-receipt run (a cursor without the id half would skip these)" ); let all: Vec = p1_ids.into_iter().chain(p2_ids).collect(); @@ -18629,7 +19326,7 @@ mod ref_update_keyset_same_timestamp_tests { assert_eq!( uniq.len(), 4, - "no dup or skip across a same-timestamp page boundary" + "no dup or skip across a same-receipt page boundary" ); } } @@ -19606,8 +20303,8 @@ mod ref_certificate_tests { "dup-feat-z", &r1, "refs/heads/feature", - "cccc", - "dddd", + &"c".repeat(40), + &"d".repeat(40), "2026-07-01T10:00:00Z" ); @@ -19624,8 +20321,8 @@ mod ref_certificate_tests { "dup-b-new", &r2, "refs/heads/main", - "eeee", - "ffff", + &"e".repeat(40), + &"f".repeat(40), "2026-07-02T10:00:00Z" ); @@ -19777,7 +20474,7 @@ mod ref_update_db_tests { "zOwner/myrepo", Some("did:key:zOwner"), "refs/heads/main", - "aaaa", + &"a".repeat(40), )) .await .unwrap(); @@ -19796,7 +20493,7 @@ mod ref_update_db_tests { "zOwner/myrepo", None, "refs/heads/main", - "bbbb", + &"b".repeat(40), )) .await .unwrap(); @@ -19814,7 +20511,7 @@ mod ref_update_db_tests { "alice/repo1", Some("did:key:zAlice"), "refs/heads/main", - "cccc", + &"c".repeat(40), )) .await .unwrap(); @@ -19823,7 +20520,7 @@ mod ref_update_db_tests { "bob/repo2", Some("did:key:zBob"), "refs/heads/feat", - "dddd", + &"d".repeat(40), )) .await .unwrap(); @@ -19859,7 +20556,7 @@ mod ref_update_db_tests { "ownerA/proj", Some("did:key:zA"), "refs/heads/main", - "eeee", + &"e".repeat(40), )) .await .unwrap(); @@ -19868,7 +20565,7 @@ mod ref_update_db_tests { "ownerB/proj", Some("did:web:host:zB"), "refs/heads/main", - "ffff", + &"f".repeat(40), )) .await .unwrap(); @@ -19892,14 +20589,14 @@ mod ref_update_db_tests { "repo/x", Some("did:key:zX"), "refs/heads/main", - "gggg", + &"f".repeat(40), ); db.insert_ref_update(&u).await.unwrap(); db.insert_ref_update(&u).await.unwrap(); let all = db.list_ref_updates_keyset(None, 100, None).await.unwrap(); assert_eq!(all.len(), 1); - assert_eq!(all[0].new_sha, "gggg"); + assert_eq!(all[0].new_sha, "f".repeat(40)); } } diff --git a/crates/twigpine-node/src/p2p/mod.rs b/crates/twigpine-node/src/p2p/mod.rs index 4475199fc..7cc1da191 100644 --- a/crates/twigpine-node/src/p2p/mod.rs +++ b/crates/twigpine-node/src/p2p/mod.rs @@ -500,6 +500,11 @@ fn verify_ref_update(event: &RefUpdateEvent) -> Result<(), String> { .as_deref() .ok_or_else(|| "event carries no signature".to_string())?; + // A 64-byte Ed25519 signature is exactly 86 unpadded base64url characters. + // Check that before allocating and decoding whatever length the wire sent. + if sig_b64.len() != 86 { + return Err("signature is not the base64url form of 64 bytes".to_string()); + } let sig_bytes: [u8; 64] = URL_SAFE_NO_PAD .decode(sig_b64) .map_err(|_| "signature is not valid base64url".to_string())? @@ -1170,6 +1175,13 @@ pub(crate) async fn ingest_ref_update( return IngestOutcome::SourceRateLimited; } + if data.len() > crate::db::MAX_REF_UPDATE_WIRE_BYTES { + return IngestOutcome::Rejected(format!( + "ref-update event exceeds {} encoded bytes", + crate::db::MAX_REF_UPDATE_WIRE_BYTES + )); + } + let event = match serde_json::from_slice::(data) { Ok(event) => event, Err(e) => return IngestOutcome::Rejected(format!("malformed ref-update event: {e}")), @@ -1228,19 +1240,32 @@ pub(crate) async fn ingest_ref_update( return IngestOutcome::Rejected(reason); } - // #272: the slug reaches a `PathBuf::join` in the sync worker, so it is - // rejected here, before the ref-update row and the queue row. - // - // It sits this high on purpose, above the signature verify and above the - // `peer_exists` round trip, not merely above the budgets. It depends on - // nothing but the parsed struct, so hoisting it costs nothing and removes - // the work entirely: a structurally invalid event now buys no Ed25519 - // verify and no database query. Placing it below either of those would buy - // the fairness property (a malformed event charges nobody) while leaving - // the cost in place, charged only to the pre-parse brake that `PeerId` - // rotation defeats. - if let Err(e) = crate::git::repo_store::validate_repo_slug(&event.repo) { - return IngestOutcome::Rejected(format!("invalid repo field: {e}")); + // Size and format validation, including the #272 slug guard, sits this high + // on purpose: above the signature verify, the `peer_exists` round trip, and + // every budget debit. It depends on nothing but the parsed struct, so a + // structurally invalid event buys no Ed25519 verify and no database query. + // Letting an oversized field reach either insert would make the parse the + // first half of durable storage amplification rather than a rejection. + // Empty pusher_did and old_sha stay admissible here for the same reason as + // on HTTP: pre-announcement publishers emitted them as bounded omission + // sentinels, and rejecting them would cut off replication from those peers + // during a rolling upgrade without reducing the storage amplification this + // guard exists to bound. + let wire = crate::db::RefUpdateTransportFields { + repo: &event.repo, + node_did: &event.node_did, + pusher_did: &event.pusher_did, + owner_did: event.owner_did.as_deref(), + ref_name: &event.ref_name, + old_sha: &event.old_sha, + new_sha: &event.new_sha, + timestamp: &event.timestamp, + cert_id: event.cert_id.as_deref(), + lag_origin: event.lag_origin.as_deref(), + cid: event.cid.as_deref(), + }; + if let Err(e) = crate::db::validate_ref_update_transport_fields(&wire) { + return IngestOutcome::Rejected(format!("invalid ref-update event fields: {e}")); } // Whether `node_did` was PROVEN by a signature on this event, as opposed to @@ -4468,6 +4493,8 @@ pub async fn start( mod tests { use super::*; + type RefUpdateMutationCase = (&'static str, fn(&mut RefUpdateEvent), &'static str); + fn identify_address(peer_id: PeerId, octet: u8, port: u16) -> Multiaddr { format!("/ip4/192.0.2.{octet}/udp/{port}/quic-v1") .parse::() @@ -7672,6 +7699,19 @@ mod tests { assert_eq!(received.node_did, keypair.did().to_string()); } + #[test] + fn an_oversized_signature_encoding_is_rejected_before_decode() { + let keypair = Keypair::generate(); + let mut event = event_for(&keypair); + sign_ref_update(&keypair, &mut event).unwrap(); + event.sig = Some("A".repeat(17_000)); + + assert_eq!( + verify_ref_update(&event).expect_err("an oversized sig must not decode"), + "signature is not the base64url form of 64 bytes" + ); + } + /// A cryptographically valid signature that does not bind the claimed /// identity. This is the RUSTSEC-2022-0009 shape: libp2p-core accepted a /// valid signature without checking it derived the claimed peer id, so the @@ -8182,6 +8222,229 @@ mod tests { assert_rejected_in_both_modes(&db, &pool, &bytes_of(&event), "traversal slug", None).await; } + /// Unknown JSON members are ignored by serde, so padding is not part of + /// the field validator's answer. The frame cap must reject it before the + /// parse; without that guard this otherwise valid signed event is accepted. + #[sqlx::test] + async fn an_oversized_frame_is_rejected_before_json_parse(pool: PgPool) { + let db = ingest_db(&pool).await; + let keypair = Keypair::generate(); + let mut event = event_for(&keypair); + sign_ref_update(&keypair, &mut event).unwrap(); + seed_peer(&pool, &event.node_did).await; + let mut value = serde_json::to_value(&event).unwrap(); + value["padding"] = serde_json::json!("x".repeat(crate::db::MAX_REF_UPDATE_WIRE_BYTES)); + let bytes = serde_json::to_vec(&value).unwrap(); + assert!(bytes.len() > crate::db::MAX_REF_UPDATE_WIRE_BYTES); + + assert_rejected_in_both_modes( + &db, + &pool, + &bytes, + "oversized frame", + Some(( + "ref-update event exceeds 16384 encoded bytes", + "the encoded-frame cap must own the rejection", + )), + ) + .await; + } + + /// Peer-controlled size and shape validation, before either durable sink. + /// Every witness is correctly signed and comes from a seeded peer so the + /// malformed field is the only rule that can reject it. + #[sqlx::test] + async fn malformed_or_oversized_fields_are_rejected_before_any_write(pool: PgPool) { + let db = ingest_db(&pool).await; + let cases: Vec = vec![ + ( + "oversized ref_name", + |e| { + e.ref_name = format!("refs/heads/{}", "x".repeat(2_000)); + }, + "invalid ref-update event fields: ref_name exceeds 1024 bytes", + ), + ( + "malformed ref_name", + |e| { + e.ref_name = "refs/heads/a..b".into(); + }, + "invalid ref-update event fields: ref_name is not a valid git ref", + ), + ( + "malformed new_sha", + |e| { + e.new_sha = "not-a-sha".into(); + }, + "invalid ref-update event fields: new_sha must be a 40- or 64-character hexadecimal object id", + ), + ( + "malformed old_sha", + |e| { + e.old_sha = "0".into(); + }, + "invalid ref-update event fields: old_sha must be a 40- or 64-character hexadecimal object id", + ), + ( + "oversized pusher_did", + |e| { + e.pusher_did = format!("did:key:{}", "z".repeat(300)); + }, + "invalid ref-update event fields: pusher_did exceeds 256 bytes", + ), + ( + "unsupported owner_did", + |e| { + e.owner_did = Some("did:unsupported:x".into()); + }, + "invalid ref-update event fields: owner_did uses an unsupported DID method", + ), + ( + "malformed timestamp", + |e| { + e.timestamp = "not-a-time".into(); + }, + "invalid ref-update event fields: timestamp must be an RFC 3339 timestamp", + ), + ( + "malformed lag_origin", + |e| { + e.lag_origin = Some("not-a-time".into()); + }, + "invalid ref-update event fields: lag_origin must be an RFC 3339 timestamp", + ), + ( + "oversized cert_id", + |e| { + e.cert_id = Some("c".repeat(129)); + }, + "invalid ref-update event fields: cert_id exceeds 128 bytes", + ), + ( + "oversized cid", + |e| { + e.cid = Some("c".repeat(129)); + }, + "invalid ref-update event fields: cid exceeds 128 bytes", + ), + ]; + + for (label, mutate, expected) in cases { + let keypair = Keypair::generate(); + let mut event = event_for(&keypair); + mutate(&mut event); + sign_ref_update(&keypair, &mut event).unwrap(); + seed_peer(&pool, &event.node_did).await; + assert_rejected_in_both_modes( + &db, + &pool, + &bytes_of(&event), + label, + Some((expected, "the wire-field guard must own the rejection")), + ) + .await; + } + } + + /// Older publishers emitted empty `pusher_did` and `old_sha` before those + /// fields carried values. Both are bounded omission sentinels rather than + /// amplification input, so a versionless unsigned event carrying them must + /// still replicate in rolling-upgrade mode. The JSON is written directly + /// rather than serialized from `RefUpdateEvent` so the wire shape really is + /// the pre-version one an un-upgraded publisher emits. + #[sqlx::test] + async fn an_unsigned_legacy_empty_pusher_and_old_sha_event_is_accepted(pool: PgPool) { + let db = ingest_db(&pool).await; + let keypair = Keypair::generate(); + let node_did = keypair.did().to_string(); + let legacy = serde_json::json!({ + "node_did": node_did, + "pusher_did": "", + "repo": "zOwner/myrepo", + "ref_name": "refs/heads/main", + "old_sha": "", + "new_sha": "a".repeat(40), + "timestamp": ingest_now().to_rfc3339(), + }); + seed_peer(&pool, &node_did).await; + + let outcome = ingest_with_fresh_limiter( + &db, + false, + true, + &serde_json::to_vec(&legacy).unwrap(), + &PeerId::random(), + ) + .await; + assert!( + matches!(outcome, IngestOutcome::UnsignedAdmitted), + "a legacy empty-identity event from a known peer must replicate, got {outcome:?}" + ); + let stored: (String, String) = + sqlx::query_as("SELECT pusher_did, old_sha FROM received_ref_updates") + .fetch_one(&pool) + .await + .expect("legacy ref-update row"); + assert_eq!(stored, (String::new(), String::new())); + assert_eq!( + count(&pool, "sync_queue").await, + 1, + "the legacy event must still enqueue replication" + ); + } + + #[sqlx::test] + async fn malformed_fields_are_rejected_before_signature_and_peer_lookup(pool: PgPool) { + let db = ingest_db(&pool).await; + let keypair = Keypair::generate(); + let mut event = event_for(&keypair); + event.ref_name = format!("refs/heads/{}", "x".repeat(2_000)); + sign_ref_update(&keypair, &mut event).unwrap(); + event.sig = Some("not-a-valid-signature".into()); + + reset_peer_exists_calls(); + let outcome = + ingest_with_fresh_limiter(&db, true, true, &bytes_of(&event), &PeerId::random()).await; + assert_eq!( + rejection_reason(outcome, "malformed field with a forged signature"), + "invalid ref-update event fields: ref_name exceeds 1024 bytes", + "the field guard must own the rejection before signature verification" + ); + assert_eq!( + peer_exists_calls(), + 0, + "the field guard must also precede the peer lookup" + ); + } + + /// Sha256-format repositories carry 64-character object ids. They must pass + /// the same boundary as the 40-character sha1 control, or the shape rule + /// becomes a silent object-format refusal. + #[sqlx::test] + async fn a_signed_sha256_ref_update_is_accepted(pool: PgPool) { + let db = ingest_db(&pool).await; + let keypair = Keypair::generate(); + let mut event = event_for(&keypair); + event.old_sha = "0".repeat(64); + event.new_sha = "a".repeat(64); + sign_ref_update(&keypair, &mut event).unwrap(); + seed_peer(&pool, &event.node_did).await; + + let outcome = + ingest_with_fresh_limiter(&db, true, true, &bytes_of(&event), &PeerId::random()).await; + assert!( + matches!(outcome, IngestOutcome::Accepted), + "sha256 object ids must ingest, got {outcome:?}" + ); + let stored: (String, String) = + sqlx::query_as("SELECT old_sha, new_sha FROM received_ref_updates") + .fetch_one(&pool) + .await + .expect("sha256 ref-update row"); + assert_eq!(stored.0.len(), 64); + assert_eq!(stored.1.len(), 64); + } + /// R6: the acceptance path, which is what keeps federation alive. A guard /// that rejects everything would pass every test above and fail here. #[sqlx::test] @@ -11106,12 +11369,11 @@ mod tests { .await; assert_eq!( outcome.metric_label(), - "stale_timestamp", - "an unparseable stamp must count under the same label as its two siblings; a publisher \ - emitting non-RFC-3339 is a freshness violation an operator reads off one series" + "rejected", + "wire-format validation now owns a non-RFC-3339 stamp before the freshness window" ); assert!( - matches!(outcome, IngestOutcome::StaleTimestamp(_)), + matches!(outcome, IngestOutcome::Rejected(_)), "a timestamp that cannot be parsed cannot be freshness-checked, so it must be refused \ rather than admitted, got {outcome:?}" ); diff --git a/crates/twigpine-node/src/server.rs b/crates/twigpine-node/src/server.rs index 1290c39b4..01318b6e9 100644 --- a/crates/twigpine-node/src/server.rs +++ b/crates/twigpine-node/src/server.rs @@ -615,7 +615,14 @@ pub fn build_router(state: AppState) -> Router { .layer(axum::Extension(rate_limit::IpRateLimiter { limiter: state.peer_write_rate_limiter.clone(), trust: state.push_limiter_trust, - })); + })) + // Announce and notify payloads are both small even at every field cap. + // Keep unknown-member padding from turning the pre-validation parse + // into a multi-megabyte allocation; the JSON schema caps below remain + // the exact field contract. + .layer(RequestBodyLimitLayer::new( + crate::db::MAX_REF_UPDATE_WIRE_BYTES, + )); // ── Read routes — open for public repos ─────────────────────────────── let read_routes = Router::new() diff --git a/crates/twigpine-node/src/sync.rs b/crates/twigpine-node/src/sync.rs index c7c026e2d..05ab09fcd 100644 --- a/crates/twigpine-node/src/sync.rs +++ b/crates/twigpine-node/src/sync.rs @@ -2488,14 +2488,19 @@ mod tests { .unwrap(); } + /// Insert a queue row without the write-side validation choke point. The + /// malformed-slug and legacy full-DID worker tests use this to model rows + /// written before the choke point existed; current writers must keep going + /// through `enqueue`. 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)", + "INSERT INTO sync_queue (id, repo, node_did, ref_name, new_sha, cid, status, enqueued_at) + VALUES ($1, $2, $3, $4, $5, NULL, 'pending', $6)", ) .bind(uuid::Uuid::new_v4().to_string()) .bind(repo) .bind(did) + .bind("refs/heads/main") .bind("0".repeat(40)) .bind(chrono::Utc::now().to_rfc3339()) .execute(pool) @@ -2748,7 +2753,7 @@ mod tests { let did = "did:key:z6MkAttacker"; seed_local_peer(&pool, did, &peer_url).await; - enqueue(&state.db, &slug, did).await; + enqueue_raw(&pool, &slug, did).await; run_batch(&state, &repos_dir).await; @@ -2798,7 +2803,7 @@ mod tests { let did = "did:key:z6MkAttacker"; seed_local_peer(&pool, did, &peer_url).await; for slug in slugs { - enqueue(&state.db, slug, did).await; + enqueue_raw(&pool, slug, did).await; } run_batch(&state, &repos_dir).await; @@ -4113,7 +4118,7 @@ git "$@" let (_remote, peer_url) = rooted_remote(&["../hello"]); let did = "did:key:z6MkAttacker"; seed_local_peer(&pool, did, &peer_url).await; - enqueue(&state.db, "../hello", did).await; + enqueue_raw(&pool, "../hello", did).await; run_batch(&state, &repos_dir).await; assert_eq!(sync_status(&pool, "../hello").await, "failed"); @@ -4129,10 +4134,9 @@ git "$@" #[sqlx::test] async fn queued_escape_slug_cannot_plant_a_mirror_outside_repos_dir(pool: PgPool) { // The worker half of #272, committed in its attack form. The row goes - // into sync_queue directly rather than through notify, because that is - // the case the boundary check cannot cover: rows queued before the fix - // existed, plus the gossip and trigger writers, which also enqueue a - // peer-controlled slug. `a//gitlawb-probe` used to reach + // into sync_queue directly because current writers validate before + // enqueueing; the fixture models rows written before that choke point + // existed. `a//gitlawb-probe` used to reach // PathBuf::join, whose absolute second component discards repos_dir and // puts the mirror at //gitlawb-probe.git. let state = crate::test_support::test_state(pool.clone()).await; @@ -4158,7 +4162,7 @@ git "$@" let (_remote, peer_url) = rooted_remote(&[&rel]); let did = "did:key:z6MkAttacker"; seed_local_peer(&pool, did, &peer_url).await; - enqueue(&state.db, &slug, did).await; + enqueue_raw(&pool, &slug, did).await; run_batch(&state, &repos_dir).await; diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 885669e27..bcbd19ab8 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -5769,7 +5769,7 @@ mod tests { repo: format!("{keypart}/evt-priv"), ref_name: "refs/heads/embargo-gossip".to_string(), old_sha: "0".repeat(40), - new_sha: "gossipSEKRET".to_string(), + new_sha: "5ec1e7".repeat(6) + "5ec1", timestamp: Utc::now().to_rfc3339(), cert_id: None, received_at: Utc::now().to_rfc3339(), @@ -5832,7 +5832,7 @@ mod tests { .unwrap(); let body = String::from_utf8_lossy(&bytes).to_string(); assert!( - !body.contains("gossipSEKRET"), + !body.contains("5ec1e75ec1e7"), "fail-closed response must not leak the gossip secret" ); }