Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 53 additions & 10 deletions crates/twigpine-node/src/api/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub(crate) async fn collect_visible_ref_updates(
caller: Option<&str>,
) -> Result<Vec<crate::db::ReceivedRefUpdate>> {
// 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
}

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -324,12 +324,18 @@ pub async fn list_repo_events(
let mut all_events: Vec<serde_json::Value> = 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);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
221 changes: 205 additions & 16 deletions crates/twigpine-node/src/api/peers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,13 +495,50 @@ pub async fn notify_sync(
auth: Option<Extension<AuthenticatedDid>>,
Json(req): Json<NotifyRequest>,
) -> Result<Json<serde_json::Value>> {
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"
Expand All @@ -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(
Expand All @@ -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(),
Expand All @@ -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),
Expand Down Expand Up @@ -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);
Expand All @@ -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"
);
}

Expand Down
Loading
Loading