From 697ef37bd8bedbe8aefbed9a7991a653392e5573 Mon Sep 17 00:00:00 2001 From: dawn <90008@gaze.systems> Date: Sat, 28 Mar 2026 20:30:05 +0300 Subject: [PATCH] [ingest] sync validation pass --- src/config.rs | 15 +- src/control/mod.rs | 4 + src/ingest/mod.rs | 1 + src/ingest/validation.rs | 410 +++++++++++++++++++++++++++++++++++++++ src/ingest/worker.rs | 163 ++++++++++------ src/ops.rs | 67 +------ tests/api.nu | 10 +- tests/repos_api.nu | 20 +- 8 files changed, 549 insertions(+), 141 deletions(-) create mode 100644 src/ingest/validation.rs diff --git a/src/config.rs b/src/config.rs index ea52dd2..26aed4e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -100,7 +100,7 @@ impl FromStr for CrawlerMode { "list_repos" | "list-repos" => Ok(Self::ListRepos), "by_collection" | "by-collection" => Ok(Self::ByCollection), _ => Err(miette::miette!( - "invalid crawler mode: expected 'relay' or 'by_collection'" + "invalid crawler mode: expected 'list_repos' or 'by_collection'" )), } } @@ -261,6 +261,13 @@ pub struct Config { /// number of resolved identities to keep in the in-memory LRU cache. /// set via `HYDRANT_IDENTITY_CACHE_SIZE`. pub identity_cache_size: u64, + /// enable MST inversion validation on incoming commits (expensive). + /// set via `HYDRANT_VERIFY_MST`. + pub verify_mst: bool, + /// clock drift window for future-rev rejection, in seconds. + /// commits with a rev timestamp more than this many seconds in the future are rejected. + /// set via `HYDRANT_REV_CLOCK_SKEW`. default: 300 (5 minutes). + pub rev_clock_skew_secs: i64, /// NSID patterns that trigger auto-discovery in filter mode (e.g. `app.bsky.feed.post`). /// set via `HYDRANT_FILTER_SIGNALS` as a comma-separated list. @@ -346,6 +353,8 @@ impl Default for Config { }], verify_signatures: SignatureVerification::Full, identity_cache_size: 1_000_000, + verify_mst: false, + rev_clock_skew_secs: 300, filter_signals: None, filter_collections: None, filter_excludes: None, @@ -438,6 +447,8 @@ impl Config { let verify_signatures = cfg!("VERIFY_SIGNATURES", defaults.verify_signatures); let identity_cache_size = cfg!("IDENTITY_CACHE_SIZE", defaults.identity_cache_size); + let verify_mst: bool = cfg!("VERIFY_MST", defaults.verify_mst); + let rev_clock_skew_secs: i64 = cfg!("REV_CLOCK_SKEW", defaults.rev_clock_skew_secs); let enable_firehose = cfg!("ENABLE_FIREHOSE", defaults.enable_firehose); let enable_crawler = std::env::var("HYDRANT_ENABLE_CRAWLER") .ok() @@ -541,6 +552,8 @@ impl Config { crawler_sources, verify_signatures, identity_cache_size, + verify_mst, + rev_clock_skew_secs, filter_signals, filter_collections, filter_excludes, diff --git a/src/control/mod.rs b/src/control/mod.rs index a07055f..509e658 100644 --- a/src/control/mod.rs +++ b/src/control/mod.rs @@ -518,6 +518,10 @@ impl Hydrant { matches!(config.verify_signatures, SignatureVerification::Full), config.ephemeral, config.firehose_workers, + crate::ingest::validation::ValidationOptions { + verify_mst: config.verify_mst, + rev_clock_skew_secs: config.rev_clock_skew_secs, + }, ) .run(handle) } diff --git a/src/ingest/mod.rs b/src/ingest/mod.rs index a5abbf4..f8fc5b9 100644 --- a/src/ingest/mod.rs +++ b/src/ingest/mod.rs @@ -2,6 +2,7 @@ use tokio::sync::mpsc; pub mod firehose; pub mod stream; +pub mod validation; pub mod worker; use jacquard_common::types::did::Did; diff --git a/src/ingest/validation.rs b/src/ingest/validation.rs new file mode 100644 index 0000000..f9f1d9a --- /dev/null +++ b/src/ingest/validation.rs @@ -0,0 +1,410 @@ +use jacquard_common::IntoStatic; +use jacquard_common::types::cid::Cid; +use jacquard_common::types::crypto::PublicKey; +use jacquard_repo::MemoryBlockStore; +use jacquard_repo::Mst; +use jacquard_repo::car::reader::{ParsedCar, parse_car_bytes}; +use jacquard_repo::commit::Commit as AtpCommit; +use jacquard_repo::mst::VerifiedWriteOp; +use miette::IntoDiagnostic; +use smol_str::ToSmolStr; +use std::sync::Arc; +use thiserror::Error; + +use crate::ingest::stream::{Commit, RepoOpAction, Sync}; +use crate::types::RepoState; + +/// describes which size limit was exceeded +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SizeLimitKind { + /// msg.blocks.len() > 2 MiB + BlocksField, + /// msg.ops.len() > 200 + OpCount, + /// individual record block > 1 MiB + RecordSize, +} + +impl std::fmt::Display for SizeLimitKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::BlocksField => write!(f, "blocks field exceeds 2MiB"), + Self::OpCount => write!(f, "op count exceeds 200"), + Self::RecordSize => write!(f, "record block exceeds 1MiB"), + } + } +} + +#[derive(Debug, Error)] +pub enum CommitValidationError { + /// rev is not greater than the last known rev + #[error("stale rev")] + StaleRev, + /// rev timestamp exceeds the clock skew window + #[error("future rev")] + FutureRev, + /// CAR could not be parsed, or a required block is missing + #[error("malformed CAR: {0}")] + MalformedCar(miette::Report), + /// wire message fields differ from the signed commit object + #[error("field mismatch in {field}")] + FieldMismatch { field: &'static str }, + /// signature verification failed. + /// `refreshed: false` means the key has not been re-fetched yet; + /// the caller should refresh and retry with the same commit. + #[error("signature verification failed")] + SigFailure { refreshed: bool }, + /// a block, op count, or record exceeds the ATProto size limits + #[error("size limit exceeded: {0}")] + SizeLimitExceeded(SizeLimitKind), + /// MST inversion check failed (only when verify_mst = true) + #[error("MST inversion failed: {0}")] + MstInvalid(miette::Report), + /// commit arrived from a host that is not the authoritative PDS for this DID + /// (enforced in phase 2 relay worker) + #[allow(dead_code)] + #[error("commit from wrong host")] + WrongHost, +} + +#[derive(Debug, Error)] +pub enum SyncValidationError { + /// blocks field exceeds 2MiB + #[error("size limit exceeded")] + SizeLimitExceeded, + /// CAR could not be parsed + #[error("malformed CAR: {0}")] + MalformedCar(miette::Report), + /// wire message fields differ from the signed commit object + #[error("field mismatch in {field}")] + FieldMismatch { field: &'static str }, + /// signature verification failed + #[error("signature verification failed")] + SigFailure { refreshed: bool }, +} + +/// indicates that the commit's chain pointers do not match the last known repo state. +/// this is not a hard rejection so callers can decide whta they want to do +pub struct ChainBreak { + /// msg.since is present and does not match the last known rev + pub since_mismatch: bool, + /// msg.prev_data does not match the last known data CID + pub prev_data_mismatch: bool, +} + +/// a successfully validated `#commit` message, carrying pre-parsed data for apply_commit +pub struct ValidatedCommit<'c> { + pub commit: &'c Commit<'c>, + /// result of parse_car_bytes, already done so apply_commit does not re-parse + pub parsed_blocks: ParsedCar, + /// deserialized and signature-verified commit object + pub commit_obj: AtpCommit<'static>, + /// Some if chain pointers are inconsistent with last known state + pub chain_break: Option, +} + +/// a successfully validated `#sync` message +pub struct ValidatedSync { + /// MST root CID from the commit object, used to detect noop syncs + pub data_cid: Cid<'static>, + /// rev string from the commit object, used to detect stale syncs + pub rev: String, +} + +pub struct ValidationOptions { + /// clock drift window for future-rev rejection (seconds). default: 300 + pub rev_clock_skew_secs: i64, + /// run MST inversion validation (expensive). default: false + pub verify_mst: bool, +} + +impl Default for ValidationOptions { + fn default() -> Self { + Self { + rev_clock_skew_secs: 300, + verify_mst: false, + } + } +} + +/// validate an incoming `#commit` message. +/// +/// on success, returns a `ValidatedCommit` carrying pre-parsed data so that +/// `apply_commit` does not need to repeat the work. +/// +/// chain-break (since/prevData mismatch) is NOT an error. callers check +/// `validated.chain_break.is_some()` and decide how to respond. +/// +/// - `repo_state`: `None` for the first-ever commit for this DID. +/// - `signing_key`: `None` when signature verification is disabled. +pub fn validate_commit<'c>( + msg: &'c Commit<'c>, + repo_state: Option<&RepoState>, + signing_key: Option<&PublicKey>, + opts: &ValidationOptions, + handle: &tokio::runtime::Handle, +) -> Result, CommitValidationError> { + const MAX_BLOCKS_BYTES: usize = 2_097_152; // 2 MiB + const MAX_OPS: usize = 200; + const MAX_RECORD_BYTES: usize = 1_048_576; // 1 MiB + + // 1. size limits + if msg.blocks.len() > MAX_BLOCKS_BYTES { + return Err(CommitValidationError::SizeLimitExceeded( + SizeLimitKind::BlocksField, + )); + } + if msg.ops.len() > MAX_OPS { + return Err(CommitValidationError::SizeLimitExceeded( + SizeLimitKind::OpCount, + )); + } + + // 2. stale rev, skip if msg.rev <= last known rev (lexicographic order) + if let Some(state) = repo_state { + if let Some(root) = &state.root { + if msg.rev.as_str() <= root.rev.to_tid().as_str() { + return Err(CommitValidationError::StaleRev); + } + } + } + + // 3. future rev, reject if rev timestamp is more than clock_skew_secs ahead of now + { + let rev_us = msg.rev.timestamp() as i64; + let now_us = chrono::Utc::now().timestamp_micros(); + if rev_us > now_us + opts.rev_clock_skew_secs * 1_000_000 { + return Err(CommitValidationError::FutureRev); + } + } + + // 4. CAR parse + let parsed = handle + .block_on(parse_car_bytes(msg.blocks.as_ref())) + .map_err(|e| CommitValidationError::MalformedCar(miette::miette!("{e}")))?; + + let root_bytes = parsed.blocks.get(&parsed.root).ok_or_else(|| { + CommitValidationError::MalformedCar(miette::miette!("root block missing from CAR")) + })?; + + // 5. commit object deserialization + let commit_obj = AtpCommit::from_cbor(root_bytes) + .map_err(|e| CommitValidationError::MalformedCar(miette::miette!("{e}")))?; + + // 6. field consistency: wire message vs signed commit object + if commit_obj.did.as_str() != msg.repo.as_str() { + return Err(CommitValidationError::FieldMismatch { field: "repo" }); + } + if commit_obj.rev.as_str() != msg.rev.as_str() { + return Err(CommitValidationError::FieldMismatch { field: "rev" }); + } + + // 7. signature verification + if let Some(key) = signing_key { + commit_obj + .verify(key) + .map_err(|_| CommitValidationError::SigFailure { refreshed: false })?; + } + + let commit_obj = commit_obj.into_static(); + + // 8. chain break checks + let chain_break = chain_break_check(msg, repo_state); + + // 9–10. per-record size limits and basic CBOR validity + for op in &msg.ops { + let Some(cid_link) = &op.cid else { continue }; + let cid = cid_link.to_ipld().map_err(|e| { + CommitValidationError::MalformedCar(miette::miette!("invalid op CID: {e}")) + })?; + let Some(block) = parsed.blocks.get(&cid) else { + return Err(CommitValidationError::MalformedCar(miette::miette!( + "block for op CID {cid} missing from CAR" + ))); + }; + + if block.len() > MAX_RECORD_BYTES { + return Err(CommitValidationError::SizeLimitExceeded( + SizeLimitKind::RecordSize, + )); + } + + serde_ipld_dagcbor::from_slice::(block).map_err(|e| { + CommitValidationError::MalformedCar(miette::miette!("record is not valid CBOR: {e}")) + })?; + } + + // 11. MST inversion + if opts.verify_mst { + verify_mst(msg, &parsed, &commit_obj, handle).map_err(CommitValidationError::MstInvalid)?; + } + + Ok(ValidatedCommit { + commit: msg, + parsed_blocks: parsed, + commit_obj, + chain_break, + }) +} + +/// validate an incoming `#sync` message. +/// +/// replaces `ops::verify_sync_event`, adding field consistency checks. +pub fn validate_sync<'c>( + msg: &'c Sync<'c>, + signing_key: Option<&PublicKey>, + handle: &tokio::runtime::Handle, +) -> Result { + const MAX_BLOCKS_BYTES: usize = 2_097_152; + + // 1. size limit + if msg.blocks.len() > MAX_BLOCKS_BYTES { + return Err(SyncValidationError::SizeLimitExceeded); + } + + // 2. CAR parse + let parsed = handle + .block_on(parse_car_bytes(msg.blocks.as_ref())) + .map_err(|e| SyncValidationError::MalformedCar(miette::miette!("{e}")))?; + + let root_bytes = parsed.blocks.get(&parsed.root).ok_or_else(|| { + SyncValidationError::MalformedCar(miette::miette!("root block missing from CAR")) + })?; + + // 3. commit object deserialization + let commit_obj = AtpCommit::from_cbor(root_bytes) + .map_err(|e| SyncValidationError::MalformedCar(miette::miette!("{e}")))?; + + // 4. field consistency + if commit_obj.did.as_str() != msg.did.as_str() { + return Err(SyncValidationError::FieldMismatch { field: "did" }); + } + if commit_obj.rev.as_str() != msg.rev.as_str() { + return Err(SyncValidationError::FieldMismatch { field: "rev" }); + } + + // 5. signature verification + if let Some(key) = signing_key { + commit_obj + .verify(key) + .map_err(|_| SyncValidationError::SigFailure { refreshed: false })?; + } + + Ok(ValidatedSync { + data_cid: Cid::ipld(commit_obj.data).into_static(), + rev: commit_obj.rev.to_string(), + }) +} + +/// compare msg chain pointers against known repo state and return a `ChainBreak` if inconsistent. +fn chain_break_check(msg: &Commit<'_>, repo_state: Option<&RepoState>) -> Option { + let state = repo_state?; + let root = state.root.as_ref()?; + + // since should equal the rev of the previous commit; only flag when since is present and wrong + let since_mismatch = msg + .since + .as_ref() + .map(|since| since.as_str() != root.rev.to_tid().as_str()) + .unwrap_or(false); + + // prev_data must equal the last known data CID when both are present + let prev_data_mismatch = match &msg.prev_data { + Some(prev_link) => match prev_link.to_ipld() { + Ok(cid) => cid != root.data, + Err(_) => true, // unparseable CID is a mismatch + }, + None => true, // no prev_data but we have a previous state is a chain break + }; + + if since_mismatch || prev_data_mismatch { + Some(ChainBreak { + since_mismatch, + prev_data_mismatch, + }) + } else { + None + } +} + +/// apply the inverse of each op (in reverse order) to the new MST and verify the resulting root +/// equals `msg.prev_data`. called only when `opts.verify_mst` is true. +fn verify_mst( + msg: &Commit<'_>, + parsed: &ParsedCar, + commit_obj: &AtpCommit<'_>, + handle: &tokio::runtime::Handle, +) -> miette::Result<()> { + let store = Arc::new(MemoryBlockStore::new_from_blocks(parsed.blocks.clone())); + let mut mst: Mst = Mst::load(store, commit_obj.data, None); + + handle.block_on(async { + for op in msg.ops.iter().rev() { + let inv = match &op.action { + RepoOpAction::Create => { + let cid_link = op + .cid + .as_ref() + .ok_or_else(|| miette::miette!("create op missing CID"))?; + let cid = cid_link.to_ipld().into_diagnostic()?; + VerifiedWriteOp::Create { + key: op.path.to_smolstr(), + cid, + } + } + RepoOpAction::Update => { + let cid_link = op + .cid + .as_ref() + .ok_or_else(|| miette::miette!("update op missing CID"))?; + let Some(prev_link) = op.prev.as_ref() else { + // prev is optional in inductive firehose (v3); skip if absent + continue; + }; + let cid = cid_link.to_ipld().into_diagnostic()?; + let prev = prev_link.to_ipld().into_diagnostic()?; + VerifiedWriteOp::Update { + key: op.path.to_smolstr(), + cid, + prev, + } + } + RepoOpAction::Delete => { + let Some(prev_link) = op.prev.as_ref() else { + // prev is optional in inductive firehose (v3); skip if absent + continue; + }; + let prev = prev_link.to_ipld().into_diagnostic()?; + VerifiedWriteOp::Delete { + key: op.path.to_smolstr(), + prev, + } + } + RepoOpAction::Other(action) => { + return Err(miette::miette!("unknown op action: {action}")); + } + }; + + let ok = mst.invert_op(inv).await.into_diagnostic()?; + if !ok { + return Err(miette::miette!( + "MST inversion inconsistent with tree state for op on {}", + op.path + )); + } + } + + // verify the resulting root CID equals prev_data (skip for genesis commits) + if let Some(prev_link) = &msg.prev_data { + let expected = prev_link.to_ipld().into_diagnostic()?; + let root_cid = mst.get_pointer().await.into_diagnostic()?; + if root_cid != expected { + return Err(miette::miette!( + "MST inversion root mismatch: expected {expected}, got {root_cid}" + )); + } + } + + Ok(()) + }) +} diff --git a/src/ingest/worker.rs b/src/ingest/worker.rs index 9eaff30..b92d2d0 100644 --- a/src/ingest/worker.rs +++ b/src/ingest/worker.rs @@ -1,6 +1,9 @@ use crate::db::{self, keys}; use crate::filter::FilterMode; use crate::ingest::stream::{Account, Commit, Identity, SubscribeReposMessage, Sync}; +use crate::ingest::validation::{ + CommitValidationError, SyncValidationError, ValidationOptions, validate_commit, validate_sync, +}; use crate::ingest::{BufferRx, IngestMessage}; use crate::ops; use crate::resolver::{NoSigningKeyError, ResolverError}; @@ -14,7 +17,7 @@ use jacquard_common::cowstr::ToCowStr; use jacquard_common::types::crypto::PublicKey; use jacquard_common::types::did::Did; use jacquard_repo::error::CommitError; -use miette::{Context, Diagnostic, IntoDiagnostic, Result}; +use miette::{Diagnostic, IntoDiagnostic, Result}; use rand::Rng; use smol_str::ToSmolStr; use std::collections::hash_map::DefaultHasher; @@ -78,6 +81,7 @@ pub struct FirehoseWorker { verify_signatures: bool, ephemeral: bool, num_shards: usize, + validation_opts: Arc, } struct WorkerContext<'a> { @@ -89,6 +93,7 @@ struct WorkerContext<'a> { records_delta: &'a mut i64, broadcast_events: &'a mut Vec, handle: &'a tokio::runtime::Handle, + validation_opts: &'a ValidationOptions, } impl FirehoseWorker { @@ -98,6 +103,7 @@ impl FirehoseWorker { verify_signatures: bool, ephemeral: bool, num_shards: usize, + validation_opts: ValidationOptions, ) -> Self { Self { state, @@ -105,6 +111,7 @@ impl FirehoseWorker { verify_signatures, ephemeral, num_shards, + validation_opts: Arc::new(validation_opts), } } @@ -124,11 +131,12 @@ impl FirehoseWorker { let verify = self.verify_signatures; let ephemeral = self.ephemeral; let handle = handle.clone(); + let validation_opts = self.validation_opts.clone(); std::thread::Builder::new() .name(format!("ingest-shard-{i}")) .spawn(move || { - Self::shard(i, rx, state, verify, ephemeral, handle); + Self::shard(i, rx, state, verify, ephemeral, handle, validation_opts); }) .into_diagnostic()?; } @@ -175,6 +183,7 @@ impl FirehoseWorker { verify_signatures: bool, ephemeral: bool, handle: tokio::runtime::Handle, + validation_opts: Arc, ) { let _guard = handle.enter(); debug!(shard = id, "shard started"); @@ -197,6 +206,7 @@ impl FirehoseWorker { handle: &handle, verify_signatures, ephemeral, + validation_opts: &validation_opts, }; match msg { @@ -434,33 +444,59 @@ impl FirehoseWorker { ) -> Result, IngestError> { repo_state.advance_message_time(commit.time.0.timestamp_millis()); - // skip replayed events (already seen revision) - if matches!(repo_state.root, Some(ref root) if commit.rev.as_str() <= root.rev.to_tid().as_str()) - { - debug!( - did = %did, - commit_rev = %commit.rev, - state_rev = %repo_state.root.as_ref().map(|c| c.rev.to_tid()).expect("we checked in if"), - "skipping replayed event" - ); - return Ok(RepoProcessResult::Ok(repo_state)); - } + // TODO phase 2: host authority check (source_host not available in indexer mode) + + // validate the commit: stale rev, size limits, future rev, CAR parse, field + // consistency, signature, and chain-break detection + let signing_key = Self::fetch_key(ctx, did)?; + let validated = match validate_commit( + commit, + Some(&repo_state), + signing_key.as_ref(), + ctx.validation_opts, + ctx.handle, + ) { + Ok(v) => v, + Err(CommitValidationError::StaleRev) => { + debug!( + did = %did, + commit_rev = %commit.rev, + "skipping replayed commit" + ); + return Ok(RepoProcessResult::Ok(repo_state)); + } + Err(CommitValidationError::SigFailure { .. }) => { + // refresh key and retry once + Self::refresh_doc(ctx, &mut repo_state, did)?; + let refreshed_key = Self::fetch_key(ctx, did)?; + match validate_commit( + commit, + Some(&repo_state), + refreshed_key.as_ref(), + ctx.validation_opts, + ctx.handle, + ) { + Ok(v) => v, + Err(e) => { + warn!(did = %did, err = %e, "commit rejected after key refresh"); + return Ok(RepoProcessResult::Ok(repo_state)); + } + } + } + Err(e) => { + warn!(did = %did, err = %e, "commit rejected"); + return Ok(RepoProcessResult::Ok(repo_state)); + } + }; - if let (Some(repo_commit), Some(prev_commit)) = (&repo_state.root, &commit.prev_data) - && repo_commit.data - != prev_commit - .0 - .to_ipld() - .into_diagnostic() - .wrap_err("invalid cid from relay")? - { + // chain break: prev_data or since mismatch against last known state → backfill + if let Some(cb) = &validated.chain_break { warn!( did = %did, - repo = %repo_commit.data, - prev_commit = %prev_commit.0, - "gap detected, triggering backfill" + since_mismatch = cb.since_mismatch, + prev_data_mismatch = cb.prev_data_mismatch, + "chain break detected, triggering backfill" ); - let mut batch = ctx.state.db.inner.batch(); let _repo_state = ops::update_repo_status( &mut batch, @@ -477,13 +513,11 @@ impl FirehoseWorker { return Ok(RepoProcessResult::NeedsBackfill(Some(commit))); } - let signing_key = Self::fetch_key(ctx, did)?; let res = ops::apply_commit( &mut ctx.batch, &ctx.state.db, repo_state, - commit, - signing_key.as_ref(), + validated, &ctx.state.filter.load(), ctx.ephemeral, )?; @@ -505,43 +539,58 @@ impl FirehoseWorker { ) -> Result, IngestError> { repo_state.advance_message_time(sync.time.0.timestamp_millis()); - Self::refresh_doc(ctx, &mut repo_state, did)?; - - match ops::verify_sync_event(sync.blocks.as_ref(), Self::fetch_key(ctx, did)?.as_ref()) { - Ok((root, rev)) => { - if let Some(current_commit) = &repo_state.root { - if current_commit.data == root.to_ipld().expect("valid cid") { - debug!(did = %did, "skipping noop sync"); - return Ok(RepoProcessResult::Ok(repo_state)); - } + // TODO phase 2: host authority check - if rev.as_str() <= current_commit.rev.to_tid().as_str() { - debug!(did = %did, "skipping replayed sync"); + // validate: size limit, CAR parse, field consistency, signature + let signing_key = Self::fetch_key(ctx, did)?; + let validated = match validate_sync(sync, signing_key.as_ref(), ctx.handle) { + Ok(v) => v, + Err(SyncValidationError::SigFailure { .. }) => { + // refresh key and retry once (same pattern as handle_commit) + Self::refresh_doc(ctx, &mut repo_state, did)?; + let refreshed_key = Self::fetch_key(ctx, did)?; + match validate_sync(sync, refreshed_key.as_ref(), ctx.handle) { + Ok(v) => v, + Err(e) => { + warn!(did = %did, err = %e, "sync rejected after key refresh"); return Ok(RepoProcessResult::Ok(repo_state)); } } - - warn!(did = %did, "sync event, triggering backfill"); - let mut batch = ctx.state.db.inner.batch(); - repo_state = ops::update_repo_status( - &mut batch, - &ctx.state.db, - did, - repo_state, - RepoStatus::Backfilling, - )?; - batch.commit().into_diagnostic()?; - ctx.state - .db - .update_gauge_diff(&GaugeState::Synced, &GaugeState::Pending); - ctx.state.notify_backfill(); - Ok(RepoProcessResult::Ok(repo_state)) } Err(e) => { - error!(did = %did, err = %e, "failed to process sync event"); - Ok(RepoProcessResult::Ok(repo_state)) + warn!(did = %did, err = %e, "sync rejected"); + return Ok(RepoProcessResult::Ok(repo_state)); + } + }; + + // skip noop syncs (data CID unchanged) + if let Some(current_commit) = &repo_state.root { + if current_commit.data == validated.data_cid.to_ipld().expect("valid cid") { + debug!(did = %did, "skipping noop sync"); + return Ok(RepoProcessResult::Ok(repo_state)); + } + + if validated.rev.as_str() <= current_commit.rev.to_tid().as_str() { + debug!(did = %did, "skipping replayed sync"); + return Ok(RepoProcessResult::Ok(repo_state)); } } + + warn!(did = %did, "sync event, triggering backfill"); + let mut batch = ctx.state.db.inner.batch(); + repo_state = ops::update_repo_status( + &mut batch, + &ctx.state.db, + did, + repo_state, + RepoStatus::Backfilling, + )?; + batch.commit().into_diagnostic()?; + ctx.state + .db + .update_gauge_diff(&GaugeState::Synced, &GaugeState::Pending); + ctx.state.notify_backfill(); + Ok(RepoProcessResult::Ok(repo_state)) } fn handle_identity<'s>( diff --git a/src/ops.rs b/src/ops.rs index bf31437..63722f9 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -4,22 +4,18 @@ use fjall::Slice; use jacquard_common::CowStr; #[cfg(feature = "backlinks")] use jacquard_common::Data; -use jacquard_common::IntoStatic; -use jacquard_common::types::cid::Cid; -use jacquard_common::types::crypto::PublicKey; use jacquard_common::types::did::Did; -use jacquard_repo::car::reader::parse_car_bytes; use miette::{Context, IntoDiagnostic, Result}; use rand::{Rng, rng}; use std::collections::HashMap; use std::sync::atomic::Ordering; -use std::time::Instant; -use tracing::{debug, trace}; +use tracing::debug; use crate::db::types::{DbAction, DbRkey, DbTid, TrimmedDid}; use crate::db::{self, Db, keys, ser_repo_state}; use crate::filter::FilterConfig; use crate::ingest::stream::Commit; +use crate::ingest::validation::ValidatedCommit; use crate::types::StoredData; use crate::types::{ AccountEvt, BroadcastEvent, IdentityEvt, MarshallableEvt, RepoState, RepoStatus, ResyncState, @@ -197,75 +193,26 @@ pub fn update_repo_status<'batch, 's>( Ok(repo_state) } -pub fn verify_sync_event(blocks: &[u8], key: Option<&PublicKey>) -> Result<(Cid<'static>, String)> { - let parsed = tokio::task::block_in_place(|| { - tokio::runtime::Handle::current() - .block_on(parse_car_bytes(blocks)) - .into_diagnostic() - })?; - - let root_bytes = parsed - .blocks - .get(&parsed.root) - .ok_or_else(|| miette::miette!("root block missing from CAR"))?; - - let repo_commit = jacquard_repo::commit::Commit::from_cbor(root_bytes).into_diagnostic()?; - - if let Some(key) = key { - repo_commit - .verify(key) - .map_err(|e| miette::miette!("signature verification failed: {e}"))?; - } - - Ok(( - Cid::ipld(repo_commit.data).into_static(), - repo_commit.rev.to_string(), - )) -} - pub struct ApplyCommitResults<'s> { pub repo_state: RepoState<'s>, pub records_delta: i64, pub blocks_count: i64, } -pub fn apply_commit<'commit, 's>( +pub fn apply_commit<'s>( batch: &mut OwnedWriteBatch, db: &Db, mut repo_state: RepoState<'s>, - commit: &'commit Commit<'commit>, - signing_key: Option<&PublicKey>, + validated: ValidatedCommit<'_>, filter: &FilterConfig, ephemeral: bool, ) -> Result> { + let commit = validated.commit; + let parsed = validated.parsed_blocks; let did = &commit.repo; debug!(did = %did, commit = %commit.commit, "applying commit"); - // 1. parse CAR blocks and store them in CAS - let start = Instant::now(); - let parsed = tokio::task::block_in_place(|| { - tokio::runtime::Handle::current() - .block_on(parse_car_bytes(commit.blocks.as_ref())) - .into_diagnostic() - })?; - - trace!(did = %did, elapsed = ?start.elapsed(), "parsed car"); - - let root_bytes = parsed - .blocks - .get(&parsed.root) - .ok_or_else(|| miette::miette!("root block missing from CAR"))?; - - let root_commit = jacquard_repo::commit::Commit::from_cbor(root_bytes).into_diagnostic()?; - - if let Some(key) = signing_key { - root_commit - .verify(key) - .map_err(|e| miette::miette!("signature verification failed for {did}: {e}"))?; - trace!(did = %did, "signature verified"); - } - - repo_state.root = Some(root_commit.into()); + repo_state.root = Some(validated.commit_obj.into()); repo_state.touch(); batch.insert(&db.repos, keys::repo_key(did), ser_repo_state(&repo_state)?); diff --git a/tests/api.nu b/tests/api.nu index 621e6c7..3022ab3 100644 --- a/tests/api.nu +++ b/tests/api.nu @@ -12,11 +12,11 @@ def test-crawler-sources [url: string, pid: int] { } print " ok: starts empty" - # add a relay source - print " POST /crawler/sources (relay)..." + # add a list_repos source + print " POST /crawler/sources (list_repos)..." http post -f -e -t application/json $"($url)/crawler/sources" { url: "https://bsky.network", - mode: "relay" + mode: "list_repos" } | assert-status 201 "POST /crawler/sources" $pid print " ok: 201 Created" @@ -27,8 +27,8 @@ def test-crawler-sources [url: string, pid: int] { fail $"expected 1 source, got ($sources | length)" $pid } let s = ($sources | first) - if $s.mode != "relay" { - fail $"expected mode=relay, got ($s.mode)" $pid + if $s.mode != "list_repos" { + fail $"expected mode=list_repos, got ($s.mode)" $pid } if not $s.persisted { fail "expected persisted=true for dynamically added source" $pid diff --git a/tests/repos_api.nu b/tests/repos_api.nu index 1388191..14ac171 100644 --- a/tests/repos_api.nu +++ b/tests/repos_api.nu @@ -12,9 +12,8 @@ def test-repos [url: string] { } print $" count: ($items | length)" - # 2. test partition=all - print " testing partition=all..." - let all_items = (http get $"($url)/repos?partition=all" | from json -o) + # 2. test + let all_items = (http get $"($url)/repos" | from json -o) print $" count: ($all_items | length)" # 3. test cursor (if we have enough items) @@ -31,16 +30,6 @@ def test-repos [url: string] { } } - # 4. test partition=pending - print " testing partition=pending..." - let pending_items = (http get $"($url)/repos?partition=pending" | from json -o) - print $" pending count: ($pending_items | length)" - - # 5. test partition=resync - print " testing partition=resync..." - let resync_items = (http get $"($url)/repos?partition=resync" | from json -o) - print $" resync count: ($resync_items | length)" - print "all /repos pagination and filtering tests passed!" } @@ -62,11 +51,6 @@ def test-errors [url: string] { http get -f -e $"($url)/repos?cursor=invalid" | assert-status 400 "GET /repos invalid cursor" - # invalid partition in GET - print " testing GET /repos with invalid partition..." - http get -f -e $"($url)/repos?partition=invalid" - | assert-status 400 "GET /repos invalid partition" - print "all /repos error handling tests passed!" } -- knotmirror 0.0.1