diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 4c947688fb..eebe1db9df 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -3905,12 +3905,12 @@ dependencies = [ "id-core", "id-events", "id-store", + "id-sync", "iroh", "iroh-base", "iroh-blobs", "iroh-docs", "iroh-gossip", - "iroh-mainline-address-lookup", "iroh-mdns-address-lookup", "iroh-tickets", "libc", @@ -4069,6 +4069,34 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "id-sync" +version = "0.1.0" +dependencies = [ + "anyhow", + "futures-lite", + "futures-util", + "id-core", + "id-events", + "id-store", + "iroh", + "iroh-base", + "iroh-blobs", + "iroh-mainline-address-lookup", + "p2panda-auth", + "p2panda-core", + "p2panda-store", + "p2panda-sync", + "postcard", + "proptest", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tracing", +] + [[package]] name = "identity-hash" version = "0.1.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 2505746eb8..da325388ca 100644 --- a/pkgs/id/Cargo.toml +++ b/pkgs/id/Cargo.toml @@ -16,14 +16,14 @@ categories = ["command-line-utilities", "network-programming"] # id-core sub-crate under crates/; this package is the workspace root. [workspace] -members = ["crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-native-shell"] +members = ["crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-sync", "crates/id-native-shell"] # The vendored crates stay OUT of the workspace: as path dependencies inside # this directory Cargo would otherwise treat them as members, and a member's # feature graph joins the lock resolve — p2panda-sync's `test_utils` feature # forwards to `p2panda-store/test_utils`, whose `sqlite` feature pulls sqlx # into Cargo.lock even though no build here enables it (see vendor/README.md). exclude = ["vendor/p2panda-sync", "vendor/p2panda-encryption"] -default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events"] +default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-sync"] # ============================================================================= # Features @@ -57,7 +57,7 @@ web = [ "id-core/web", ] # Mainline DHT address lookup (P7.3, decision 15). Off in the default build; src/dht.rs decides per server. -dht = ["dep:iroh-mainline-address-lookup"] +dht = ["id-sync/dht"] # Live-cluster binding for the currency PoC (#2289): the official TigerBeetle # Rust client, pinned to the harness server version (harness.rs). Off by # default so normal builds do not link the client native tb_client library. @@ -77,6 +77,9 @@ id-store = { path = "crates/id-store", default-features = false } # Events-family modules extracted in step 2b of the crate split (#4405). # Re-exported at their historical crate:: paths in src/lib.rs. id-events = { path = "crates/id-events", default-features = false } +# Sync-family modules extracted in step 3 of the crate split (#4406). +# Re-exported at their historical crate:: paths in src/lib.rs. +id-sync = { path = "crates/id-sync", default-features = false } anyhow = "1" cbor-core = { version = "=0.10.1", features = ["serde"] } # Calendar arithmetic and the IANA time-zone database for the did-it tracker's @@ -92,8 +95,6 @@ futures-lite = "2" futures-util = { version = "0.3", features = ["sink"] } iroh = "1" iroh-mdns-address-lookup = "0.6" -# Mainline DHT address lookup (P7.3). Optional: only the `dht` feature brings it and n0-mainline in. -iroh-mainline-address-lookup = { version = "0.6", optional = true } iroh-base = "1" iroh-tickets = "1" iroh-blobs = "0.103" diff --git a/pkgs/id/crates/id-sync/Cargo.toml b/pkgs/id/crates/id-sync/Cargo.toml new file mode 100644 index 0000000000..63f8597076 --- /dev/null +++ b/pkgs/id/crates/id-sync/Cargo.toml @@ -0,0 +1,142 @@ +[package] +name = "id-sync" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +description = "Sync layer of the id crate: log sync, the meta protocol, file operations and the meta client wire half (pkgs/id crate split step 3, #4406)" +license = "MIT OR Apache-2.0" + +# Step 3 of the pkgs/id crate split (#3447 umbrella, #4406): the sync +# family lives here - `log_sync` and the wire layer (`protocol`, +# `fileops`, `dht`, and the wire half of `meta_client`). The envelope / +# artifact transfer modules join in step 3c. Dependencies per the design +# map: id-core, id-store, id-events (id-groups does not exist yet; the +# step needs nothing from it). `sync_method`, `discovery` and +# `connectivity` already live in id-core (landed drift from the design +# map, which had them here). Composition stays in the facade: the +# `MetaClient` enum (remote-or-local) and the `LocalNode`-backed tests +# remain there until step 7. + +[features] +default = [] +# Mainline DHT address lookup (P7.3). Off in the default build; the +# facade forwards its `dht` feature here. +dht = ["dep:iroh-mainline-address-lookup"] + +[dependencies] +anyhow = "1" +futures-lite = "2" +futures-util = { version = "0.3", features = ["sink"] } +id-core = { path = "../id-core", default-features = false } +id-events = { path = "../id-events", default-features = false } +id-store = { path = "../id-store", default-features = false } +iroh = "1" +iroh-base = "1" +iroh-blobs = "0.103" +iroh-mainline-address-lookup = { version = "0.6", optional = true } +p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc" } +p2panda-store = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", default-features = false } +p2panda-sync = { path = "../../vendor/p2panda-sync" } +postcard = { version = "1", features = ["alloc"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +tokio = { version = "1", features = ["full"] } +tracing = "0.1" + +[dev-dependencies] +p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", features = ["serde"] } +proptest = "1.12" +tempfile = "3" +tokio = { version = "1", features = ["test-util"] } + +[lints.rust] +# Rust compiler lints +unsafe_code = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } +rust_2024_compatibility = { level = "warn", priority = -1 } +missing_debug_implementations = "warn" +missing_docs = "warn" +trivial_casts = "warn" +trivial_numeric_casts = "warn" +unused_lifetimes = "warn" +unused_qualifications = "warn" +# Treat some warnings as errors in CI +# dead_code = "deny" +# unused_imports = "deny" + +[lints.clippy] +# Enable standard lint groups +all = { level = "warn", priority = -1 } +pedantic = { level = "warn", priority = -1 } +nursery = { level = "warn", priority = -1 } +cargo = { level = "warn", priority = -1 } + +# Deny critical issues - these indicate bugs or serious problems +# Test modules should add: #[allow(clippy::unwrap_used, clippy::expect_used)] +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +unimplemented = "deny" +todo = "deny" +dbg_macro = "deny" +# Allow print macros - this is a CLI application +print_stdout = "allow" +print_stderr = "allow" + +# Restriction lints - selectively enable valuable checks +clone_on_ref_ptr = "warn" +create_dir = "warn" +deref_by_slicing = "warn" +empty_structs_with_brackets = "warn" +filetype_is_file = "warn" +float_cmp_const = "warn" +fn_to_numeric_cast_any = "warn" +format_push_string = "warn" +get_unwrap = "warn" +if_then_some_else_none = "warn" +lossy_float_literal = "warn" +map_err_ignore = "warn" +mem_forget = "warn" +mixed_read_write_in_expression = "warn" +mutex_atomic = "warn" +rc_buffer = "warn" +rc_mutex = "warn" +redundant_type_annotations = "warn" +rest_pat_in_fully_bound_structs = "warn" +same_name_method = "warn" +self_named_module_files = "warn" +str_to_string = "warn" +string_add = "warn" +# string_to_string removed - clippy::implicit_clone covers it +suspicious_xor_used_as_pow = "warn" +try_err = "warn" +undocumented_unsafe_blocks = "warn" +unnecessary_safety_comment = "warn" +unnecessary_safety_doc = "warn" +unnecessary_self_imports = "warn" +unneeded_field_pattern = "warn" +verbose_file_reads = "warn" + +# Allow specific lints - too noisy or conflict with project style +module_name_repetitions = "allow" +must_use_candidate = "allow" +missing_errors_doc = "allow" +missing_panics_doc = "allow" +redundant_pub_crate = "allow" +significant_drop_tightening = "allow" +option_if_let_else = "allow" +multiple_crate_versions = "allow" +cargo_common_metadata = "allow" +too_many_lines = "allow" +# Allow these - they're reasonable for CLI app complexity +too_many_arguments = "allow" +fn_params_excessive_bools = "allow" +struct_excessive_bools = "allow" +cognitive_complexity = "allow" +future_not_send = "allow" +# TODO(P8.8): Clippy 1.99 fires these on about 50 `assert!(x.is_empty())` sites +# and 2 `chunks_exact` sites. Allowed until the lints review in plan step P8.8 +# (doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md). +assert_is_empty = "allow" +chunks_exact_to_as_chunks = "allow" diff --git a/pkgs/id/src/dht.rs b/pkgs/id/crates/id-sync/src/dht.rs similarity index 100% rename from pkgs/id/src/dht.rs rename to pkgs/id/crates/id-sync/src/dht.rs diff --git a/pkgs/id/crates/id-sync/src/fileops.rs b/pkgs/id/crates/id-sync/src/fileops.rs new file mode 100644 index 0000000000..6174ebbb4d --- /dev/null +++ b/pkgs/id/crates/id-sync/src/fileops.rs @@ -0,0 +1,816 @@ +//! File-level operations shared by the CLI, REPL, meta protocol and web UI. +//! +//! A "file" in `id` is a *name* (an iroh-blobs tag) pointing at an immutable +//! blob hash, plus a set of metadata tags in the [`TagStore`]. Operations that +//! touch both halves — `put`, `rename`, `copy`, `delete` — used to be +//! implemented separately in the web routes, the meta protocol and the REPL, +//! and they drifted apart (for example: copy over the meta protocol did not +//! copy metadata, and delete left metadata behind). This module is the single +//! implementation; every entry point calls it. +//! +//! # Semantics +//! +//! - [`FileOps::put`] verifies that the blob is present **before** creating the +//! name, so a failed upload can never leave a dangling reference. +//! - [`FileOps::rename`] and [`FileOps::copy`] archive a file they replace +//! (`.archive.`) and record `archive.replace` / `archive.rename` +//! metadata. Metadata moves (rename) or is duplicated (copy) with the file, +//! and the `name`/`file` identity tags are refreshed to the new name. +//! - [`FileOps::delete`] is a *hard* delete: the name, its metadata and its +//! archive tags are removed. The blob bytes stay until garbage collected. + +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use futures_lite::StreamExt; +use iroh_blobs::{Hash, api::Store}; +use thiserror::Error; + +use id_store::tags::{TagStore, TagValue, now_unix}; + +const ARCHIVE_IDENTITY_TAG_KEYS: [&[u8]; 5] = [ + b"name", + b"file", + b"path", + // Archive references describe the live file's archives, so they + // stay on the live name when its other metadata moves onto an + // archive. Letting one travel onto the archive subject orphans + // every earlier archive from the live file's delete (#4574). + b"archive.rename", + b"archive.replace", +]; + +/// Errors from file operations, distinguishable so callers can map them to +/// protocol errors or HTTP status codes. +#[derive(Debug, Error)] +pub enum FileOpError { + /// The new name was empty or whitespace. + #[error("name cannot be empty")] + EmptyName, + /// The name is rooted or contains a traversal component. + #[error("name must be a safe relative path: {0}")] + InvalidName(String), + /// The name collides with the namespace used for system archives. + #[error("name is reserved for archives: {0}")] + ReservedArchiveName(String), + /// Source and destination are the same name. + #[error("new name must differ from the current name")] + SameName, + /// The named file does not exist. + #[error("file not found: {0}")] + NotFound(String), + /// The blob to be named is not (completely) in the store. + #[error("blob {0} is not present in the store (upload the content before naming it)")] + BlobMissing(Hash), + /// Any other storage failure. + #[error(transparent)] + Store(#[from] anyhow::Error), +} + +/// Whether an error message from a server means "the blob is not (yet) there". +/// +/// Clients use this to retry a `Put` while an upload is still being finalized. +pub fn is_blob_missing_message(message: &str) -> bool { + message.contains("is not present in the store") +} + +/// Result of [`FileOps::rename`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RenameOutcome { + /// Hash of the renamed content. + pub hash: Hash, + /// Archive tag created for the original name, if any. + pub archived_original: Option, + /// Archive tag created for a file that was replaced at the destination. + pub archived_replaced: Option, +} + +/// Result of [`FileOps::copy`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CopyOutcome { + /// Hash of the copied content. + pub hash: Hash, + /// Archive tag created for a file that was replaced at the destination. + pub archived_replaced: Option, +} + +/// Result of [`FileOps::delete`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeleteOutcome { + /// Whether the name existed. + pub existed: bool, + /// Number of archive tags removed. + pub archives_removed: usize, + /// Number of metadata tags removed. + pub metadata_removed: usize, +} + +/// File operations over a blob [`Store`] and a [`TagStore`]. +#[derive(Debug, Clone)] +pub struct FileOps<'a> { + store: &'a Store, + tags: &'a TagStore, + blob_wait: Duration, + /// Node that originated a write, stamped as the file's `origin` tag + /// (#4973). `None` when the caller does not know its node id: no + /// origin is stamped and listings show the file's origin as unknown. + origin: Option, +} + +/// Serialises archive-name resolve+claim within this process (#2462). +/// +/// On its own, resolving a free archive name is check-then-act: the name +/// comes back *unclaimed* and the caller claims it with a later +/// unconditional `tags().set`, so two concurrent same-second replaces of +/// one name could resolve the same candidate and the second claim would +/// silently overwrite the first replace's archive. +/// [`claim_archive_name`] holds this lock across the whole +/// resolve-and-set, so a name is never handed out unclaimed. +/// +/// Scope: this is an in-process lock. It is sound because the `id` server +/// is the single process writing this tag store; a second writer process +/// sharing the store would need store-level compare-and-set instead. +static ARCHIVE_CLAIM_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// The archive tag for `name` at `ts`, bumped past any archive tag that +/// already exists: `{name}.archive.{ts}`, then `{name}.archive.{ts + 1}`, +/// and so on until the name is free. +/// +/// Archive names carry second-resolution timestamps, so two replaces of +/// one name within the same second would otherwise pick the same tag and +/// the second would silently overwrite the first replace's archive +/// (#1612). The suffix stays all digits: `delete` enumerates a file's +/// archives by exactly that shape, and the web layer parses the suffix +/// as the archive timestamp. +/// +/// The returned name is NOT claimed: callers must go through +/// [`claim_archive_name`], which holds [`ARCHIVE_CLAIM_LOCK`]; this +/// helper may only be called with that lock held. +async fn free_archive_name(store: &Store, name: &str, ts: u64) -> Result { + let mut suffix = ts; + loop { + let candidate = format!("{name}.archive.{suffix}"); + if store.tags().get(&candidate).await?.is_none() { + return Ok(candidate); + } + suffix += 1; + } +} + +/// Whether `name` has the archive tag shape used by FileOps. +fn is_archive_tag_name(name: &str) -> bool { + let Some((file_name, suffix)) = name.rsplit_once(".archive.") else { + return false; + }; + !file_name.is_empty() && !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()) +} + +/// Resolve a free archive name for `name` at `ts` and claim it for +/// `hash` in the same critical section (#2462): when this returns, the +/// tag already points at `hash`, and no concurrent claim in this process +/// can receive the same name. +pub(crate) async fn claim_archive_name( + store: &Store, + name: &str, + ts: u64, + hash: Hash, +) -> Result { + let _guard = ARCHIVE_CLAIM_LOCK.lock().await; + let candidate = free_archive_name(store, name, ts).await?; + store.tags().set(&candidate, hash).await?; + Ok(candidate) +} + +/// Provenance metadata keys recorded at a file's first write (#4973): +/// the origin node and the upload (`created`) timestamp. Listings read +/// a file's origin and upload time from these tags on its own name. +pub(crate) const PROVENANCE_TAG_KEYS: [&[u8]; 2] = [b"origin", b"created"]; + +/// Snapshot `from`'s recorded provenance tags onto `to` (#5383). +/// +/// An archive alias points at the same blob as its source but lives +/// under a new name, so without this copy a listing reports the +/// archive's origin as unknown and origin filtering misses it. Tags +/// are copied by content hash so the recorded values are preserved +/// exactly; a source with no recorded provenance leaves `to` with +/// none — unknown stays unknown, provenance is never invented. +pub(crate) async fn snapshot_provenance_tags(tags: &TagStore, from: &str, to: &str) -> Result<()> { + for key in PROVENANCE_TAG_KEYS { + for tag in tags.get_by_key(&tags.global, from.as_bytes(), key).await? { + tags.set_tag_hash( + &tags.global, + to.as_bytes(), + &tag.key, + tag.value.as_ref().map(TagValue::as_bytes), + tag.hash, + tag.len, + ) + .await?; + } + } + Ok(()) +} + +impl<'a> FileOps<'a> { + /// Create file operations over the given stores. + pub const fn new(store: &'a Store, tags: &'a TagStore) -> Self { + Self { + store, + tags, + blob_wait: Duration::ZERO, + origin: None, + } + } + + /// How long [`FileOps::put`] waits for a blob that is still being + /// uploaded to become complete before declaring it missing. + /// + /// A pushing client can finish *sending* slightly before the server has + /// finished *storing*, so a `Put` that immediately follows a push may + /// arrive first. Servers set a few seconds here; local puts keep the + /// default of zero, since their blob is already complete. + #[must_use] + pub const fn with_blob_wait(mut self, wait: Duration) -> Self { + self.blob_wait = wait; + self + } + + /// Stamp writes with `origin` (a node id) as the file's origin node + /// (#4973). The stamp is set-if-absent: the node that first wrote a + /// file stays its origin across later writes and renames, and files + /// written before origin stamping existed simply have no origin tag. + #[must_use] + pub fn with_origin(mut self, origin: String) -> Self { + self.origin = Some(origin); + self + } + + /// Whether the blob is complete, waiting up to `blob_wait` for it. + async fn blob_present(&self, hash: Hash) -> Result { + let deadline = Instant::now() + self.blob_wait; + loop { + if self + .store + .blobs() + .has(hash) + .await + .map_err(anyhow::Error::from)? + { + return Ok(true); + } + if Instant::now() >= deadline { + return Ok(false); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + + /// The single canonical-name rule for every FileOps entry point. + /// + /// A name is stored exactly as given, so any name that cannot be + /// re-specified identically is refused rather than stored under a + /// look-alike: leading or trailing padding, empty components + /// (`a//b`, `a/`, `a\`), rooted names, drive prefixes, and `.`/`..` + /// components all fail with [`FileOpError::InvalidName`]. Forgiving + /// surfaces (CLI, REPL, web) trim user input before calling in. + pub fn validate_name(name: &str) -> Result<(), FileOpError> { + if name.trim().is_empty() { + return Err(FileOpError::EmptyName); + } + let bytes = name.as_bytes(); + let has_windows_drive_prefix = + bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; + if name != name.trim() + || name.starts_with('/') + || name.starts_with('\\') + || has_windows_drive_prefix + || name + .split(['/', '\\']) + .any(|component| component.is_empty() || matches!(component, "." | "..")) + { + return Err(FileOpError::InvalidName(name.to_owned())); + } + if is_archive_tag_name(name) { + return Err(FileOpError::ReservedArchiveName(name.to_owned())); + } + Ok(()) + } + + /// Validate a rename/copy target without normalising it: the target is + /// stored verbatim, so trimming here would create the padded-value twins + /// the canonical-name rule exists to prevent. + fn validate_target(from: &str, to: &str) -> Result { + Self::validate_name(to)?; + if from == to { + return Err(FileOpError::SameName); + } + Ok(to.to_owned()) + } + + /// Archive whatever currently lives at `name`, returning the archive tag. + async fn archive_existing(&self, name: &str, ts: u64) -> Result> { + let Some(existing) = self.store.tags().get(name).await? else { + return Ok(None); + }; + // Archive references belong to the live file: they name the + // archives a future delete of this file must also remove. The + // transfer below discards them from this name (and the + // exclusion list keeps them off the archive), so snapshot them + // here and restore them onto the live name afterwards - + // otherwise each replacement orphans every earlier archive. + let mut archive_refs = Vec::new(); + for key in [&b"archive.rename"[..], &b"archive.replace"[..]] { + for tag in self + .tags + .get_by_key(&self.tags.global, name.as_bytes(), key) + .await? + { + if let Some(value) = tag.value.as_ref().and_then(|value| value.as_str()) { + archive_refs.push((key, value.to_owned())); + } + } + } + let archive = claim_archive_name(self.store, name, ts, existing.hash) + .await + .with_context(|| format!("archiving replaced file {name}"))?; + self.tags + .transfer_all_tags_except( + &self.tags.global, + name.as_bytes(), + archive.as_bytes(), + &ARCHIVE_IDENTITY_TAG_KEYS, + ) + .await + .with_context(|| format!("moving metadata for archived file {name}"))?; + self.tags + .refresh_identity_tags(&self.tags.global, archive.as_bytes()) + .await + .with_context(|| format!("refreshing identity for archive {archive}"))?; + for (key, value) in &archive_refs { + self.tags + .set_tag( + &self.tags.global, + name.as_bytes(), + key, + Some(value.as_bytes()), + b"", + ) + .await + .with_context(|| format!("restoring archive references for {name}"))?; + } + Ok(Some(archive)) + } + + /// Name `hash` as `name`, after verifying the blob is complete in the store. + /// + /// Sets the `created` tag only if absent and always refreshes `modified`, + /// stamps the `origin` node on a genuine first write (no `created` tag + /// recorded yet) if one is configured, then auto-tags `name`/`file`. + /// A legacy file that predates origin stamping keeps an unknown origin + /// when it is overwritten: absence of an `origin` tag alone does not + /// prove this write is the file's first. + pub async fn put(&self, name: &str, hash: Hash) -> Result<(), FileOpError> { + Self::validate_name(name)?; + if !self.blob_present(hash).await? { + return Err(FileOpError::BlobMissing(hash)); + } + self.store + .tags() + .set(name, hash) + .await + .map_err(anyhow::Error::from)?; + self.stamp(name, false).await; + Ok(()) + } + + /// Record `created` (if absent or `reset_created`), `modified`, and identity tags. + /// + /// Metadata bookkeeping failures are logged, not fatal: the name already + /// points at the right content. + async fn stamp(&self, name: &str, reset_created: bool) { + let ns = &self.tags.global; + let now = now_unix().to_string(); + let subject = name.as_bytes(); + // Origin is stamped only for a genuine first write: a name with a + // `created` tag but no `origin` tag is a legacy file whose true + // origin is unknown and must stay unknown (Codex review, PR #5191). + let first_write = self + .tags + .get_by_key(ns, subject, b"created") + .await + .map(|existing| existing.is_empty()) + .unwrap_or(false); + let created = if reset_created { + self.tags + .set_singleton(ns, subject, b"created", Some(now.as_bytes()), b"") + .await + } else { + self.tags + .set_if_absent(ns, subject, b"created", Some(now.as_bytes()), b"") + .await + .map(|_| ()) + }; + if let Err(e) = created { + tracing::warn!("failed to set created tag for {name}: {e:#}"); + } + if let Err(e) = self + .tags + .set_singleton(ns, subject, b"modified", Some(now.as_bytes()), b"") + .await + { + tracing::warn!("failed to set modified tag for {name}: {e:#}"); + } + if first_write + && let Some(origin) = &self.origin + && let Err(e) = self + .tags + .set_if_absent(ns, subject, b"origin", Some(origin.as_bytes()), b"") + .await + { + tracing::warn!("failed to set origin tag for {name}: {e:#}"); + } + if let Err(e) = self.tags.auto_tag(ns, subject, None).await { + tracing::warn!("failed to auto-tag {name}: {e:#}"); + } + } + + /// Rename `from` to `to`. + /// + /// A file already at `to` is archived first. When `archive` is true the + /// original name is also archived. Metadata follows the file. + pub async fn rename( + &self, + from: &str, + to: &str, + archive: bool, + ) -> Result { + let to = Self::validate_target(from, to)?; + let hash = self + .store + .tags() + .get(from) + .await + .map_err(anyhow::Error::from)? + .ok_or_else(|| FileOpError::NotFound(from.to_owned()))? + .hash; + let ts = now_unix(); + + let archived_replaced = self.archive_existing(&to, ts).await?; + self.store + .tags() + .set(&to, hash) + .await + .map_err(anyhow::Error::from)?; + + let archived_original = if archive { + match claim_archive_name(self.store, from, ts, hash).await { + Ok(name) => Some(name), + Err(e) => { + tracing::error!("failed to archive original {from}: {e}"); + None + } + } + } else { + None + }; + + // The archive alias keeps the source's recorded provenance + // (#5383): snapshot it now, before the transfer below moves + // (and deletes) the source name's tags onto `to`. + if let Some(archive_name) = &archived_original + && let Err(e) = snapshot_provenance_tags(self.tags, from, archive_name).await + { + tracing::warn!("failed to snapshot provenance {from} -> {archive_name}: {e:#}"); + } + + self.store + .tags() + .delete(from) + .await + .map_err(anyhow::Error::from)?; + + let ns = &self.tags.global; + if let Err(e) = self + .tags + .transfer_all_tags(ns, from.as_bytes(), to.as_bytes()) + .await + { + tracing::warn!("failed to transfer tags {from} -> {to}: {e:#}"); + } + if let Err(e) = self.tags.refresh_identity_tags(ns, to.as_bytes()).await { + tracing::warn!("failed to refresh identity tags for {to}: {e:#}"); + } + for (key, value) in [ + ("archive.rename", &archived_original), + ("archive.replace", &archived_replaced), + ] { + if let Some(archive_name) = value + && let Err(e) = self + .tags + .set_tag( + ns, + to.as_bytes(), + key.as_bytes(), + Some(archive_name.as_bytes()), + b"", + ) + .await + { + tracing::warn!("failed to set {key} tag on {to}: {e:#}"); + } + } + + Ok(RenameOutcome { + hash, + archived_original, + archived_replaced, + }) + } + + /// Copy `from` to `to` (a second name for the same content). + /// + /// A file already at `to` is archived first. Metadata is duplicated, the + /// identity tags are refreshed, and the copy gets its own `created` and + /// `modified` timestamps. + pub async fn copy(&self, from: &str, to: &str) -> Result { + let to = Self::validate_target(from, to)?; + let hash = self + .store + .tags() + .get(from) + .await + .map_err(anyhow::Error::from)? + .ok_or_else(|| FileOpError::NotFound(from.to_owned()))? + .hash; + let ts = now_unix(); + + let archived_replaced = self.archive_existing(&to, ts).await?; + self.store + .tags() + .set(&to, hash) + .await + .map_err(anyhow::Error::from)?; + + let ns = &self.tags.global; + if let Err(e) = self + .tags + .copy_all_tags_except( + ns, + from.as_bytes(), + to.as_bytes(), + &[b"archive.rename", b"archive.replace"], + ) + .await + { + tracing::warn!("failed to copy tags {from} -> {to}: {e:#}"); + } + if let Err(e) = self.tags.refresh_identity_tags(ns, to.as_bytes()).await { + tracing::warn!("failed to refresh identity tags for {to}: {e:#}"); + } + self.stamp(&to, true).await; + if let Some(archive_name) = &archived_replaced + && let Err(e) = self + .tags + .set_tag( + ns, + to.as_bytes(), + b"archive.replace", + Some(archive_name.as_bytes()), + b"", + ) + .await + { + tracing::warn!("failed to set archive.replace tag on {to}: {e:#}"); + } + + Ok(CopyOutcome { + hash, + archived_replaced, + }) + } + + /// Hard-delete `name`: the name itself, its metadata, and its archive tags. + pub async fn delete(&self, name: &str) -> Result { + if name.trim().is_empty() { + return Err(FileOpError::EmptyName); + } + + // Renames move the file identity metadata, including these archive + // references, to the current name. Read them before deleting metadata. + let mut archives = BTreeSet::new(); + for key in [&b"archive.rename"[..], &b"archive.replace"[..]] { + for tag in self + .tags + .get_by_key(&self.tags.global, name.as_bytes(), key) + .await? + { + if let Some(archive_name) = tag.value.as_ref().and_then(|value| value.as_str()) { + if is_archive_tag_name(archive_name) { + archives.insert(archive_name.to_owned()); + } else { + tracing::warn!("ignoring malformed archive reference on {name}"); + } + } + } + } + + // Keep the legacy/current-name scan for archives without metadata. + // Collect before mutation so a listing failure cannot leave a partial + // hard delete behind. + let prefix = format!("{name}.archive."); + let mut list = self + .store + .tags() + .list() + .await + .map_err(anyhow::Error::from)?; + while let Some(item) = list.next().await { + let item = item.map_err(anyhow::Error::from)?; + let tag = String::from_utf8_lossy(item.name.as_ref()).into_owned(); + if let Some(rest) = tag.strip_prefix(&prefix) + && !rest.is_empty() + && rest.bytes().all(|b| b.is_ascii_digit()) + { + archives.insert(tag); + } + } + + let existed = self + .store + .tags() + .get(name) + .await + .map_err(anyhow::Error::from)? + .is_some(); + self.store + .tags() + .delete(name) + .await + .map_err(anyhow::Error::from)?; + + let metadata_removed = self + .tags + .del_all_tags(&self.tags.global, name.as_bytes()) + .await + .unwrap_or_else(|e| { + tracing::warn!("failed to delete metadata for {name}: {e:#}"); + 0 + }); + + let mut archives_removed = 0; + for tag in archives { + match self.store.tags().delete(&tag).await { + Ok(_) => archives_removed += 1, + Err(e) => tracing::warn!("failed to delete archive tag {tag}: {e}"), + } + // Archives created by rename/copy carry the replaced file's + // metadata (archive_existing moves it onto the archive subject); + // remove it too, or it stays searchable after the archive blob + // tag is gone. + if let Err(e) = self + .tags + .del_all_tags(&self.tags.global, tag.as_bytes()) + .await + { + tracing::warn!("failed to delete metadata for archive {tag}: {e:#}"); + } + } + + Ok(DeleteOutcome { + existed, + archives_removed, + metadata_removed, + }) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod archive_name_tests { + use iroh_blobs::{Hash, store::mem::MemStore}; + + use super::*; + + fn hash(byte: u8) -> Hash { + Hash::from([byte; 32]) + } + + #[test] + fn fileops_rejects_archive_shaped_names_but_allows_lookalikes() { + for name in [ + "report.archive.0", + "report.archive.1700000000", + "report.archive.18446744073709551616", + ] { + assert!(matches!( + FileOps::validate_name(name), + Err(FileOpError::ReservedArchiveName(found)) if found == name + )); + } + + for name in ["a.archive.notes", "a.archive.+1", "a.archive.١"] { + assert!(FileOps::validate_name(name).is_ok(), "{name:?}"); + } + } + + /// Two replaces of one name within the same second must not share an + /// archive tag (#1612): the second archive is bumped to the next free + /// numeric suffix, and both replaced versions stay archived. + #[tokio::test] + async fn same_second_archives_never_overwrite() { + let store: Store = MemStore::new().into(); + let ts = 1_700_000_000_u64; + + let first = claim_archive_name(&store, "doc", ts, hash(1)) + .await + .unwrap(); + assert_eq!(first, format!("doc.archive.{ts}")); + + let second = claim_archive_name(&store, "doc", ts, hash(2)) + .await + .unwrap(); + assert_eq!(second, format!("doc.archive.{}", ts + 1)); + + // Both archives survive, each still pointing at its own version. + assert_eq!( + store.tags().get(&first).await.unwrap().unwrap().hash, + hash(1) + ); + assert_eq!( + store.tags().get(&second).await.unwrap().unwrap().hash, + hash(2) + ); + + // A third same-second replace bumps past both. + let third = claim_archive_name(&store, "doc", ts, hash(3)) + .await + .unwrap(); + assert_eq!(third, format!("doc.archive.{}", ts + 2)); + } + + /// Concurrent same-second claims must never share a name (#2462): + /// when resolve and claim were separate steps, interleaved resolves + /// could pick the same candidate and one archive silently overwrote + /// another. Barrier-synchronised claims must all land on distinct + /// tags, each still pointing at its own version. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_same_second_claims_never_collide() { + use std::sync::Arc; + + use tokio::sync::Barrier; + + let store: Store = MemStore::new().into(); + let store = Arc::new(store); + let ts = 1_700_000_000_u64; + const CLAIMS: u8 = 8; + let barrier = Arc::new(Barrier::new(usize::from(CLAIMS))); + let mut handles = Vec::new(); + for i in 0..CLAIMS { + let store = Arc::clone(&store); + let barrier = Arc::clone(&barrier); + handles.push(tokio::spawn(async move { + barrier.wait().await; + let name = claim_archive_name(&store, "doc", ts, hash(i + 1)) + .await + .unwrap(); + (name, hash(i + 1)) + })); + } + let mut claimed = Vec::new(); + for handle in handles { + claimed.push(handle.await.unwrap()); + } + let mut names: Vec<&str> = claimed.iter().map(|(name, _)| name.as_str()).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), usize::from(CLAIMS), "archive claims collided"); + for (name, expected) in &claimed { + assert_eq!( + store.tags().get(name).await.unwrap().unwrap().hash, + *expected, + "archive {name} lost its version" + ); + } + } + + /// With no collision the archive name is exactly the historic shape. + #[tokio::test] + async fn uncontested_archive_name_is_unchanged() { + let store: Store = MemStore::new().into(); + let name = claim_archive_name(&store, "doc", 42, hash(7)) + .await + .unwrap(); + assert_eq!(name, "doc.archive.42"); + assert_eq!( + store.tags().get(&name).await.unwrap().unwrap().hash, + hash(7) + ); + } +} + + + + + + diff --git a/pkgs/id/crates/id-sync/src/lib.rs b/pkgs/id/crates/id-sync/src/lib.rs new file mode 100644 index 0000000000..317e42b93f --- /dev/null +++ b/pkgs/id/crates/id-sync/src/lib.rs @@ -0,0 +1,20 @@ +//! Sync layer of the `id` crate. +//! +//! Step 3 of the pkgs/id crate split (#3447 umbrella, #4406): the sync +//! family lives here — [`log_sync`] (the p2panda log-sync sessions and +//! the range-sync bridge), the wire layer ([`protocol`], the meta +//! protocol; [`fileops`], the file operations the protocol serves; +//! [`dht`], the opt-in mainline lookup policy) and the wire half of +//! [`meta_client`] (request/response plumbing over an open connection). +//! +//! The facade re-exports each module at its historical `id::` path, so +//! no call site outside the moved modules changed. Composition stays +//! in the facade until step 7: the `MetaClient` enum that chooses +//! between a running server and the in-process local node is defined +//! there, over this crate's [`meta_client`] plumbing. + +pub mod dht; +pub mod fileops; +pub mod log_sync; +pub mod meta_client; +pub mod protocol; diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/crates/id-sync/src/log_sync.rs similarity index 92% rename from pkgs/id/src/log_sync.rs rename to pkgs/id/crates/id-sync/src/log_sync.rs index 7a433496d8..0d48601391 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/crates/id-sync/src/log_sync.rs @@ -48,19 +48,20 @@ use tokio::sync::{broadcast, mpsc}; use tokio::task::{JoinHandle, JoinSet}; use tokio::time::timeout; -use crate::chain::ChainExt; -use crate::connectivity::connect; -use crate::event_store::Ingest; -use crate::frames::{read_frame, write_frame}; -use crate::pull_policy::PullGate; -use crate::store_traits::{ChainLog, SharedEventStore}; -use crate::sync_method::{Answer, Request, SyncMethod, SyncStats, SyncSupport, choose}; -use crate::time::unix_ms; +use id_store::chain::ChainExt; +use id_core::connectivity::connect; +use id_events::event_store::Ingest; +use id_core::frames::{read_frame, write_frame}; +use id_events::pull_policy::PullGate; +use id_events::event_store::sync::RangeStore; +use id_store::store_traits::{ChainLog, EventStoreBackend, SharedEventStore}; +use id_core::sync_method::{Answer, Request, SyncMethod, SyncStats, SyncSupport, choose}; +use id_core::time::unix_ms; /// The ALPN for sync sessions. Range sync joins as a method of the same session, and the /// first frame of every session is the [`Request`]: one session shape on this ALPN. /// `serve`'s own range sessions (P3.1) run on their own ALPN, `/id-range-sync/1` -/// ([`crate::event_store::sync::ALPN`]) — a deliberate, documented split (#179), so no +/// ([`id_events::event_store::sync::ALPN`]) — a deliberate, documented split (#179), so no /// second, unlabelled session shape shares this one either. pub const SYNC_ALPN: &[u8] = b"/id-sync/1"; @@ -182,17 +183,17 @@ pub struct Outcome { /// Serves sync sessions on [`SYNC_ALPN`]. Register it with /// `Router::builder(..).accept(SYNC_ALPN, SyncProtocol::new(store, support, gate))`. #[derive(Clone, Debug)] -pub struct SyncProtocol { - store: SharedEventStore, +pub struct SyncProtocol { + store: SharedEventStore, support: Arc, gate: PullGate, } -impl SyncProtocol { +impl SyncProtocol { /// Serves `store`, running the methods that `support` allows, to the peers `gate` admits. #[must_use] pub fn new( - store: SharedEventStore, + store: SharedEventStore, support: impl SyncSupport + 'static, gate: PullGate, ) -> Self { @@ -204,7 +205,10 @@ impl SyncProtocol { } } -impl ProtocolHandler for SyncProtocol { +impl ProtocolHandler for SyncProtocol +where + SharedEventStore: RangeStore, +{ async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { let mut sessions = JoinSet::new(); let peer = conn.remote_id(); @@ -240,14 +244,17 @@ impl ProtocolHandler for SyncProtocol { /// /// Returns [`SyncError::Timeout`] if the session does not finish within `deadline`, and an error /// for a refused, mismatched or failed step. -pub async fn sync_with( +pub async fn sync_with( endpoint: &Endpoint, peer: impl Into, - store: &SharedEventStore, + store: &SharedEventStore, topic: Hash, stats: &impl SyncStats, deadline: Duration, -) -> Result { +) -> Result +where + SharedEventStore: RangeStore, +{ let method = choose(stats); let session = async { let conn = connect(endpoint, peer, SYNC_ALPN) @@ -289,15 +296,18 @@ pub async fn sync_with( /// Returns [`SyncError::Timeout`] past `deadline`, [`SyncError::Refused`] when `support` does not /// allow the method, [`SyncError::PullRefused`] when `gate` refuses `peer`, and an error for a /// failed step. -pub async fn answer( - store: &SharedEventStore, +pub async fn answer( + store: &SharedEventStore, support: &dyn SyncSupport, gate: &PullGate, peer: EndpointId, mut send: SendStream, mut recv: RecvStream, deadline: Duration, -) -> Result { +) -> Result +where + SharedEventStore: RangeStore, +{ let session = async { let request: Request = next_message(&mut recv).await?; // The pull policy decides before the method is agreed, so a refused peer gets no event. @@ -337,14 +347,17 @@ pub async fn answer( /// and writing, so the `Log` arm hands the streams to [`Frames`] (whose own task reads), /// while the `Range` arm keeps the raw streams: a range session sends and receives at /// once through its own halves, and reads each frame to its end before answering it. -async fn run_agreed( - store: &SharedEventStore, +async fn run_agreed( + store: &SharedEventStore, topic: Hash, method: SyncMethod, send: SendStream, recv: RecvStream, initiator: bool, -) -> Result { +) -> Result +where + SharedEventStore: RangeStore, +{ match method { SyncMethod::Log => { let mut frames = Frames::new(send, recv); @@ -369,19 +382,22 @@ async fn run_agreed( /// session never blocks the store's other users behind a network wait. The range sync /// set is the store's whole set: range sync has no topic subset, so `topic` names the /// session for the `Log` arm only. The deadline is the caller's, as for `Log`. -async fn run_range_sync( - store: &SharedEventStore, +async fn run_range_sync( + store: &SharedEventStore, send: &mut SendStream, recv: &mut RecvStream, initiator: bool, -) -> Result { +) -> Result +where + SharedEventStore: RangeStore, +{ let mut store = store.clone(); - let ranged = crate::event_store::sync::sync_on_streams( + let ranged = id_events::event_store::sync::sync_on_streams( &mut store, send, recv, initiator, - crate::event_store::range::Params::default(), + id_events::event_store::range::Params::default(), unix_ms(), ) .await @@ -449,8 +465,8 @@ async fn finish_stream(send: &mut SendStream, recv: &mut RecvStream) { /// /// The logs are the topic's authors on this side, as `TopicStore::resolve` gives them. An author /// the topic does not name here is sent in full by the other side, and the duplicates are counted. -async fn run_log_sync( - store: &SharedEventStore, +async fn run_log_sync( + store: &SharedEventStore, topic: Hash, frames: &mut Frames, ) -> Result { @@ -461,7 +477,7 @@ async fn run_log_sync( // Nothing reads the broadcast events. The sender fails only when no receiver exists, so this // receiver is kept alive until the session ends. let (events_tx, _events_rx) = broadcast::channel::>(EVENT_BUFFER); - let protocol: LogSync> = + let protocol: LogSync, LogSyncEvent> = LogSync::new(store.clone(), logs, events_tx); // The operations are stored by a worker on a thread that may block, so a write does not hold the @@ -542,8 +558,8 @@ enum Arrival { /// /// Returns [`SyncError::Store`] for the first batch the store refuses. Nothing of that batch is /// stored, and the arrivals after it are not read. -fn ingest_arrivals( - store: &SharedEventStore, +fn ingest_arrivals( + store: &SharedEventStore, mut arrivals: mpsc::Receiver, ) -> Result { let mut tally = Tally::default(); @@ -675,22 +691,141 @@ impl Drop for Frames { } } +/// Fixtures for the sync-session tests: a folded world reduced to the +/// membership set the pull gate actually reads, and an operator block +/// list with fixed rows. +/// +/// Step 3b of the crate split (#4406): these are the same fixtures the +/// facade's `pull_policy::testing` provided, re-based on the +/// `WorldAccess` trait the gate checks (id-events) — a members set is +/// the whole of what the gate can observe, so the sessions under test +/// behave identically. +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +pub(crate) mod testing { + use std::collections::HashSet; + use std::sync::{Arc, Mutex}; + + use iroh_base::{EndpointId, SecretKey}; + + use id_events::pull_policy::{PullGate, PullPolicy}; + use id_events::world_access::WorldAccess; + use id_store::event_types::{BlockKind, BlockList}; + + /// The world every fixture names. + pub(crate) const WORLD: &str = "docs"; + + /// The identity with byte `n` repeated, so a test knows the endpoint ID before it dials. + pub(crate) fn key(n: u8) -> SecretKey { + SecretKey::from_bytes(&[n; 32]) + } + + /// Membership that a test can change between two checks, as a removal changes the fold. + #[derive(Debug)] + pub(crate) struct Live(Mutex>); + + impl Live { + /// Replaces the membership, as the fold of a newer log does. + pub(crate) fn set(&self, folded: Self) { + *self.0.lock().expect("the fixture lock is not poisoned") = + folded.0.into_inner().expect("the fixture lock is not poisoned"); + } + } + + impl WorldAccess for Live { + fn is_current_member(&self, _world: &str, requester: &EndpointId) -> bool { + self.0 + .lock() + .is_ok_and(|members| members.contains(requester.as_bytes())) + } + + fn worlds_referencing(&self, _hash: &iroh_blobs::Hash) -> Vec { + Vec::new() + } + } + + /// The folded `docs` world, founded by `founder`, which adds `member` as a reader and, when + /// `removed`, removes them again. Reduced to the membership set the gate reads. + pub(crate) fn docs_world(founder: EndpointId, member: EndpointId, removed: bool) -> Live { + let mut members = HashSet::from([*founder.as_bytes(), *member.as_bytes()]); + if removed { + members.remove(member.as_bytes()); + } + Live(Mutex::new(members)) + } + + /// `folded` as shared membership that a gate can hold. + pub(crate) fn live(folded: Live) -> Arc { + Arc::new(folded) + } + + /// An operator block list with fixed rows, for the gate tests and the + /// session tests: the peers and topic tags it names are blocked, and + /// nothing else is. + #[derive(Debug, Default)] + pub(crate) struct StubBlocks { + /// Blocked endpoint keys. + pub peers: HashSet<[u8; 32]>, + /// Blocked topic tags, as raw bytes. + pub topics: HashSet>, + /// Blocked IPs, in the text form `BlockList::ip_blocked` + /// formats them in. + pub ips: HashSet, + } + + impl BlockList for StubBlocks { + fn is_blocked(&self, kind: BlockKind, value: &[u8]) -> bool { + match kind { + BlockKind::PeerKey => { + <[u8; 32]>::try_from(value).is_ok_and(|key| self.peers.contains(&key)) + } + BlockKind::TopicTag => self.topics.iter().any(|t| t == value), + BlockKind::Ip => { + std::str::from_utf8(value).is_ok_and(|text| self.ips.contains(text)) + } + } + } + } + + /// A stub block list naming `peers` by key and `topics` by tag. + pub(crate) fn stub_blocks(peers: &[[u8; 32]], topics: &[&str]) -> Arc { + Arc::new(StubBlocks { + peers: peers.iter().copied().collect(), + topics: topics.iter().map(|t| t.as_bytes().to_vec()).collect(), + ips: HashSet::new(), + }) + } + + /// An open gate over the fixture world. It never reads membership. + pub(crate) fn open_gate() -> PullGate { + PullGate::new( + PullPolicy::Open, + WORLD, + live(docs_world(key(0).public(), key(0).public(), false)), + ) + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use std::net::{Ipv4Addr, SocketAddr}; + /// The tests run against the concrete store, as the facade's alias + /// did before step 3b made the sessions generic over the backend. + type SharedEventStore = id_store::store_traits::SharedEventStore; + use iroh::endpoint::{Connection, RelayMode, presets}; use iroh::protocol::Router; use p2panda_core::{SeqNum, SigningKey}; use proptest::prelude::*; use super::*; - use crate::chain::{Event, sign}; - use crate::event_store::EventStore; - use crate::pull_policy::{PullGate, PullPolicy, testing}; - use crate::sync_method::{Estimate, LogAndRange, LogSyncOnly}; - use crate::waiting::WaitingLimits; + use id_store::chain::{Event, sign}; + use id_events::event_store::EventStore; + use id_events::pull_policy::{PullGate, PullPolicy}; + use id_core::sync_method::{Estimate, LogAndRange, LogSyncOnly}; + use id_core::waiting::WaitingLimits; use iroh_base::SecretKey; // Keep test sessions aligned with production; CI can run the bulk page-transfer test under @@ -1008,8 +1143,8 @@ mod tests { /// the group at that position, is kept without applying. #[tokio::test] async fn test_a_range_session_counts_a_stored_but_unapplied_arrival_as_voided() { - use crate::membership::AuthId; - use crate::membership::body::encode_body; + use id_core::membership::AuthId; + use id_core::membership::body::encode_body; use p2panda_auth::Access; use p2panda_auth::group::{GroupAction, GroupMember}; diff --git a/pkgs/id/crates/id-sync/src/meta_client.rs b/pkgs/id/crates/id-sync/src/meta_client.rs new file mode 100644 index 0000000000..b22c3a059f --- /dev/null +++ b/pkgs/id/crates/id-sync/src/meta_client.rs @@ -0,0 +1,321 @@ +//! Client side of the meta protocol, with an in-process fallback. +//! +//! Commands that talk to the meta protocol (tags, and anything else expressed +//! as a [`MetaRequest`]) are written once against [`MetaRequester`]. Two +//! implementations exist: +//! +//! - [`MetaClient::Remote`]: a QUIC connection to a running `id serve` +//! (local, found via the lock file) or to any peer by node ID. +//! - [`MetaClient::Local`]: no server is running, so the request is answered +//! **in-process by the very same [`MetaProtocol::handle`]** over a +//! [`LocalNode`]. Offline and online therefore behave identically — there is +//! no separate "legacy" code path to drift out of sync. + +use std::future::Future; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use iroh::{ + EndpointAddr, + endpoint::{Connection, Endpoint, ReadToEndError, RecvStream}, +}; +use iroh_base::EndpointId; + +use crate::protocol::{MetaRequest, MetaResponse}; + +/// Maximum accepted size of a single response (64 MiB). +pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; + +/// Maximum time allowed for one remote meta request and its response. +pub const META_RESPONSE_TIMEOUT: Duration = Duration::from_secs(45); + +/// Something that can answer a [`MetaRequest`]. +pub trait MetaRequester { + /// Send `req` and return the node's response. + /// + /// A [`MetaResponse::Error`] is returned as `Ok`; use [`expect_ok`] to turn + /// it into an `Err`. + fn request(&mut self, req: MetaRequest) -> impl Future>; +} + +/// Turn a [`MetaResponse::Error`] into an `Err`, passing other responses through. +pub fn expect_ok(resp: MetaResponse) -> Result { + match resp { + MetaResponse::Error { message } => bail!("{message}"), + other => Ok(other), + } +} + +/// Map a capped response-read failure to an error worth showing a user. +/// +/// `ReadToEndError::TooLong` displays as a bare "stream too long", which +/// sends diagnosis toward the transport; name the actual cause and the +/// limit instead. Any other read failure passes through unchanged. +pub fn capped_response_error(err: ReadToEndError) -> anyhow::Error { + match err { + ReadToEndError::TooLong => { + anyhow::anyhow!("response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit") + } + other => other.into(), + } +} + +/// Read one response stream to its end, bounded by [`MAX_RESPONSE_BYTES`] +/// and [`META_RESPONSE_TIMEOUT`]. +/// +/// Hand-rolled request paths (remote find in the CLI and the REPL) use this +/// instead of a per-call-site literal bound, so every response read shares +/// the one named cap and cannot drift back to a smaller size: the find +/// handler returns every match unbounded, so a response past ~64 KiB is +/// ordinary for a large store (#1617). +pub async fn read_capped_response(recv: &mut RecvStream) -> Result> { + read_capped_response_with_timeout(recv, META_RESPONSE_TIMEOUT).await +} + +async fn read_capped_response_with_timeout( + recv: &mut RecvStream, + timeout: Duration, +) -> Result> { + id_core::connectivity::within( + timeout, + "reading a meta response", + read_capped_response_unbounded(recv), + ) + .await +} + +async fn read_capped_response_unbounded(recv: &mut RecvStream) -> Result> { + recv.read_to_end(MAX_RESPONSE_BYTES) + .await + .map_err(capped_response_error) +} + +/// Send one request over an open connection. +pub async fn request_over(conn: &Connection, req: &MetaRequest) -> Result { + request_over_with_timeout(conn, req, META_RESPONSE_TIMEOUT).await +} + +async fn request_over_with_timeout( + conn: &Connection, + req: &MetaRequest, + timeout: Duration, +) -> Result { + id_core::connectivity::within(timeout, "waiting for a meta response", async { + let (mut send, mut recv) = conn.open_bi().await?; + send.write_all(&postcard::to_allocvec(req)?).await?; + send.finish()?; + let buf = read_capped_response_unbounded(&mut recv).await?; + crate::protocol::decode_meta_exact(&buf).context("decoding meta response") + }) + .await +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::protocol::{FindMatch, ListEntry, MatchKind}; + use iroh::{RelayMode, TransportAddr, endpoint::presets}; + use iroh_blobs::Hash; + use std::net::Ipv4Addr; + + const TEST_ALPN: &[u8] = b"id-capped-response-test"; + + /// An endpoint on localhost, with no relay and no address lookup. + async fn endpoint(alpns: Vec>) -> Result { + Ok(Endpoint::builder(presets::Minimal) + .alpns(alpns) + .relay_mode(RelayMode::Disabled) + .bind() + .await?) + } + + /// The address of `ep` on localhost: every bound socket, with an + /// unspecified IP replaced by the loopback address. + fn loopback_addr(ep: &Endpoint) -> EndpointAddr { + EndpointAddr::from_parts( + ep.id(), + ep.bound_sockets().iter().map(|addr| { + let ip = if addr.ip().is_unspecified() { + Ipv4Addr::LOCALHOST.into() + } else { + addr.ip() + }; + TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) + }), + ) + } + + /// Serve `payload` as the response on the first stream `server` accepts. + fn serve_once(server: Endpoint, payload: Vec) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + let incoming = server.accept().await.expect("incoming"); + let conn = incoming.await.expect("connecting"); + let (mut send, mut recv) = conn.accept_bi().await.expect("accept_bi"); + let _req = recv.read_to_end(1024).await.expect("read request"); + send.write_all(&payload).await.expect("write payload"); + send.finish().expect("finish"); + conn.closed().await; + }) + } + + /// Accept and read one request, then leave the response stream open. + fn serve_silently(server: Endpoint) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + let incoming = server.accept().await.expect("incoming"); + let conn = incoming.await.expect("connecting"); + let (_send, mut recv) = conn.accept_bi().await.expect("accept_bi"); + let _req = recv.read_to_end(1024).await.expect("read request"); + tokio::time::sleep(Duration::from_secs(5)).await; + }) + } + + #[tokio::test(flavor = "multi_thread")] + async fn silent_peer_response_times_out() { + let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); + let client = endpoint(vec![]).await.unwrap(); + let silent = serve_silently(server.clone()); + let conn = client + .connect(loopback_addr(&server), TEST_ALPN) + .await + .unwrap(); + + let err = request_over_with_timeout(&conn, &MetaRequest::List, Duration::from_millis(100)) + .await + .unwrap_err(); + assert!(err.to_string().contains("timed out after")); + assert!(err.to_string().contains("waiting for a meta response")); + + conn.close(0u32.into(), b"done"); + silent.abort(); + client.close().await; + server.close().await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn silent_peer_capped_read_times_out() { + let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); + let client = endpoint(vec![]).await.unwrap(); + let silent = serve_silently(server.clone()); + let conn = client + .connect(loopback_addr(&server), TEST_ALPN) + .await + .unwrap(); + let (mut send, mut recv) = conn.open_bi().await.unwrap(); + send.write_all(&postcard::to_allocvec(&MetaRequest::List).unwrap()) + .await + .unwrap(); + send.finish().unwrap(); + + let err = read_capped_response_with_timeout(&mut recv, Duration::from_millis(100)) + .await + .unwrap_err(); + assert!(err.to_string().contains("timed out after")); + assert!(err.to_string().contains("reading a meta response")); + + conn.close(0u32.into(), b"done"); + silent.abort(); + client.close().await; + server.close().await; + } + + /// Send one request to `server` and read the response with + /// [`read_capped_response`], exactly as the remote-find paths do. + async fn round_trip(server: &Endpoint, client: &Endpoint) -> Result> { + let conn = client.connect(loopback_addr(server), TEST_ALPN).await?; + let (mut send, mut recv) = conn.open_bi().await?; + send.write_all(b"find").await?; + send.finish()?; + let buf = read_capped_response(&mut recv).await; + conn.close(0u32.into(), b"done"); + buf + } + + /// #1617: a find response past the old 64 KiB per-site bound must read + /// through the shared cap intact — 2,000 matches at ~45 wire bytes each + /// is ~90 KiB, comfortably past the old bound and under the shared one. + #[tokio::test(flavor = "multi_thread")] + async fn find_response_larger_than_64_kib_reads_through() { + let matches: Vec = (0..2_000) + .map(|i| FindMatch { + hash: Hash::from_bytes([7u8; 32]), + name: format!("found-{i:04}.txt"), + kind: MatchKind::Contains, + is_hash_match: false, + }) + .collect(); + let payload = postcard::to_allocvec(&MetaResponse::Find { matches }).unwrap(); + assert!( + payload.len() > 64 * 1024, + "payload {} bytes must exceed the old 64 KiB bound", + payload.len() + ); + + let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); + let client = endpoint(vec![]).await.unwrap(); + let served = serve_once(server.clone(), payload); + let buf = round_trip(&server, &client).await.unwrap(); + served.await.unwrap(); + client.close().await; + server.close().await; + + let resp: MetaResponse = postcard::from_bytes(&buf).unwrap(); + match resp { + MetaResponse::Find { matches } => assert_eq!(matches.len(), 2_000), + _ => panic!("unexpected response"), + } + } + + /// #1761: a List response past the hand-rolled 1 MiB bound the CLI, + /// REPL, peers and serve-probe paths used to apply must read through + /// the shared cap intact — 30,000 items at ~50 wire bytes each is + /// ~1.5 MiB, past the old bound and under the shared one. This is + /// the shape of store (15–25k items) that could not be listed at all. + #[tokio::test(flavor = "multi_thread")] + async fn list_response_larger_than_1_mib_reads_through() { + let items: Vec = (0..30_000) + .map(|i| ListEntry { + hash: Hash::from_bytes([9u8; 32]), + name: format!("file-{i:05}.txt"), + origin: None, + uploaded_at: None, + }) + .collect(); + let payload = postcard::to_allocvec(&MetaResponse::List { items }).unwrap(); + assert!( + payload.len() > 1024 * 1024, + "payload {} bytes must exceed the old 1 MiB bound", + payload.len() + ); + + let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); + let client = endpoint(vec![]).await.unwrap(); + let served = serve_once(server.clone(), payload); + let buf = round_trip(&server, &client).await.unwrap(); + served.await.unwrap(); + client.close().await; + server.close().await; + + let resp: MetaResponse = postcard::from_bytes(&buf).unwrap(); + match resp { + MetaResponse::List { items } => { + assert_eq!(items.len(), 30_000); + assert_eq!(items[29_999].name, "file-29999.txt"); + } + _ => panic!("unexpected response"), + } + } + + /// A response past the shared cap must fail by name — the limit and its + /// size — not as noq's bare "stream too long". + #[test] + fn over_cap_error_names_the_limit() { + let err = capped_response_error(ReadToEndError::TooLong); + let msg = format!("{err}"); + assert_eq!( + msg, + format!("response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit"), + "the message must be exactly the named limit, with no leftover placeholder text" + ); + } +} diff --git a/pkgs/id/crates/id-sync/src/protocol.rs b/pkgs/id/crates/id-sync/src/protocol.rs new file mode 100644 index 0000000000..60814a23bf --- /dev/null +++ b/pkgs/id/crates/id-sync/src/protocol.rs @@ -0,0 +1,1690 @@ +//! Network protocol types for remote node communication. +//! +//! This module defines the custom "meta" protocol used for peer-to-peer +//! metadata operations beyond basic blob transfer. While Iroh handles +//! blob content via its built-in protocol, this meta protocol enables: +//! +//! - **Tag management**: Create, list, delete, rename, and copy tags on remote nodes +//! - **Search operations**: Find blobs by name or hash with fuzzy matching +//! - **Metadata queries**: List all stored items on a remote node +//! - **Peer discovery**: Query a node's known peers from gossip-based discovery +//! +//! # Protocol Architecture +//! +//! ```text +//! ┌─────────────┐ ┌─────────────┐ +//! │ Client │ │ Server │ +//! │ │ │ │ +//! │ MetaRequest├───── QUIC ────────►│MetaProtocol │ +//! │ │ (postcard) │ handler │ +//! │ │◄───────────────────┤ │ +//! │ MetaResponse│ │ │ +//! └─────────────┘ └─────────────┘ +//! ``` +//! +//! Messages are serialized using [postcard](https://docs.rs/postcard) for +//! compact binary encoding. Each connection can handle multiple request/response +//! pairs using bidirectional QUIC streams. +//! +//! # Protocol Identifier +//! +//! The meta protocol uses the ALPN identifier defined in [`META_ALPN`]: +//! `b"/iroh-meta/3"`. This allows nodes to negotiate the correct protocol handler. +//! +//! # Usage Example +//! +//! ```rust,ignore +//! use id_sync::protocol::{MetaRequest, MetaResponse}; +//! +//! // Create a request to find files matching "config" +//! let request = MetaRequest::Find { +//! query: "config".to_string(), +//! prefer_name: true, +//! }; +//! +//! // Serialize and send over QUIC connection +//! let bytes = postcard::to_allocvec(&request)?; +//! send_stream.write_all(&bytes).await?; +//! +//! // Read and deserialize response +//! let response_bytes = recv_stream.read_to_end(64 * 1024).await?; +//! let response: MetaResponse = postcard::from_bytes(&response_bytes)?; +//! ``` +//! +//! # Match Quality +//! +//! Search operations return results ranked by [`MatchKind`]: +//! - [`MatchKind::Exact`]: Query exactly equals the name/hash (best) +//! - [`MatchKind::Prefix`]: Name/hash starts with query (good) +//! - [`MatchKind::Contains`]: Name/hash contains query anywhere (okay) + +use std::{sync::Arc, time::Duration}; + +use futures_lite::StreamExt; +use iroh::endpoint::Connection; +use iroh::protocol::{AcceptError, ProtocolHandler}; +use iroh_base::EndpointId; +use iroh_blobs::{Hash, api::Store}; +use serde::{Deserialize, Serialize}; +use tokio::{sync::Semaphore, task::JoinSet}; + +use id_core::access::AccessPolicy; +use id_core::discovery::{PeerAnnouncement, PeerDiscovery}; +use crate::fileops::{FileOpError, FileOps}; +use id_store::tags::TagStore; + +/// Decode exactly one meta-protocol value, rejecting any trailing bytes. +/// +/// Meta requests and responses are one-message-per-stream. Accepting a valid +/// postcard prefix would let a padded or concatenated stream be interpreted as +/// a different, complete message. +pub fn decode_meta_exact(bytes: &[u8]) -> anyhow::Result { + let (value, rest) = postcard::take_from_bytes(bytes)?; + anyhow::ensure!( + rest.is_empty(), + "trailing bytes after meta-protocol value ({} bytes)", + rest.len() + ); + Ok(value) +} + +/// Maximum time for one network phase (request read or response write) of a +/// meta stream. The phases are bounded separately on purpose: once a request +/// has been fully read, its handler runs to completion, so the deadline can +/// never cancel a non-transactional mutation (e.g. a rename) midway through. +const META_STREAM_DEADLINE: Duration = Duration::from_secs(60); + +/// Concurrent meta requests allowed on one connection. +pub const MAX_META_STREAMS_PER_CONNECTION: usize = 16; + +/// Match quality for find/search operations. +/// +/// Represents how closely a search query matches a blob's name or hash. +/// The variants are ordered by quality, with [`Exact`](MatchKind::Exact) +/// being the best match. +/// +/// # Ordering +/// +/// `MatchKind` implements `Ord` such that better matches compare less: +/// +/// ```rust +/// use id_sync::protocol::MatchKind; +/// +/// assert!(MatchKind::Exact < MatchKind::Prefix); +/// assert!(MatchKind::Prefix < MatchKind::Contains); +/// ``` +/// +/// This allows sorting search results by quality using the natural ordering. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum MatchKind { + /// Query exactly equals the target string. + /// + /// For example, query "config.json" matches name "config.json" exactly. + Exact, + /// Target string starts with the query. + /// + /// For example, query "config" matches name "config.json" as a prefix. + Prefix, + /// Target string contains the query somewhere. + /// + /// For example, query "fig" matches name "config.json" as contained. + Contains, +} + +/// Determines how a search query matches a string. +/// +/// This function implements a priority-based matching system: +/// 1. **Exact**: The strings are identical +/// 2. **Prefix**: The haystack starts with the needle +/// 3. **Contains**: The haystack contains the needle somewhere +/// +/// # Arguments +/// +/// * `haystack` - The string to search within (e.g., filename or hash) +/// * `needle` - The search query +/// +/// # Returns +/// +/// * `Some(MatchKind::Exact)` if `haystack == needle` +/// * `Some(MatchKind::Prefix)` if `haystack.starts_with(needle)` +/// * `Some(MatchKind::Contains)` if `haystack.contains(needle)` +/// * `None` if no match +/// +/// # Example +/// +/// ```rust +/// use id_sync::protocol::{match_kind, MatchKind}; +/// +/// assert_eq!(match_kind("hello.txt", "hello.txt"), Some(MatchKind::Exact)); +/// assert_eq!(match_kind("hello.txt", "hello"), Some(MatchKind::Prefix)); +/// assert_eq!(match_kind("say-hello.txt", "hello"), Some(MatchKind::Contains)); +/// assert_eq!(match_kind("world.txt", "hello"), None); +/// ``` +pub fn match_kind(haystack: &str, needle: &str) -> Option { + if haystack == needle { + Some(MatchKind::Exact) + } else if haystack.starts_with(needle) { + Some(MatchKind::Prefix) + } else if haystack.contains(needle) { + Some(MatchKind::Contains) + } else { + None + } +} + +/// A single match result from find/search operations. +/// +/// Represents one blob that matched a search query, including metadata +/// about how well it matched and whether the match was against the +/// blob's name or its hash. +/// +/// # Example +/// +/// ```rust +/// use id_sync::protocol::{FindMatch, MatchKind}; +/// use iroh_blobs::Hash; +/// +/// let m = FindMatch { +/// hash: Hash::from_bytes([0u8; 32]), +/// name: "example.txt".to_string(), +/// kind: MatchKind::Exact, +/// is_hash_match: false, +/// }; +/// +/// // This was a name match, not a hash match +/// assert!(!m.is_hash_match); +/// ``` +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FindMatch { + /// The content hash of the matched blob. + pub hash: Hash, + /// The tag name associated with this blob. + pub name: String, + /// How well the query matched (exact, prefix, or contains). + pub kind: MatchKind, + /// Whether the match was against the hash (`true`) or name (`false`). + /// + /// When searching, both the name and hash are checked. This field + /// indicates which one matched the query, useful for understanding + /// the search result context. + pub is_hash_match: bool, +} + +/// A match result tagged with the query that produced it. +/// +/// When searching with multiple queries, this struct associates each +/// match with the specific query that found it. This is used internally +/// for grouping and formatting multi-query search results. +/// +/// # Example +/// +/// ```rust +/// use id_sync::protocol::{TaggedMatch, MatchKind}; +/// use iroh_blobs::Hash; +/// +/// let m = TaggedMatch { +/// query: "config".to_string(), +/// hash: Hash::from_bytes([0u8; 32]), +/// name: "config.json".to_string(), +/// kind: MatchKind::Prefix, +/// is_hash_match: false, +/// }; +/// +/// // The query "config" matched "config.json" as a prefix +/// assert_eq!(m.query, "config"); +/// assert_eq!(m.kind, MatchKind::Prefix); +/// ``` +#[derive(Debug, Clone)] +pub struct TaggedMatch { + /// The search query that produced this match. + pub query: String, + /// The content hash of the matched blob. + pub hash: Hash, + /// The tag name associated with this blob. + pub name: String, + /// How well the query matched. + pub kind: MatchKind, + /// Whether the match was against the hash or name. + pub is_hash_match: bool, +} + +/// Requests that can be sent to a remote node via the meta protocol. +/// +/// Each variant represents an operation that can be performed on a remote +/// node's blob store. The request is serialized with postcard and sent +/// over a QUIC bidirectional stream. +/// +/// # Serialization +/// +/// All variants are serializable for network transmission: +/// +/// ```rust +/// use id_sync::protocol::MetaRequest; +/// use iroh_blobs::Hash; +/// +/// let req = MetaRequest::List; +/// let bytes = postcard::to_allocvec(&req).unwrap(); +/// let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); +/// ``` +/// A metadata tag as carried on the wire. +/// +/// Subject, key and value are raw bytes. The tag store is binary-safe, and the +/// v2 wire format no longer forces a lossy UTF-8 conversion on the way out. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WireTag { + /// The subject (usually a filename). + pub subject: Vec, + /// The tag key. + pub key: Vec, + /// The tag value, `None` for key-only tags. + pub value: Option>, +} + +impl WireTag { + /// Build a wire tag from UTF-8 strings (convenience for callers and tests). + pub fn from_strs(subject: &str, key: &str, value: Option<&str>) -> Self { + Self { + subject: subject.as_bytes().to_vec(), + key: key.as_bytes().to_vec(), + value: value.map(|v| v.as_bytes().to_vec()), + } + } +} + +impl From for WireTag { + fn from(t: id_store::tags::Tag) -> Self { + Self { + subject: t.subject.into_bytes(), + key: t.key.into_bytes(), + value: t.value.map(id_store::tags::TagValue::into_bytes), + } + } +} + +/// Maximum size of a single request on the meta protocol (1 MiB). +pub const MAX_REQUEST_BYTES: usize = 1024 * 1024; + +/// Application-Level Protocol Negotiation (ALPN) identifier for the meta protocol. +/// +/// Used during QUIC handshake to identify connections for metadata operations +/// (list, find, delete, rename, etc.) as opposed to blob data transfer. +/// +/// **Version 2** carries tag keys/values as raw bytes (binary-safe), defines +/// `DelTag` with no value as "delete every value of the key", and adds `Whoami` +/// and `Error`. It is not wire-compatible with `/iroh-meta/1`; the ALPN bump +/// makes old and new nodes fail the handshake cleanly instead of mis-decoding. +/// +/// **Version 3** changes the `List` response item from `(hash, name)` pairs +/// to `ListEntry` records carrying the file's origin node and upload time +/// (#4973). That payload change is not wire-compatible with `/iroh-meta/2` +/// under postcard, so it takes this ALPN bump per the rule below. +/// +/// Compatibility rule: within a version, only **append** enum variants. Any +/// other change to [`protocol::MetaRequest`] / [`protocol::MetaResponse`] +/// requires a new ALPN. `protocol::tests` pins every discriminant. +pub const META_ALPN: &[u8] = b"/iroh-meta/3"; + +/// How long a server waits for a just-pushed blob to finish arriving before a +/// `Put` naming it is refused. +pub const DEFAULT_BLOB_WAIT: std::time::Duration = std::time::Duration::from_secs(5); + +/// Requests to a remote node via the meta protocol (`/iroh-meta/3`). +/// +/// **Compatibility rule:** postcard encodes enum variants by position. Within +/// a protocol version, new variants may only be *appended*; reordering, +/// inserting or changing a payload requires a new ALPN. The +/// `wire_format_is_pinned` test fixes every discriminant. +#[derive(Debug, Serialize, Deserialize)] +pub enum MetaRequest { + /// Create or update a name on the remote node. + /// + /// Associates `filename` with `hash`. The blob content must already be on + /// the remote (push it via the blobs protocol *first*): the server verifies + /// the blob is present and refuses to create a dangling name. + Put { + /// The tag name to create or update. + filename: String, + /// The content hash to associate with this tag. + hash: Hash, + }, + /// Look up a name on the remote node, returning its hash if it exists. + Get { + /// The tag name to look up. + filename: String, + }, + /// List all names on the remote node as (hash, name) pairs. + List, + /// Delete a name from the remote node (hard delete). + /// + /// Removes the name, its metadata tags and its archive tags. The blob + /// bytes remain until garbage collected. + Delete { + /// The tag name to delete. + filename: String, + }, + /// Rename a file on the remote node. + /// + /// Metadata follows the file; a file replaced at the destination and the + /// original name are archived as `.archive.`. + Rename { + /// The current tag name. + from: String, + /// The new tag name. + to: String, + }, + /// Copy a file on the remote node. + /// + /// Creates `to` pointing at the same hash and duplicates the metadata. + Copy { + /// The source tag name. + from: String, + /// The destination tag name. + to: String, + }, + /// Search for names and hashes matching a query, ranked by match quality. + Find { + /// The search query (matched case-insensitively). + query: String, + /// If `true`, prioritize name matches over hash matches in results. + prefer_name: bool, + }, + /// Set a metadata tag (global namespace). + SetTag { + /// The subject (usually a filename) to tag. + subject: Vec, + /// The tag key (e.g. "author", "status"). + key: Vec, + /// Optional tag value (arbitrary bytes). + value: Option>, + }, + /// Delete metadata tags (global namespace). + DelTag { + /// The subject (usually a filename). + subject: Vec, + /// The tag key to delete. + key: Vec, + /// A specific value to delete. `None` deletes **every** tag with this + /// subject and key (including a value-less key-only tag). + value: Option>, + }, + /// List metadata tags for a subject (or every tag when `None`). + GetTags { + /// The subject (filename) to list tags for. `None` = list all. + subject: Option>, + }, + /// Search metadata tags with the structured query syntax. + /// + /// Supports `key:`, `:value`, `key:value`, `"literal"` and bare words; + /// multiple terms are `AND`ed. + SearchTags { + /// The search query string. + query: String, + }, + /// Add `name`/`file` auto-tags to every blob name that lacks them. + MigrateTags, + /// Request the peers this node has discovered via gossip. + ListPeers, + /// Ask the node who it is and whether the caller may write to it. + /// + /// Lets clients give an actionable error instead of an opaque failure when + /// a write is refused. + Whoami, + /// Read the node's per-(local node, remote endpoint) frame/byte abuse + /// counters, split by direction, plus the policy rates that produced them. + /// + /// Read-only. The counters cover world-protocol traffic admitted + /// by the node's abuse evaluator; a node with no evaluator attached + /// (a plain serve without a world, or a build without the world + /// feature) records none and answers with an empty report. + AbuseCounters, +} + +impl MetaRequest { + /// Whether this request mutates the store (and therefore needs write access). + pub const fn is_write(&self) -> bool { + matches!( + self, + Self::Put { .. } + | Self::Delete { .. } + | Self::Rename { .. } + | Self::Copy { .. } + | Self::SetTag { .. } + | Self::DelTag { .. } + | Self::MigrateTags + ) + } +} + +/// Responses from a remote node via the meta protocol. +/// +/// Each variant corresponds to a [`MetaRequest`] variant. Any request may also +/// be answered with [`MetaResponse::Error`]. The same append-only rule as +/// [`MetaRequest`] applies. +/// One entry of a [`MetaResponse::List`] response (#4973). +/// +/// `origin` is the node that first wrote the file, recorded by the +/// `origin` metadata tag at write time; `uploaded_at` is the file's +/// upload time (unix seconds) from its `created` tag. Files written +/// before those tags existed carry `None` for both and list with +/// origin unknown — the values are never guessed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ListEntry { + /// The content hash. + pub hash: Hash, + /// The tag name. + pub name: String, + /// Node id of the file's origin node, if recorded. + pub origin: Option, + /// Upload time (unix seconds), if recorded. + pub uploaded_at: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +pub enum MetaResponse { + /// Response to [`MetaRequest::Put`]. + Put { + /// Whether the name was created/updated. + success: bool, + }, + /// Response to [`MetaRequest::Get`]. + Get { + /// The hash if found, or `None` if the name doesn't exist. + hash: Option, + }, + /// Response to [`MetaRequest::List`]. + List { + /// All names with their origin node and upload time (#4973). + items: Vec, + }, + /// Response to [`MetaRequest::Delete`]. + Delete { + /// Whether the name existed and was deleted. + success: bool, + }, + /// Response to [`MetaRequest::Rename`]. + Rename { + /// Whether the rename succeeded. + success: bool, + }, + /// Response to [`MetaRequest::Copy`]. + Copy { + /// Whether the copy succeeded. + success: bool, + }, + /// Response to [`MetaRequest::Find`]. + Find { + /// Matches, sorted by match quality. + matches: Vec, + }, + /// Response to [`MetaRequest::SetTag`]. + SetTag { + /// Whether the tag was set. + success: bool, + }, + /// Response to [`MetaRequest::DelTag`]. + DelTag { + /// Whether at least one tag was deleted. + success: bool, + /// How many tags were deleted. + deleted: u32, + }, + /// Response to [`MetaRequest::GetTags`]. + GetTags { + /// The matching tags. + tags: Vec, + }, + /// Response to [`MetaRequest::SearchTags`]. + SearchTags { + /// The matching tags. + tags: Vec, + }, + /// Response to [`MetaRequest::MigrateTags`]. + MigrateTags { + /// Number of subjects that were updated with auto-tags. + migrated: usize, + }, + /// Response to [`MetaRequest::ListPeers`]. + ListPeers { + /// Known peers as announcements. Empty if peer discovery is off. + peers: Vec, + }, + /// Response to [`MetaRequest::Whoami`]. + Whoami { + /// The responding node's ID. + node_id: EndpointId, + /// The responding node's `id` version. + version: String, + /// Whether the *caller* may perform mutating requests. + can_write: bool, + /// Whether the node lets every peer write. + open_writes: bool, + }, + /// The request was refused or failed; `message` explains why. + Error { + /// Human-readable reason. + message: String, + }, + /// Response to [`MetaRequest::AbuseCounters`]. + AbuseCounters { + /// One row per (local node, remote endpoint), already sorted by + /// local node then remote endpoint. + rows: Vec, + /// The policy rates the counters are charged against, or `None` + /// when the node exposes counters without a policy view. + policy: Option, + }, +} + +/// One row of [`MetaResponse::AbuseCounters`]: the frame and byte counters +/// admitted for one (local node, remote endpoint) pair, split by direction. +/// +/// `unattributed` holds traffic admitted through a check that does not know +/// its direction; it is never guessed into `inbound` or `outbound`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AbuseCountersRow { + /// The local node's ID (32-byte verifying key). + pub local: [u8; 32], + /// The remote endpoint's ID (32-byte verifying key). + pub remote: [u8; 32], + /// Frames admitted inbound. + pub inbound_frames: u64, + /// Bytes admitted inbound. + pub inbound_bytes: u64, + /// Frames admitted outbound. + pub outbound_frames: u64, + /// Bytes admitted outbound. + pub outbound_bytes: u64, + /// Frames admitted without a known direction. + pub unattributed_frames: u64, + /// Bytes admitted without a known direction. + pub unattributed_bytes: u64, +} + +/// The authorized token-bucket policy rates shown alongside +/// [`AbuseCountersRow`]s. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct AbusePolicyView { + /// Authorized frames admitted per second. + pub frames_per_sec: u64, + /// Authorized frame burst. + pub frame_burst: u64, + /// Authorized bytes admitted per second. + pub bytes_per_sec: u64, + /// Authorized byte burst. + pub byte_burst: u64, +} + +impl MetaResponse { + /// If this is an [`MetaResponse::Error`], return its message. + pub fn error_message(&self) -> Option<&str> { + match self { + Self::Error { message } => Some(message), + _ => None, + } + } +} + +/// Protocol handler for the meta protocol. +/// +/// Implements Iroh's [`ProtocolHandler`] trait. When a remote node connects +/// with [`META_ALPN`], each bidirectional stream carries one +/// [`MetaRequest`] and is answered with one [`MetaResponse`]. Mutating +/// requests are checked against the [`AccessPolicy`] using the authenticated +/// identity of the connection. +/// +/// ```text +/// Connection opened → identity = conn.remote_id() +/// ↓ +/// Accept bidirectional stream +/// ↓ +/// Read request → authorize (writes) → handle → send response +/// ↓ +/// Loop until connection closed +/// ``` +#[derive(Clone, Debug)] +pub struct MetaProtocol { + /// The blob store used for name operations. + pub store: Store, + /// Optional peer discovery table for the `ListPeers` RPC. + pub peer_discovery: Option, + /// Metadata tag store (iroh-docs backed). + pub tag_store: Arc, + /// Who may perform mutating requests. + pub access: AccessPolicy, + /// This node's ID (reported by `Whoami`). + pub node_id: EndpointId, + /// How long a `Put` waits for a blob that is still arriving (see + /// [`FileOps::with_blob_wait`]). Zero for in-process use. + pub blob_wait: std::time::Duration, + /// The node's abuse evaluator, when this surface exposes it. `None` + /// answers [`MetaRequest::AbuseCounters`] with an empty report. + pub abuse: Option>>, +} + +impl MetaProtocol { + /// Creates a new meta protocol handler. + /// + /// Returns an `Arc` for registration with Iroh's router. + pub fn new( + store: &Store, + peer_discovery: Option, + tag_store: Arc, + access: AccessPolicy, + node_id: EndpointId, + abuse: Option>>, + ) -> Arc { + Arc::new(Self { + store: store.clone(), + peer_discovery, + tag_store, + access, + node_id, + blob_wait: DEFAULT_BLOB_WAIT, + abuse, + }) + } + + /// Handle one request on behalf of `remote` and produce the response. + /// + /// This is the whole server-side behaviour of the protocol, independent of + /// QUIC, so it can be exercised directly in tests. + pub async fn handle(&self, remote: &EndpointId, req: MetaRequest) -> MetaResponse { + if req.is_write() && !self.access.can_write(remote) { + return MetaResponse::Error { + message: format!( + "permission denied: node {remote} may not modify this store \ + (ask the owner to run `id serve --allow-node {remote}`)" + ), + }; + } + let ops = FileOps::new(&self.store, &self.tag_store) + .with_blob_wait(self.blob_wait) + .with_origin(remote.to_string()); + let ts = &self.tag_store; + let ns = &ts.global; + match req { + MetaRequest::Put { filename, hash } => match ops.put(&filename, hash).await { + Ok(()) => MetaResponse::Put { success: true }, + Err(e) => MetaResponse::Error { + message: e.to_string(), + }, + }, + MetaRequest::Get { filename } => { + let hash = self + .store + .tags() + .get(&filename) + .await + .ok() + .flatten() + .map(|t| t.hash); + MetaResponse::Get { hash } + } + MetaRequest::List => { + let mut items = Vec::new(); + if let Ok(mut list) = self.store.tags().list().await { + while let Some(Ok(item)) = list.next().await { + let name = String::from_utf8_lossy(item.name.as_ref()).into_owned(); + items.push(ListEntry { + hash: item.hash, + name, + origin: None, + uploaded_at: None, + }); + } + } + // Enrich with origin + upload time from the metadata tags + // (#4973): `origin` is stamped at write time by FileOps, + // `created` is the upload time. Files written before the + // tags existed keep `None` and list as origin unknown. + if let Ok(tags) = self.tag_store.list_all(ns).await { + let mut origins: std::collections::HashMap = + std::collections::HashMap::new(); + let mut created: std::collections::HashMap = + std::collections::HashMap::new(); + for tag in &tags { + if tag.key == "origin" { + if let Some(value) = tag.value.as_ref().and_then(|v| v.as_str()) { + origins.insert(tag.subject.display_lossy(), value.to_owned()); + } + } else if tag.key == "created" + && let Some(ts) = tag + .value + .as_ref() + .and_then(|v| v.as_str()) + .and_then(|v| v.parse::().ok()) + { + created.insert(tag.subject.display_lossy(), ts); + } + } + for item in &mut items { + item.origin = origins.get(&item.name).cloned(); + item.uploaded_at = created.get(&item.name).copied(); + } + } + MetaResponse::List { items } + } + MetaRequest::Delete { filename } => match ops.delete(&filename).await { + Ok(outcome) => MetaResponse::Delete { + success: outcome.existed, + }, + Err(e) => MetaResponse::Error { + message: e.to_string(), + }, + }, + MetaRequest::Rename { from, to } => match ops.rename(&from, &to, true).await { + Ok(_) => MetaResponse::Rename { success: true }, + Err(FileOpError::NotFound(_)) => MetaResponse::Rename { success: false }, + Err(e) => MetaResponse::Error { + message: e.to_string(), + }, + }, + MetaRequest::Copy { from, to } => match ops.copy(&from, &to).await { + Ok(_) => MetaResponse::Copy { success: true }, + Err(FileOpError::NotFound(_)) => MetaResponse::Copy { success: false }, + Err(e) => MetaResponse::Error { + message: e.to_string(), + }, + }, + MetaRequest::Find { query, prefer_name } => MetaResponse::Find { + matches: self.find(&query, prefer_name).await, + }, + MetaRequest::SetTag { + subject, + key, + value, + } => match ts.set_tag(ns, &subject, &key, value.as_deref(), b"").await { + Ok(()) => MetaResponse::SetTag { success: true }, + Err(e) => MetaResponse::Error { + message: format!("{e:#}"), + }, + }, + MetaRequest::DelTag { + subject, + key, + value, + } => match ts + .delete_matching(ns, &subject, &key, value.as_deref()) + .await + { + Ok(n) => MetaResponse::DelTag { + success: n > 0, + deleted: u32::try_from(n).unwrap_or(u32::MAX), + }, + Err(e) => MetaResponse::Error { + message: format!("{e:#}"), + }, + }, + MetaRequest::GetTags { subject } => { + let result = match &subject { + Some(s) => ts.get_tags(ns, s).await, + None => ts.list_all(ns).await, + }; + match result { + Ok(list) => MetaResponse::GetTags { + tags: list.into_iter().map(WireTag::from).collect(), + }, + Err(e) => MetaResponse::Error { + message: format!("{e:#}"), + }, + } + } + MetaRequest::SearchTags { query } => match ts.search_by_query(ns, &query).await { + Ok(list) => MetaResponse::SearchTags { + tags: list.into_iter().map(WireTag::from).collect(), + }, + Err(e) => MetaResponse::Error { + message: format!("{e:#}"), + }, + }, + MetaRequest::MigrateTags => match ts.migrate_tags(&self.store, ns).await { + Ok(migrated) => MetaResponse::MigrateTags { migrated }, + Err(e) => MetaResponse::Error { + message: format!("{e:#}"), + }, + }, + MetaRequest::ListPeers => { + let peers = self + .peer_discovery + .as_ref() + .map(|pd| pd.peers().into_iter().map(|pi| pi.announcement).collect()) + .unwrap_or_default(); + MetaResponse::ListPeers { peers } + } + MetaRequest::Whoami => MetaResponse::Whoami { + node_id: self.node_id, + version: env!("CARGO_PKG_VERSION").to_owned(), + can_write: self.access.can_write(remote), + open_writes: self.access.is_open(), + }, + MetaRequest::AbuseCounters => { + // No evaluator attached means no world traffic is recorded: + // answer the empty report, not an error, so + // `id peers --abuse` against a plain serve succeeds. + let Some(abuse) = &self.abuse else { + return MetaResponse::AbuseCounters { + rows: Vec::new(), + policy: None, + }; + }; + // Copy the counters and the policy out under the lock, then + // release it before sorting and building rows: that work + // must not block world frame charges on the evaluator. + let (mut snapshot, authorized) = { + let Ok(guard) = abuse.lock() else { + return MetaResponse::Error { + message: + "abuse counters are unavailable: the evaluator lock is poisoned" + .to_owned(), + }; + }; + ( + guard.counters().copied_directional(), + guard.policy().authorized, + ) + }; + snapshot.sort_by(|a, b| a.0.cmp(&b.0)); + let rows = snapshot + .into_iter() + .map(|((local, remote), counters)| AbuseCountersRow { + local, + remote, + inbound_frames: counters.inbound.frames, + inbound_bytes: counters.inbound.bytes, + outbound_frames: counters.outbound.frames, + outbound_bytes: counters.outbound.bytes, + unattributed_frames: counters.unattributed.frames, + unattributed_bytes: counters.unattributed.bytes, + }) + .collect(); + MetaResponse::AbuseCounters { + rows, + policy: Some(AbusePolicyView { + frames_per_sec: authorized.frames_per_sec, + frame_burst: authorized.frame_burst, + bytes_per_sec: authorized.bytes_per_sec, + byte_burst: authorized.byte_burst, + }), + } + } + } + } + + /// Rank blob names and hashes against `query`. + async fn find(&self, query: &str, prefer_name: bool) -> Vec { + let mut matches = Vec::new(); + let query_lower = query.to_lowercase(); + if let Ok(mut list) = self.store.tags().list().await { + while let Some(Ok(item)) = list.next().await { + let name = String::from_utf8_lossy(item.name.as_ref()).into_owned(); + let hash_str = item.hash.to_string(); + if let Some(kind) = match_kind(&name.to_lowercase(), &query_lower) { + matches.push(FindMatch { + hash: item.hash, + name, + kind, + is_hash_match: false, + }); + } else if let Some(kind) = match_kind(&hash_str, &query_lower) { + matches.push(FindMatch { + hash: item.hash, + name, + kind, + is_hash_match: true, + }); + } + } + } + // Best kind first; ties prefer name matches (`prefer_name`) or hash matches. + matches.sort_by(|a, b| { + a.kind.cmp(&b.kind).then_with(|| { + if prefer_name { + a.is_hash_match.cmp(&b.is_hash_match) + } else { + b.is_hash_match.cmp(&a.is_hash_match) + } + }) + }); + matches + } + + pub async fn accept_connection( + &self, + conn: Connection, + stream_deadline: Duration, + ) -> Result<(), AcceptError> { + let remote = conn.remote_id(); + let permits = Arc::new(Semaphore::new(MAX_META_STREAMS_PER_CONNECTION)); + let mut streams = JoinSet::new(); + + loop { + tokio::select! { + incoming = conn.accept_bi() => { + let Ok((mut send, recv)) = incoming else { + break; + }; + let Ok(permit) = Arc::clone(&permits).try_acquire_owned() else { + // Refuse only this stream; the connection remains usable. + let _ = send.reset(1_u32.into()); + continue; + }; + let protocol = self.clone(); + streams.spawn(async move { + let _permit = permit; + protocol + .handle_stream(remote, send, recv, stream_deadline) + .await; + }); + } + Some(result) = streams.join_next(), if !streams.is_empty() => { + if let Err(error) = result { + tracing::warn!(%error, "meta stream handler task failed"); + } + } + } + } + + // The peer closed the connection. Drain admitted handlers instead + // of aborting them: shutdown() would cancel a handler at its next + // suspension point, and a mutating handler cancelled mid-flight + // (e.g. FileOps::rename, which deletes the source before awaiting + // the metadata transfer) can leave partial state behind. Each + // handler's network phases stay bounded by the stream deadline, + // so this drain terminates. + while let Some(result) = streams.join_next().await { + if let Err(error) = result { + tracing::warn!(%error, "meta stream handler task failed"); + } + } + Ok(()) + } + + async fn handle_stream( + &self, + remote: EndpointId, + mut send: iroh::endpoint::SendStream, + mut recv: iroh::endpoint::RecvStream, + stream_deadline: Duration, + ) { + // Phase 1: read the request under the deadline. A stalled or + // trickling peer is cut off here, without affecting other streams. + let buf = match tokio::time::timeout(stream_deadline, recv.read_to_end(MAX_REQUEST_BYTES)) + .await + { + Ok(Ok(buf)) => buf, + Ok(Err(error)) => { + tracing::debug!(%remote, %error, "meta stream read failed"); + return; + } + Err(_) => { + tracing::debug!(%remote, ?stream_deadline, "meta stream read deadline exceeded"); + let _ = send.reset(1_u32.into()); + return; + } + }; + + // Phase 2: handle the admitted request to completion. This is + // deliberately NOT wrapped in the deadline: handlers perform + // non-transactional mutations (e.g. FileOps::rename moves a blob and + // then transfers metadata), and cancelling one midway would corrupt + // state. The handler does no peer-controlled waiting — the network + // phases on either side of it carry the deadline. + let resp = match decode_meta_exact::(&buf) { + Ok(req) => self.handle(&remote, req).await, + Err(error) => MetaResponse::Error { + message: format!("malformed request: {error}"), + }, + }; + + // Phase 3: write the response under the deadline; a peer that stops + // reading is cut off and its stream reset. + let written = tokio::time::timeout(stream_deadline, async { + let bytes = postcard::to_allocvec(&resp).map_err(AcceptError::from_err)?; + send.write_all(&bytes) + .await + .map_err(AcceptError::from_err)?; + send.finish()?; + Ok::<(), AcceptError>(()) + }) + .await; + + match written { + Ok(Ok(())) => {} + Ok(Err(error)) => tracing::debug!(%remote, %error, "meta stream failed"), + Err(_) => { + tracing::debug!(%remote, ?stream_deadline, "meta stream write deadline exceeded"); + let _ = send.reset(1_u32.into()); + } + } + } +} + +impl ProtocolHandler for MetaProtocol { + /// Serves requests on a connection until the peer closes it. + /// Individual stream failures are isolated; active streams are stopped when + /// the peer closes the connection. + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + self.accept_connection(conn, META_STREAM_DEADLINE).await + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use iroh::{ + EndpointAddr, + endpoint::{Endpoint, RelayMode, presets}, + protocol::Router, + }; + use iroh_base::{SecretKey, TransportAddr}; + use std::net::{Ipv4Addr, SocketAddr}; + + + #[test] + fn test_find_match_struct() { + let hash = Hash::from_bytes([0u8; 32]); + let m = FindMatch { + hash, + name: "test.txt".to_owned(), + kind: MatchKind::Exact, + is_hash_match: false, + }; + assert_eq!(m.name, "test.txt"); + assert_eq!(m.kind, MatchKind::Exact); + assert!(!m.is_hash_match); + } + + #[test] + fn test_tagged_match_struct() { + let hash = Hash::from_bytes([0u8; 32]); + let m = TaggedMatch { + query: "test".to_owned(), + hash, + name: "test.txt".to_owned(), + kind: MatchKind::Prefix, + is_hash_match: true, + }; + assert_eq!(m.query, "test"); + assert_eq!(m.kind, MatchKind::Prefix); + assert!(m.is_hash_match); + } + + #[test] + fn meta_decode_requires_full_consumption() { + let list = postcard::to_allocvec(&MetaRequest::List).unwrap(); + assert!(matches!( + decode_meta_exact::(&list), + Ok(MetaRequest::List) + )); + + let mut padded_list = list.clone(); + padded_list.push(0); + assert!(decode_meta_exact::(&padded_list).is_err()); + + let mut garbage_list = list; + garbage_list.extend_from_slice(b"GARBAGE"); + assert!(decode_meta_exact::(&garbage_list).is_err()); + + let delete = MetaRequest::Delete { + filename: "victim.txt".to_owned(), + }; + let mut padded_delete = postcard::to_allocvec(&delete).unwrap(); + padded_delete.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); + assert!(decode_meta_exact::(&padded_delete).is_err()); + + let mut double_request = postcard::to_allocvec(&delete).unwrap(); + double_request.extend_from_slice(&postcard::to_allocvec(&MetaRequest::List).unwrap()); + assert!(decode_meta_exact::(&double_request).is_err()); + + let response = MetaResponse::Delete { success: true }; + let mut padded_response = postcard::to_allocvec(&response).unwrap(); + padded_response.extend_from_slice(b"EXTRA"); + assert!(decode_meta_exact::(&padded_response).is_err()); + + assert!(matches!( + decode_meta_exact::(&postcard::to_allocvec(&response).unwrap()), + Ok(MetaResponse::Delete { success: true }) + )); + } + + #[test] + fn test_meta_request_serialization() { + // Test Put + let req = MetaRequest::Put { + filename: "test.txt".to_owned(), + hash: Hash::from_bytes([0u8; 32]), + }; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaRequest::Put { filename, .. } => assert_eq!(filename, "test.txt"), + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_request_get_serialization() { + let req = MetaRequest::Get { + filename: "myfile.txt".to_owned(), + }; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaRequest::Get { filename } => assert_eq!(filename, "myfile.txt"), + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_request_list_serialization() { + let req = MetaRequest::List; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + assert!(matches!(decoded, MetaRequest::List)); + } + + #[test] + fn test_meta_request_delete_serialization() { + let req = MetaRequest::Delete { + filename: "to_delete.txt".to_owned(), + }; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaRequest::Delete { filename } => assert_eq!(filename, "to_delete.txt"), + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_request_rename_serialization() { + let req = MetaRequest::Rename { + from: "old.txt".to_owned(), + to: "new.txt".to_owned(), + }; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaRequest::Rename { from, to } => { + assert_eq!(from, "old.txt"); + assert_eq!(to, "new.txt"); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_request_copy_serialization() { + let req = MetaRequest::Copy { + from: "source.txt".to_owned(), + to: "dest.txt".to_owned(), + }; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaRequest::Copy { from, to } => { + assert_eq!(from, "source.txt"); + assert_eq!(to, "dest.txt"); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_request_find_serialization() { + let req = MetaRequest::Find { + query: "search term".to_owned(), + prefer_name: true, + }; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaRequest::Find { query, prefer_name } => { + assert_eq!(query, "search term"); + assert!(prefer_name); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_put_serialization() { + let resp = MetaResponse::Put { success: true }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::Put { success } => assert!(success), + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_get_serialization() { + let hash = Hash::from_bytes([1u8; 32]); + let resp = MetaResponse::Get { hash: Some(hash) }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::Get { hash: h } => { + assert!(h.is_some()); + assert_eq!(h.unwrap(), hash); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_get_none_serialization() { + let resp = MetaResponse::Get { hash: None }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::Get { hash } => assert!(hash.is_none()), + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_list_serialization() { + let hash1 = Hash::from_bytes([1u8; 32]); + let hash2 = Hash::from_bytes([2u8; 32]); + let resp = MetaResponse::List { + items: vec![ + ListEntry { + hash: hash1, + name: "file1.txt".to_owned(), + origin: Some("node-a".to_owned()), + uploaded_at: Some(1_700_000_000), + }, + ListEntry { + hash: hash2, + name: "file2.txt".to_owned(), + origin: None, + uploaded_at: None, + }, + ], + }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::List { items } => { + assert_eq!(items.len(), 2); + assert_eq!(items[0].name, "file1.txt"); + assert_eq!(items[0].origin.as_deref(), Some("node-a")); + assert_eq!(items[0].uploaded_at, Some(1_700_000_000)); + assert_eq!(items[1].name, "file2.txt"); + assert_eq!(items[1].origin, None); + assert_eq!(items[1].uploaded_at, None); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_find_serialization() { + let hash = Hash::from_bytes([0u8; 32]); + let matches = vec![FindMatch { + hash, + name: "found.txt".to_owned(), + kind: MatchKind::Exact, + is_hash_match: false, + }]; + let resp = MetaResponse::Find { matches }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::Find { matches } => { + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].name, "found.txt"); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_match_kind_serialization() { + for kind in [MatchKind::Exact, MatchKind::Prefix, MatchKind::Contains] { + let bytes = postcard::to_allocvec(&kind).unwrap(); + let decoded: MatchKind = postcard::from_bytes(&bytes).unwrap(); + assert_eq!(decoded, kind); + } + } + + #[test] + fn test_find_match_serialization() { + let hash = Hash::from_bytes([5u8; 32]); + let m = FindMatch { + hash, + name: "serialized.txt".to_owned(), + kind: MatchKind::Contains, + is_hash_match: true, + }; + let bytes = postcard::to_allocvec(&m).unwrap(); + let decoded: FindMatch = postcard::from_bytes(&bytes).unwrap(); + assert_eq!(decoded.hash, hash); + assert_eq!(decoded.name, "serialized.txt"); + assert_eq!(decoded.kind, MatchKind::Contains); + assert!(decoded.is_hash_match); + } + + #[test] + fn test_meta_request_list_peers_serialization() { + let req = MetaRequest::ListPeers; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + assert!(matches!(decoded, MetaRequest::ListPeers)); + } + + #[test] + fn test_meta_response_list_peers_empty_serialization() { + let resp = MetaResponse::ListPeers { peers: vec![] }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::ListPeers { peers } => assert!(peers.is_empty()), + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_list_peers_with_peers_serialization() { + use iroh_base::SecretKey; + + let node_id_1 = SecretKey::from_bytes(&[1u8; 32]).public(); + let node_id_2 = SecretKey::from_bytes(&[2u8; 32]).public(); + + let peers = vec![ + PeerAnnouncement { + node_id: node_id_1, + name: Some("peer-alpha".to_owned()), + blob_count: 42, + timestamp_secs: 1_700_000_000, + }, + PeerAnnouncement { + node_id: node_id_2, + name: None, + blob_count: 0, + timestamp_secs: 1_700_000_030, + }, + ]; + let resp = MetaResponse::ListPeers { peers }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::ListPeers { + peers: decoded_peers, + } => { + assert_eq!(decoded_peers.len(), 2); + assert_eq!(decoded_peers[0].node_id, node_id_1); + assert_eq!(decoded_peers[0].name, Some("peer-alpha".to_owned())); + assert_eq!(decoded_peers[0].blob_count, 42); + assert_eq!(decoded_peers[1].node_id, node_id_2); + assert_eq!(decoded_peers[1].name, None); + assert_eq!(decoded_peers[1].blob_count, 0); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_request_abuse_counters_serialization() { + let req = MetaRequest::AbuseCounters; + let bytes = postcard::to_allocvec(&req).unwrap(); + let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); + assert!(matches!(decoded, MetaRequest::AbuseCounters)); + } + + #[test] + fn test_meta_response_abuse_counters_serialization() { + let resp = MetaResponse::AbuseCounters { + rows: vec![AbuseCountersRow { + local: [1u8; 32], + remote: [2u8; 32], + inbound_frames: 3, + inbound_bytes: 300, + outbound_frames: 4, + outbound_bytes: 400, + unattributed_frames: 5, + unattributed_bytes: 500, + }], + policy: Some(AbusePolicyView { + frames_per_sec: 100, + frame_burst: 180, + bytes_per_sec: 1_048_576, + byte_burst: 2_097_152, + }), + }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::AbuseCounters { rows, policy } => { + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].local, [1u8; 32]); + assert_eq!(rows[0].remote, [2u8; 32]); + assert_eq!(rows[0].inbound_frames, 3); + assert_eq!(rows[0].inbound_bytes, 300); + assert_eq!(rows[0].outbound_frames, 4); + assert_eq!(rows[0].outbound_bytes, 400); + assert_eq!(rows[0].unattributed_frames, 5); + assert_eq!(rows[0].unattributed_bytes, 500); + let view = policy.expect("policy"); + assert_eq!(view.frames_per_sec, 100); + assert_eq!(view.frame_burst, 180); + assert_eq!(view.bytes_per_sec, 1_048_576); + assert_eq!(view.byte_burst, 2_097_152); + } + _ => panic!("Wrong variant"), + } + } + + #[test] + fn test_meta_response_abuse_counters_empty_serialization() { + let resp = MetaResponse::AbuseCounters { + rows: vec![], + policy: None, + }; + let bytes = postcard::to_allocvec(&resp).unwrap(); + let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); + match decoded { + MetaResponse::AbuseCounters { rows, policy } => { + assert!(rows.is_empty()); + assert!(policy.is_none()); + } + _ => panic!("Wrong variant"), + } + } + + // ======================================================================== + // Wire format + // ======================================================================== + + fn eid(n: u8) -> EndpointId { + iroh_base::SecretKey::from_bytes(&[n; 32]).public() + } + + #[test] + fn wire_format_is_pinned() { + // postcard encodes the enum variant index as the first byte. These + // indices are the wire format of `/iroh-meta/3`: within a version only + // append new variants; anything else needs a new ALPN. + let h = Hash::from_bytes([0u8; 32]); + let s = String::from("x"); + let requests: Vec<(MetaRequest, u8)> = vec![ + ( + MetaRequest::Put { + filename: s.clone(), + hash: h, + }, + 0, + ), + ( + MetaRequest::Get { + filename: s.clone(), + }, + 1, + ), + (MetaRequest::List, 2), + ( + MetaRequest::Delete { + filename: s.clone(), + }, + 3, + ), + ( + MetaRequest::Rename { + from: s.clone(), + to: s.clone(), + }, + 4, + ), + ( + MetaRequest::Copy { + from: s.clone(), + to: s.clone(), + }, + 5, + ), + ( + MetaRequest::Find { + query: s.clone(), + prefer_name: false, + }, + 6, + ), + ( + MetaRequest::SetTag { + subject: vec![], + key: vec![], + value: None, + }, + 7, + ), + ( + MetaRequest::DelTag { + subject: vec![], + key: vec![], + value: None, + }, + 8, + ), + (MetaRequest::GetTags { subject: None }, 9), + (MetaRequest::SearchTags { query: s.clone() }, 10), + (MetaRequest::MigrateTags, 11), + (MetaRequest::ListPeers, 12), + (MetaRequest::Whoami, 13), + (MetaRequest::AbuseCounters, 14), + ]; + for (req, idx) in &requests { + let bytes = postcard::to_allocvec(req).unwrap(); + assert_eq!(bytes[0], *idx, "request {req:?}"); + } + let responses: Vec<(MetaResponse, u8)> = vec![ + (MetaResponse::Put { success: true }, 0), + (MetaResponse::Get { hash: None }, 1), + (MetaResponse::List { items: vec![] }, 2), + (MetaResponse::Delete { success: true }, 3), + (MetaResponse::Rename { success: true }, 4), + (MetaResponse::Copy { success: true }, 5), + (MetaResponse::Find { matches: vec![] }, 6), + (MetaResponse::SetTag { success: true }, 7), + ( + MetaResponse::DelTag { + success: true, + deleted: 1, + }, + 8, + ), + (MetaResponse::GetTags { tags: vec![] }, 9), + (MetaResponse::SearchTags { tags: vec![] }, 10), + (MetaResponse::MigrateTags { migrated: 0 }, 11), + (MetaResponse::ListPeers { peers: vec![] }, 12), + ( + MetaResponse::Whoami { + node_id: eid(1), + version: "0".to_owned(), + can_write: true, + open_writes: false, + }, + 13, + ), + (MetaResponse::Error { message: s }, 14), + ( + MetaResponse::AbuseCounters { + rows: vec![], + policy: None, + }, + 15, + ), + ]; + for (resp, idx) in &responses { + let bytes = postcard::to_allocvec(resp).unwrap(); + assert_eq!(bytes[0], *idx, "response {resp:?}"); + } + } + + #[test] + fn is_write_classifies_every_request() { + let h = Hash::from_bytes([0u8; 32]); + let s = String::from("x"); + for req in [ + MetaRequest::Put { + filename: s.clone(), + hash: h, + }, + MetaRequest::Delete { + filename: s.clone(), + }, + MetaRequest::Rename { + from: s.clone(), + to: s.clone(), + }, + MetaRequest::Copy { + from: s.clone(), + to: s.clone(), + }, + MetaRequest::SetTag { + subject: vec![], + key: vec![], + value: None, + }, + MetaRequest::DelTag { + subject: vec![], + key: vec![], + value: None, + }, + MetaRequest::MigrateTags, + ] { + assert!(req.is_write(), "{req:?} must require write access"); + } + for req in [ + MetaRequest::Get { + filename: s.clone(), + }, + MetaRequest::List, + MetaRequest::Find { + query: s.clone(), + prefer_name: true, + }, + MetaRequest::GetTags { subject: None }, + MetaRequest::SearchTags { query: s }, + MetaRequest::ListPeers, + MetaRequest::Whoami, + MetaRequest::AbuseCounters, + ] { + assert!(!req.is_write(), "{req:?} is read-only"); + } + } + + #[test] + fn wire_tag_keeps_binary_values_intact() { + let tag = WireTag { + subject: b"f".to_vec(), + key: b"k".to_vec(), + value: Some(vec![0xff, 0xfe, 0x00, 0x80]), + }; + let bytes = postcard::to_allocvec(&tag).unwrap(); + let back: WireTag = postcard::from_bytes(&bytes).unwrap(); + assert_eq!(back, tag); + } +} diff --git a/pkgs/id/src/fileops.rs b/pkgs/id/src/fileops.rs index af92db72ab..4e70a71080 100644 --- a/pkgs/id/src/fileops.rs +++ b/pkgs/id/src/fileops.rs @@ -1,813 +1,12 @@ -//! File-level operations shared by the CLI, REPL, meta protocol and web UI. +//! File operations, re-exported from `id-sync`. //! -//! A "file" in `id` is a *name* (an iroh-blobs tag) pointing at an immutable -//! blob hash, plus a set of metadata tags in the [`TagStore`]. Operations that -//! touch both halves — `put`, `rename`, `copy`, `delete` — used to be -//! implemented separately in the web routes, the meta protocol and the REPL, -//! and they drifted apart (for example: copy over the meta protocol did not -//! copy metadata, and delete left metadata behind). This module is the single -//! implementation; every entry point calls it. -//! -//! # Semantics -//! -//! - [`FileOps::put`] verifies that the blob is present **before** creating the -//! name, so a failed upload can never leave a dangling reference. -//! - [`FileOps::rename`] and [`FileOps::copy`] archive a file they replace -//! (`.archive.`) and record `archive.replace` / `archive.rename` -//! metadata. Metadata moves (rename) or is duplicated (copy) with the file, -//! and the `name`/`file` identity tags are refreshed to the new name. -//! - [`FileOps::delete`] is a *hard* delete: the name, its metadata and its -//! archive tags are removed. The blob bytes stay until garbage collected. - -use std::collections::BTreeSet; -use std::time::{Duration, Instant}; - -use anyhow::{Context, Result}; -use futures_lite::StreamExt; -use iroh_blobs::{Hash, api::Store}; -use thiserror::Error; - -use crate::tags::{TagStore, TagValue, now_unix}; - -const ARCHIVE_IDENTITY_TAG_KEYS: [&[u8]; 5] = [ - b"name", - b"file", - b"path", - // Archive references describe the live file's archives, so they - // stay on the live name when its other metadata moves onto an - // archive. Letting one travel onto the archive subject orphans - // every earlier archive from the live file's delete (#4574). - b"archive.rename", - b"archive.replace", -]; - -/// Errors from file operations, distinguishable so callers can map them to -/// protocol errors or HTTP status codes. -#[derive(Debug, Error)] -pub enum FileOpError { - /// The new name was empty or whitespace. - #[error("name cannot be empty")] - EmptyName, - /// The name is rooted or contains a traversal component. - #[error("name must be a safe relative path: {0}")] - InvalidName(String), - /// The name collides with the namespace used for system archives. - #[error("name is reserved for archives: {0}")] - ReservedArchiveName(String), - /// Source and destination are the same name. - #[error("new name must differ from the current name")] - SameName, - /// The named file does not exist. - #[error("file not found: {0}")] - NotFound(String), - /// The blob to be named is not (completely) in the store. - #[error("blob {0} is not present in the store (upload the content before naming it)")] - BlobMissing(Hash), - /// Any other storage failure. - #[error(transparent)] - Store(#[from] anyhow::Error), -} - -/// Whether an error message from a server means "the blob is not (yet) there". -/// -/// Clients use this to retry a `Put` while an upload is still being finalized. -pub fn is_blob_missing_message(message: &str) -> bool { - message.contains("is not present in the store") -} - -/// Result of [`FileOps::rename`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RenameOutcome { - /// Hash of the renamed content. - pub hash: Hash, - /// Archive tag created for the original name, if any. - pub archived_original: Option, - /// Archive tag created for a file that was replaced at the destination. - pub archived_replaced: Option, -} - -/// Result of [`FileOps::copy`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CopyOutcome { - /// Hash of the copied content. - pub hash: Hash, - /// Archive tag created for a file that was replaced at the destination. - pub archived_replaced: Option, -} - -/// Result of [`FileOps::delete`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DeleteOutcome { - /// Whether the name existed. - pub existed: bool, - /// Number of archive tags removed. - pub archives_removed: usize, - /// Number of metadata tags removed. - pub metadata_removed: usize, -} - -/// File operations over a blob [`Store`] and a [`TagStore`]. -#[derive(Debug, Clone)] -pub struct FileOps<'a> { - store: &'a Store, - tags: &'a TagStore, - blob_wait: Duration, - /// Node that originated a write, stamped as the file's `origin` tag - /// (#4973). `None` when the caller does not know its node id: no - /// origin is stamped and listings show the file's origin as unknown. - origin: Option, -} - -/// Serialises archive-name resolve+claim within this process (#2462). -/// -/// On its own, resolving a free archive name is check-then-act: the name -/// comes back *unclaimed* and the caller claims it with a later -/// unconditional `tags().set`, so two concurrent same-second replaces of -/// one name could resolve the same candidate and the second claim would -/// silently overwrite the first replace's archive. -/// [`claim_archive_name`] holds this lock across the whole -/// resolve-and-set, so a name is never handed out unclaimed. -/// -/// Scope: this is an in-process lock. It is sound because the `id` server -/// is the single process writing this tag store; a second writer process -/// sharing the store would need store-level compare-and-set instead. -static ARCHIVE_CLAIM_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - -/// The archive tag for `name` at `ts`, bumped past any archive tag that -/// already exists: `{name}.archive.{ts}`, then `{name}.archive.{ts + 1}`, -/// and so on until the name is free. -/// -/// Archive names carry second-resolution timestamps, so two replaces of -/// one name within the same second would otherwise pick the same tag and -/// the second would silently overwrite the first replace's archive -/// (#1612). The suffix stays all digits: `delete` enumerates a file's -/// archives by exactly that shape, and the web layer parses the suffix -/// as the archive timestamp. -/// -/// The returned name is NOT claimed: callers must go through -/// [`claim_archive_name`], which holds [`ARCHIVE_CLAIM_LOCK`]; this -/// helper may only be called with that lock held. -async fn free_archive_name(store: &Store, name: &str, ts: u64) -> Result { - let mut suffix = ts; - loop { - let candidate = format!("{name}.archive.{suffix}"); - if store.tags().get(&candidate).await?.is_none() { - return Ok(candidate); - } - suffix += 1; - } -} - -/// Whether `name` has the archive tag shape used by FileOps. -fn is_archive_tag_name(name: &str) -> bool { - let Some((file_name, suffix)) = name.rsplit_once(".archive.") else { - return false; - }; - !file_name.is_empty() && !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()) -} - -/// Resolve a free archive name for `name` at `ts` and claim it for -/// `hash` in the same critical section (#2462): when this returns, the -/// tag already points at `hash`, and no concurrent claim in this process -/// can receive the same name. -pub(crate) async fn claim_archive_name( - store: &Store, - name: &str, - ts: u64, - hash: Hash, -) -> Result { - let _guard = ARCHIVE_CLAIM_LOCK.lock().await; - let candidate = free_archive_name(store, name, ts).await?; - store.tags().set(&candidate, hash).await?; - Ok(candidate) -} - -/// Provenance metadata keys recorded at a file's first write (#4973): -/// the origin node and the upload (`created`) timestamp. Listings read -/// a file's origin and upload time from these tags on its own name. -pub(crate) const PROVENANCE_TAG_KEYS: [&[u8]; 2] = [b"origin", b"created"]; - -/// Snapshot `from`'s recorded provenance tags onto `to` (#5383). -/// -/// An archive alias points at the same blob as its source but lives -/// under a new name, so without this copy a listing reports the -/// archive's origin as unknown and origin filtering misses it. Tags -/// are copied by content hash so the recorded values are preserved -/// exactly; a source with no recorded provenance leaves `to` with -/// none — unknown stays unknown, provenance is never invented. -pub(crate) async fn snapshot_provenance_tags(tags: &TagStore, from: &str, to: &str) -> Result<()> { - for key in PROVENANCE_TAG_KEYS { - for tag in tags.get_by_key(&tags.global, from.as_bytes(), key).await? { - tags.set_tag_hash( - &tags.global, - to.as_bytes(), - &tag.key, - tag.value.as_ref().map(TagValue::as_bytes), - tag.hash, - tag.len, - ) - .await?; - } - } - Ok(()) -} - -impl<'a> FileOps<'a> { - /// Create file operations over the given stores. - pub const fn new(store: &'a Store, tags: &'a TagStore) -> Self { - Self { - store, - tags, - blob_wait: Duration::ZERO, - origin: None, - } - } - - /// How long [`FileOps::put`] waits for a blob that is still being - /// uploaded to become complete before declaring it missing. - /// - /// A pushing client can finish *sending* slightly before the server has - /// finished *storing*, so a `Put` that immediately follows a push may - /// arrive first. Servers set a few seconds here; local puts keep the - /// default of zero, since their blob is already complete. - #[must_use] - pub const fn with_blob_wait(mut self, wait: Duration) -> Self { - self.blob_wait = wait; - self - } - - /// Stamp writes with `origin` (a node id) as the file's origin node - /// (#4973). The stamp is set-if-absent: the node that first wrote a - /// file stays its origin across later writes and renames, and files - /// written before origin stamping existed simply have no origin tag. - #[must_use] - pub fn with_origin(mut self, origin: String) -> Self { - self.origin = Some(origin); - self - } - - /// Whether the blob is complete, waiting up to `blob_wait` for it. - async fn blob_present(&self, hash: Hash) -> Result { - let deadline = Instant::now() + self.blob_wait; - loop { - if self - .store - .blobs() - .has(hash) - .await - .map_err(anyhow::Error::from)? - { - return Ok(true); - } - if Instant::now() >= deadline { - return Ok(false); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - } - - /// The single canonical-name rule for every FileOps entry point. - /// - /// A name is stored exactly as given, so any name that cannot be - /// re-specified identically is refused rather than stored under a - /// look-alike: leading or trailing padding, empty components - /// (`a//b`, `a/`, `a\`), rooted names, drive prefixes, and `.`/`..` - /// components all fail with [`FileOpError::InvalidName`]. Forgiving - /// surfaces (CLI, REPL, web) trim user input before calling in. - fn validate_name(name: &str) -> Result<(), FileOpError> { - if name.trim().is_empty() { - return Err(FileOpError::EmptyName); - } - let bytes = name.as_bytes(); - let has_windows_drive_prefix = - bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; - if name != name.trim() - || name.starts_with('/') - || name.starts_with('\\') - || has_windows_drive_prefix - || name - .split(['/', '\\']) - .any(|component| component.is_empty() || matches!(component, "." | "..")) - { - return Err(FileOpError::InvalidName(name.to_owned())); - } - if is_archive_tag_name(name) { - return Err(FileOpError::ReservedArchiveName(name.to_owned())); - } - Ok(()) - } - - /// Validate a rename/copy target without normalising it: the target is - /// stored verbatim, so trimming here would create the padded-value twins - /// the canonical-name rule exists to prevent. - fn validate_target(from: &str, to: &str) -> Result { - Self::validate_name(to)?; - if from == to { - return Err(FileOpError::SameName); - } - Ok(to.to_owned()) - } - - /// Archive whatever currently lives at `name`, returning the archive tag. - async fn archive_existing(&self, name: &str, ts: u64) -> Result> { - let Some(existing) = self.store.tags().get(name).await? else { - return Ok(None); - }; - // Archive references belong to the live file: they name the - // archives a future delete of this file must also remove. The - // transfer below discards them from this name (and the - // exclusion list keeps them off the archive), so snapshot them - // here and restore them onto the live name afterwards - - // otherwise each replacement orphans every earlier archive. - let mut archive_refs = Vec::new(); - for key in [&b"archive.rename"[..], &b"archive.replace"[..]] { - for tag in self - .tags - .get_by_key(&self.tags.global, name.as_bytes(), key) - .await? - { - if let Some(value) = tag.value.as_ref().and_then(|value| value.as_str()) { - archive_refs.push((key, value.to_owned())); - } - } - } - let archive = claim_archive_name(self.store, name, ts, existing.hash) - .await - .with_context(|| format!("archiving replaced file {name}"))?; - self.tags - .transfer_all_tags_except( - &self.tags.global, - name.as_bytes(), - archive.as_bytes(), - &ARCHIVE_IDENTITY_TAG_KEYS, - ) - .await - .with_context(|| format!("moving metadata for archived file {name}"))?; - self.tags - .refresh_identity_tags(&self.tags.global, archive.as_bytes()) - .await - .with_context(|| format!("refreshing identity for archive {archive}"))?; - for (key, value) in &archive_refs { - self.tags - .set_tag( - &self.tags.global, - name.as_bytes(), - key, - Some(value.as_bytes()), - b"", - ) - .await - .with_context(|| format!("restoring archive references for {name}"))?; - } - Ok(Some(archive)) - } - - /// Name `hash` as `name`, after verifying the blob is complete in the store. - /// - /// Sets the `created` tag only if absent and always refreshes `modified`, - /// stamps the `origin` node on a genuine first write (no `created` tag - /// recorded yet) if one is configured, then auto-tags `name`/`file`. - /// A legacy file that predates origin stamping keeps an unknown origin - /// when it is overwritten: absence of an `origin` tag alone does not - /// prove this write is the file's first. - pub async fn put(&self, name: &str, hash: Hash) -> Result<(), FileOpError> { - Self::validate_name(name)?; - if !self.blob_present(hash).await? { - return Err(FileOpError::BlobMissing(hash)); - } - self.store - .tags() - .set(name, hash) - .await - .map_err(anyhow::Error::from)?; - self.stamp(name, false).await; - Ok(()) - } - - /// Record `created` (if absent or `reset_created`), `modified`, and identity tags. - /// - /// Metadata bookkeeping failures are logged, not fatal: the name already - /// points at the right content. - async fn stamp(&self, name: &str, reset_created: bool) { - let ns = &self.tags.global; - let now = now_unix().to_string(); - let subject = name.as_bytes(); - // Origin is stamped only for a genuine first write: a name with a - // `created` tag but no `origin` tag is a legacy file whose true - // origin is unknown and must stay unknown (Codex review, PR #5191). - let first_write = self - .tags - .get_by_key(ns, subject, b"created") - .await - .map(|existing| existing.is_empty()) - .unwrap_or(false); - let created = if reset_created { - self.tags - .set_singleton(ns, subject, b"created", Some(now.as_bytes()), b"") - .await - } else { - self.tags - .set_if_absent(ns, subject, b"created", Some(now.as_bytes()), b"") - .await - .map(|_| ()) - }; - if let Err(e) = created { - tracing::warn!("failed to set created tag for {name}: {e:#}"); - } - if let Err(e) = self - .tags - .set_singleton(ns, subject, b"modified", Some(now.as_bytes()), b"") - .await - { - tracing::warn!("failed to set modified tag for {name}: {e:#}"); - } - if first_write - && let Some(origin) = &self.origin - && let Err(e) = self - .tags - .set_if_absent(ns, subject, b"origin", Some(origin.as_bytes()), b"") - .await - { - tracing::warn!("failed to set origin tag for {name}: {e:#}"); - } - if let Err(e) = self.tags.auto_tag(ns, subject, None).await { - tracing::warn!("failed to auto-tag {name}: {e:#}"); - } - } - - /// Rename `from` to `to`. - /// - /// A file already at `to` is archived first. When `archive` is true the - /// original name is also archived. Metadata follows the file. - pub async fn rename( - &self, - from: &str, - to: &str, - archive: bool, - ) -> Result { - let to = Self::validate_target(from, to)?; - let hash = self - .store - .tags() - .get(from) - .await - .map_err(anyhow::Error::from)? - .ok_or_else(|| FileOpError::NotFound(from.to_owned()))? - .hash; - let ts = now_unix(); - - let archived_replaced = self.archive_existing(&to, ts).await?; - self.store - .tags() - .set(&to, hash) - .await - .map_err(anyhow::Error::from)?; - - let archived_original = if archive { - match claim_archive_name(self.store, from, ts, hash).await { - Ok(name) => Some(name), - Err(e) => { - tracing::error!("failed to archive original {from}: {e}"); - None - } - } - } else { - None - }; - - // The archive alias keeps the source's recorded provenance - // (#5383): snapshot it now, before the transfer below moves - // (and deletes) the source name's tags onto `to`. - if let Some(archive_name) = &archived_original - && let Err(e) = snapshot_provenance_tags(self.tags, from, archive_name).await - { - tracing::warn!("failed to snapshot provenance {from} -> {archive_name}: {e:#}"); - } - - self.store - .tags() - .delete(from) - .await - .map_err(anyhow::Error::from)?; +//! Step 3b of the pkgs/id crate split (#4406): the implementation of +//! this module lives in `id_sync::fileops`. This facade module holds +//! the re-exports and the tests that run against the facade's own +//! `LocalNode` (which stays here until step 7), so every historical +//! `id::fileops` path is unchanged. - let ns = &self.tags.global; - if let Err(e) = self - .tags - .transfer_all_tags(ns, from.as_bytes(), to.as_bytes()) - .await - { - tracing::warn!("failed to transfer tags {from} -> {to}: {e:#}"); - } - if let Err(e) = self.tags.refresh_identity_tags(ns, to.as_bytes()).await { - tracing::warn!("failed to refresh identity tags for {to}: {e:#}"); - } - for (key, value) in [ - ("archive.rename", &archived_original), - ("archive.replace", &archived_replaced), - ] { - if let Some(archive_name) = value - && let Err(e) = self - .tags - .set_tag( - ns, - to.as_bytes(), - key.as_bytes(), - Some(archive_name.as_bytes()), - b"", - ) - .await - { - tracing::warn!("failed to set {key} tag on {to}: {e:#}"); - } - } - - Ok(RenameOutcome { - hash, - archived_original, - archived_replaced, - }) - } - - /// Copy `from` to `to` (a second name for the same content). - /// - /// A file already at `to` is archived first. Metadata is duplicated, the - /// identity tags are refreshed, and the copy gets its own `created` and - /// `modified` timestamps. - pub async fn copy(&self, from: &str, to: &str) -> Result { - let to = Self::validate_target(from, to)?; - let hash = self - .store - .tags() - .get(from) - .await - .map_err(anyhow::Error::from)? - .ok_or_else(|| FileOpError::NotFound(from.to_owned()))? - .hash; - let ts = now_unix(); - - let archived_replaced = self.archive_existing(&to, ts).await?; - self.store - .tags() - .set(&to, hash) - .await - .map_err(anyhow::Error::from)?; - - let ns = &self.tags.global; - if let Err(e) = self - .tags - .copy_all_tags_except( - ns, - from.as_bytes(), - to.as_bytes(), - &[b"archive.rename", b"archive.replace"], - ) - .await - { - tracing::warn!("failed to copy tags {from} -> {to}: {e:#}"); - } - if let Err(e) = self.tags.refresh_identity_tags(ns, to.as_bytes()).await { - tracing::warn!("failed to refresh identity tags for {to}: {e:#}"); - } - self.stamp(&to, true).await; - if let Some(archive_name) = &archived_replaced - && let Err(e) = self - .tags - .set_tag( - ns, - to.as_bytes(), - b"archive.replace", - Some(archive_name.as_bytes()), - b"", - ) - .await - { - tracing::warn!("failed to set archive.replace tag on {to}: {e:#}"); - } - - Ok(CopyOutcome { - hash, - archived_replaced, - }) - } - - /// Hard-delete `name`: the name itself, its metadata, and its archive tags. - pub async fn delete(&self, name: &str) -> Result { - if name.trim().is_empty() { - return Err(FileOpError::EmptyName); - } - - // Renames move the file identity metadata, including these archive - // references, to the current name. Read them before deleting metadata. - let mut archives = BTreeSet::new(); - for key in [&b"archive.rename"[..], &b"archive.replace"[..]] { - for tag in self - .tags - .get_by_key(&self.tags.global, name.as_bytes(), key) - .await? - { - if let Some(archive_name) = tag.value.as_ref().and_then(|value| value.as_str()) { - if is_archive_tag_name(archive_name) { - archives.insert(archive_name.to_owned()); - } else { - tracing::warn!("ignoring malformed archive reference on {name}"); - } - } - } - } - - // Keep the legacy/current-name scan for archives without metadata. - // Collect before mutation so a listing failure cannot leave a partial - // hard delete behind. - let prefix = format!("{name}.archive."); - let mut list = self - .store - .tags() - .list() - .await - .map_err(anyhow::Error::from)?; - while let Some(item) = list.next().await { - let item = item.map_err(anyhow::Error::from)?; - let tag = String::from_utf8_lossy(item.name.as_ref()).into_owned(); - if let Some(rest) = tag.strip_prefix(&prefix) - && !rest.is_empty() - && rest.bytes().all(|b| b.is_ascii_digit()) - { - archives.insert(tag); - } - } - - let existed = self - .store - .tags() - .get(name) - .await - .map_err(anyhow::Error::from)? - .is_some(); - self.store - .tags() - .delete(name) - .await - .map_err(anyhow::Error::from)?; - - let metadata_removed = self - .tags - .del_all_tags(&self.tags.global, name.as_bytes()) - .await - .unwrap_or_else(|e| { - tracing::warn!("failed to delete metadata for {name}: {e:#}"); - 0 - }); - - let mut archives_removed = 0; - for tag in archives { - match self.store.tags().delete(&tag).await { - Ok(_) => archives_removed += 1, - Err(e) => tracing::warn!("failed to delete archive tag {tag}: {e}"), - } - // Archives created by rename/copy carry the replaced file's - // metadata (archive_existing moves it onto the archive subject); - // remove it too, or it stays searchable after the archive blob - // tag is gone. - if let Err(e) = self - .tags - .del_all_tags(&self.tags.global, tag.as_bytes()) - .await - { - tracing::warn!("failed to delete metadata for archive {tag}: {e:#}"); - } - } - - Ok(DeleteOutcome { - existed, - archives_removed, - metadata_removed, - }) - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod archive_name_tests { - use iroh_blobs::{Hash, store::mem::MemStore}; - - use super::*; - - fn hash(byte: u8) -> Hash { - Hash::from([byte; 32]) - } - - #[test] - fn fileops_rejects_archive_shaped_names_but_allows_lookalikes() { - for name in [ - "report.archive.0", - "report.archive.1700000000", - "report.archive.18446744073709551616", - ] { - assert!(matches!( - FileOps::validate_name(name), - Err(FileOpError::ReservedArchiveName(found)) if found == name - )); - } - - for name in ["a.archive.notes", "a.archive.+1", "a.archive.١"] { - assert!(FileOps::validate_name(name).is_ok(), "{name:?}"); - } - } - - /// Two replaces of one name within the same second must not share an - /// archive tag (#1612): the second archive is bumped to the next free - /// numeric suffix, and both replaced versions stay archived. - #[tokio::test] - async fn same_second_archives_never_overwrite() { - let store: Store = MemStore::new().into(); - let ts = 1_700_000_000_u64; - - let first = claim_archive_name(&store, "doc", ts, hash(1)) - .await - .unwrap(); - assert_eq!(first, format!("doc.archive.{ts}")); - - let second = claim_archive_name(&store, "doc", ts, hash(2)) - .await - .unwrap(); - assert_eq!(second, format!("doc.archive.{}", ts + 1)); - - // Both archives survive, each still pointing at its own version. - assert_eq!( - store.tags().get(&first).await.unwrap().unwrap().hash, - hash(1) - ); - assert_eq!( - store.tags().get(&second).await.unwrap().unwrap().hash, - hash(2) - ); - - // A third same-second replace bumps past both. - let third = claim_archive_name(&store, "doc", ts, hash(3)) - .await - .unwrap(); - assert_eq!(third, format!("doc.archive.{}", ts + 2)); - } - - /// Concurrent same-second claims must never share a name (#2462): - /// when resolve and claim were separate steps, interleaved resolves - /// could pick the same candidate and one archive silently overwrote - /// another. Barrier-synchronised claims must all land on distinct - /// tags, each still pointing at its own version. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn concurrent_same_second_claims_never_collide() { - use std::sync::Arc; - - use tokio::sync::Barrier; - - let store: Store = MemStore::new().into(); - let store = Arc::new(store); - let ts = 1_700_000_000_u64; - const CLAIMS: u8 = 8; - let barrier = Arc::new(Barrier::new(usize::from(CLAIMS))); - let mut handles = Vec::new(); - for i in 0..CLAIMS { - let store = Arc::clone(&store); - let barrier = Arc::clone(&barrier); - handles.push(tokio::spawn(async move { - barrier.wait().await; - let name = claim_archive_name(&store, "doc", ts, hash(i + 1)) - .await - .unwrap(); - (name, hash(i + 1)) - })); - } - let mut claimed = Vec::new(); - for handle in handles { - claimed.push(handle.await.unwrap()); - } - let mut names: Vec<&str> = claimed.iter().map(|(name, _)| name.as_str()).collect(); - names.sort_unstable(); - names.dedup(); - assert_eq!(names.len(), usize::from(CLAIMS), "archive claims collided"); - for (name, expected) in &claimed { - assert_eq!( - store.tags().get(name).await.unwrap().unwrap().hash, - *expected, - "archive {name} lost its version" - ); - } - } - - /// With no collision the archive name is exactly the historic shape. - #[tokio::test] - async fn uncontested_archive_name_is_unchanged() { - let store: Store = MemStore::new().into(); - let name = claim_archive_name(&store, "doc", 42, hash(7)) - .await - .unwrap(); - assert_eq!(name, "doc.archive.42"); - assert_eq!( - store.tags().get(&name).await.unwrap().unwrap().hash, - hash(7) - ); - } -} +pub use id_sync::fileops::*; #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index bc0e469a1f..d9ff87834c 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -172,7 +172,7 @@ pub use id_core::connectivity; pub mod conversion; pub mod currency; pub mod currency_poc; -pub mod dht; +pub use id_sync::dht; #[cfg(feature = "world")] pub mod directory; #[cfg(feature = "world")] @@ -211,7 +211,7 @@ pub(crate) mod key_envelope; pub mod local; pub use id_events::local_claims; pub use id_events::local_events; -pub mod log_sync; +pub use id_sync::log_sync; mod peer_announcement; pub mod serve_proxy; pub use id_core::membership; @@ -317,6 +317,7 @@ pub use helpers::{ print_matches_cli, }; pub use protocol::{FindMatch, MatchKind, MetaProtocol, MetaRequest, MetaResponse, TaggedMatch}; +pub use protocol::match_kind; pub use repl::run_repl; pub use store::{StoreType, load_or_create_keypair, open_store}; @@ -347,25 +348,7 @@ pub use id_store::STORE_PATH; /// for local clients to connect. Automatically removed on clean shutdown. pub const SERVE_LOCK: &str = ".iroh-serve.lock"; -/// Application-Level Protocol Negotiation (ALPN) identifier for the meta protocol. -/// -/// Used during QUIC handshake to identify connections for metadata operations -/// (list, find, delete, rename, etc.) as opposed to blob data transfer. -/// -/// **Version 2** carries tag keys/values as raw bytes (binary-safe), defines -/// `DelTag` with no value as "delete every value of the key", and adds `Whoami` -/// and `Error`. It is not wire-compatible with `/iroh-meta/1`; the ALPN bump -/// makes old and new nodes fail the handshake cleanly instead of mis-decoding. -/// -/// **Version 3** changes the `List` response item from `(hash, name)` pairs -/// to `ListEntry` records carrying the file's origin node and upload time -/// (#4973). That payload change is not wire-compatible with `/iroh-meta/2` -/// under postcard, so it takes this ALPN bump per the rule below. -/// -/// Compatibility rule: within a version, only **append** enum variants. Any -/// other change to [`protocol::MetaRequest`] / [`protocol::MetaResponse`] -/// requires a new ALPN. `protocol::tests` pins every discriminant. -pub const META_ALPN: &[u8] = b"/iroh-meta/3"; +pub use id_sync::protocol::META_ALPN; // ============================================================================ // Utility Functions @@ -405,46 +388,7 @@ pub fn to_absolute(path: &PathBuf) -> Result { } } -/// Determines how a search query matches a string. -/// -/// This function implements a priority-based matching system: -/// 1. **Exact**: The strings are identical -/// 2. **Prefix**: The haystack starts with the needle -/// 3. **Contains**: The haystack contains the needle somewhere -/// -/// # Arguments -/// -/// * `haystack` - The string to search within (e.g., filename or hash) -/// * `needle` - The search query -/// -/// # Returns -/// -/// * `Some(MatchKind::Exact)` if `haystack == needle` -/// * `Some(MatchKind::Prefix)` if `haystack.starts_with(needle)` -/// * `Some(MatchKind::Contains)` if `haystack.contains(needle)` -/// * `None` if no match -/// -/// # Example -/// -/// ```rust -/// use id::{match_kind, MatchKind}; -/// -/// assert_eq!(match_kind("hello.txt", "hello.txt"), Some(MatchKind::Exact)); -/// assert_eq!(match_kind("hello.txt", "hello"), Some(MatchKind::Prefix)); -/// assert_eq!(match_kind("say-hello.txt", "hello"), Some(MatchKind::Contains)); -/// assert_eq!(match_kind("world.txt", "hello"), None); -/// ``` -pub fn match_kind(haystack: &str, needle: &str) -> Option { - if haystack == needle { - Some(MatchKind::Exact) - } else if haystack.starts_with(needle) { - Some(MatchKind::Prefix) - } else if haystack.contains(needle) { - Some(MatchKind::Contains) - } else { - None - } -} + /// Checks if a string is a valid node ID format. /// diff --git a/pkgs/id/src/meta_client.rs b/pkgs/id/src/meta_client.rs index 909224096d..c1d20d6a15 100644 --- a/pkgs/id/src/meta_client.rs +++ b/pkgs/id/src/meta_client.rs @@ -1,23 +1,17 @@ -//! Client side of the meta protocol, with an in-process fallback. +//! Client side of the meta protocol: the composition half. //! -//! Commands that talk to the meta protocol (tags, and anything else expressed -//! as a [`MetaRequest`]) are written once against [`MetaRequester`]. Two -//! implementations exist: -//! -//! - [`MetaClient::Remote`]: a QUIC connection to a running `id serve` -//! (local, found via the lock file) or to any peer by node ID. -//! - [`MetaClient::Local`]: no server is running, so the request is answered -//! **in-process by the very same [`MetaProtocol::handle`]** over a -//! [`LocalNode`]. Offline and online therefore behave identically — there is -//! no separate "legacy" code path to drift out of sync. - -use std::future::Future; -use std::time::Duration; - -use anyhow::{Context, Result, bail}; +//! Step 3b of the pkgs/id crate split (#4406): the wire half of this +//! module — [`MetaRequester`], `request_over`, the capped response +//! read — lives in `id_sync::meta_client` and is re-exported here. +//! What stays in the facade is the composition: [`MetaClient`] chooses +//! between a running `id serve` (found through the CLI layer's serve +//! lock) and the in-process [`LocalNode`], both of which are facade +//! concerns until step 7 extracts the CLI layer. + +use anyhow::Result; use iroh::{ EndpointAddr, - endpoint::{Connection, Endpoint, ReadToEndError, RecvStream}, + endpoint::{Connection, Endpoint}, }; use iroh_base::EndpointId; @@ -27,92 +21,10 @@ use crate::local::LocalNode; use crate::protocol::{MetaRequest, MetaResponse}; use crate::{CLIENT_KEY_FILE, META_ALPN, load_or_create_keypair}; -/// Maximum accepted size of a single response (64 MiB). -pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; - -/// Maximum time allowed for one remote meta request and its response. -pub const META_RESPONSE_TIMEOUT: Duration = Duration::from_secs(45); - -/// Something that can answer a [`MetaRequest`]. -pub trait MetaRequester { - /// Send `req` and return the node's response. - /// - /// A [`MetaResponse::Error`] is returned as `Ok`; use [`expect_ok`] to turn - /// it into an `Err`. - fn request(&mut self, req: MetaRequest) -> impl Future>; -} - -/// Turn a [`MetaResponse::Error`] into an `Err`, passing other responses through. -pub fn expect_ok(resp: MetaResponse) -> Result { - match resp { - MetaResponse::Error { message } => bail!("{message}"), - other => Ok(other), - } -} - -/// Map a capped response-read failure to an error worth showing a user. -/// -/// `ReadToEndError::TooLong` displays as a bare "stream too long", which -/// sends diagnosis toward the transport; name the actual cause and the -/// limit instead. Any other read failure passes through unchanged. -pub fn capped_response_error(err: ReadToEndError) -> anyhow::Error { - match err { - ReadToEndError::TooLong => { - anyhow::anyhow!("response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit") - } - other => other.into(), - } -} - -/// Read one response stream to its end, bounded by [`MAX_RESPONSE_BYTES`] -/// and [`META_RESPONSE_TIMEOUT`]. -/// -/// Hand-rolled request paths (remote find in the CLI and the REPL) use this -/// instead of a per-call-site literal bound, so every response read shares -/// the one named cap and cannot drift back to a smaller size: the find -/// handler returns every match unbounded, so a response past ~64 KiB is -/// ordinary for a large store (#1617). -pub async fn read_capped_response(recv: &mut RecvStream) -> Result> { - read_capped_response_with_timeout(recv, META_RESPONSE_TIMEOUT).await -} - -async fn read_capped_response_with_timeout( - recv: &mut RecvStream, - timeout: Duration, -) -> Result> { - crate::connectivity::within( - timeout, - "reading a meta response", - read_capped_response_unbounded(recv), - ) - .await -} - -async fn read_capped_response_unbounded(recv: &mut RecvStream) -> Result> { - recv.read_to_end(MAX_RESPONSE_BYTES) - .await - .map_err(capped_response_error) -} - -/// Send one request over an open connection. -pub async fn request_over(conn: &Connection, req: &MetaRequest) -> Result { - request_over_with_timeout(conn, req, META_RESPONSE_TIMEOUT).await -} - -async fn request_over_with_timeout( - conn: &Connection, - req: &MetaRequest, - timeout: Duration, -) -> Result { - crate::connectivity::within(timeout, "waiting for a meta response", async { - let (mut send, mut recv) = conn.open_bi().await?; - send.write_all(&postcard::to_allocvec(req)?).await?; - send.finish()?; - let buf = read_capped_response_unbounded(&mut recv).await?; - crate::protocol::decode_meta_exact(&buf).context("decoding meta response") - }) - .await -} +pub use id_sync::meta_client::{ + MAX_RESPONSE_BYTES, META_RESPONSE_TIMEOUT, MetaRequester, capped_response_error, expect_ok, + read_capped_response, request_over, +}; /// A meta-protocol client: remote over QUIC, or local in-process. #[derive(Debug)] @@ -177,213 +89,3 @@ impl MetaRequester for MetaClient { } } -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod tests { - use super::*; - use crate::MatchKind; - use crate::protocol::{FindMatch, ListEntry}; - use iroh::{RelayMode, TransportAddr, endpoint::presets}; - use iroh_blobs::Hash; - use std::net::Ipv4Addr; - - const TEST_ALPN: &[u8] = b"id-capped-response-test"; - - /// An endpoint on localhost, with no relay and no address lookup. - async fn endpoint(alpns: Vec>) -> Result { - Ok(Endpoint::builder(presets::Minimal) - .alpns(alpns) - .relay_mode(RelayMode::Disabled) - .bind() - .await?) - } - - /// The address of `ep` on localhost: every bound socket, with an - /// unspecified IP replaced by the loopback address. - fn loopback_addr(ep: &Endpoint) -> EndpointAddr { - EndpointAddr::from_parts( - ep.id(), - ep.bound_sockets().iter().map(|addr| { - let ip = if addr.ip().is_unspecified() { - Ipv4Addr::LOCALHOST.into() - } else { - addr.ip() - }; - TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) - }), - ) - } - - /// Serve `payload` as the response on the first stream `server` accepts. - fn serve_once(server: Endpoint, payload: Vec) -> tokio::task::JoinHandle<()> { - tokio::spawn(async move { - let incoming = server.accept().await.expect("incoming"); - let conn = incoming.await.expect("connecting"); - let (mut send, mut recv) = conn.accept_bi().await.expect("accept_bi"); - let _req = recv.read_to_end(1024).await.expect("read request"); - send.write_all(&payload).await.expect("write payload"); - send.finish().expect("finish"); - conn.closed().await; - }) - } - - /// Accept and read one request, then leave the response stream open. - fn serve_silently(server: Endpoint) -> tokio::task::JoinHandle<()> { - tokio::spawn(async move { - let incoming = server.accept().await.expect("incoming"); - let conn = incoming.await.expect("connecting"); - let (_send, mut recv) = conn.accept_bi().await.expect("accept_bi"); - let _req = recv.read_to_end(1024).await.expect("read request"); - tokio::time::sleep(Duration::from_secs(5)).await; - }) - } - - #[tokio::test(flavor = "multi_thread")] - async fn silent_peer_response_times_out() { - let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); - let client = endpoint(vec![]).await.unwrap(); - let silent = serve_silently(server.clone()); - let conn = client - .connect(loopback_addr(&server), TEST_ALPN) - .await - .unwrap(); - - let err = request_over_with_timeout(&conn, &MetaRequest::List, Duration::from_millis(100)) - .await - .unwrap_err(); - assert!(err.to_string().contains("timed out after")); - assert!(err.to_string().contains("waiting for a meta response")); - - conn.close(0u32.into(), b"done"); - silent.abort(); - client.close().await; - server.close().await; - } - - #[tokio::test(flavor = "multi_thread")] - async fn silent_peer_capped_read_times_out() { - let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); - let client = endpoint(vec![]).await.unwrap(); - let silent = serve_silently(server.clone()); - let conn = client - .connect(loopback_addr(&server), TEST_ALPN) - .await - .unwrap(); - let (mut send, mut recv) = conn.open_bi().await.unwrap(); - send.write_all(&postcard::to_allocvec(&MetaRequest::List).unwrap()) - .await - .unwrap(); - send.finish().unwrap(); - - let err = read_capped_response_with_timeout(&mut recv, Duration::from_millis(100)) - .await - .unwrap_err(); - assert!(err.to_string().contains("timed out after")); - assert!(err.to_string().contains("reading a meta response")); - - conn.close(0u32.into(), b"done"); - silent.abort(); - client.close().await; - server.close().await; - } - - /// Send one request to `server` and read the response with - /// [`read_capped_response`], exactly as the remote-find paths do. - async fn round_trip(server: &Endpoint, client: &Endpoint) -> Result> { - let conn = client.connect(loopback_addr(server), TEST_ALPN).await?; - let (mut send, mut recv) = conn.open_bi().await?; - send.write_all(b"find").await?; - send.finish()?; - let buf = read_capped_response(&mut recv).await; - conn.close(0u32.into(), b"done"); - buf - } - - /// #1617: a find response past the old 64 KiB per-site bound must read - /// through the shared cap intact — 2,000 matches at ~45 wire bytes each - /// is ~90 KiB, comfortably past the old bound and under the shared one. - #[tokio::test(flavor = "multi_thread")] - async fn find_response_larger_than_64_kib_reads_through() { - let matches: Vec = (0..2_000) - .map(|i| FindMatch { - hash: Hash::from_bytes([7u8; 32]), - name: format!("found-{i:04}.txt"), - kind: MatchKind::Contains, - is_hash_match: false, - }) - .collect(); - let payload = postcard::to_allocvec(&MetaResponse::Find { matches }).unwrap(); - assert!( - payload.len() > 64 * 1024, - "payload {} bytes must exceed the old 64 KiB bound", - payload.len() - ); - - let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); - let client = endpoint(vec![]).await.unwrap(); - let served = serve_once(server.clone(), payload); - let buf = round_trip(&server, &client).await.unwrap(); - served.await.unwrap(); - client.close().await; - server.close().await; - - let resp: MetaResponse = postcard::from_bytes(&buf).unwrap(); - match resp { - MetaResponse::Find { matches } => assert_eq!(matches.len(), 2_000), - _ => panic!("unexpected response"), - } - } - - /// #1761: a List response past the hand-rolled 1 MiB bound the CLI, - /// REPL, peers and serve-probe paths used to apply must read through - /// the shared cap intact — 30,000 items at ~50 wire bytes each is - /// ~1.5 MiB, past the old bound and under the shared one. This is - /// the shape of store (15–25k items) that could not be listed at all. - #[tokio::test(flavor = "multi_thread")] - async fn list_response_larger_than_1_mib_reads_through() { - let items: Vec = (0..30_000) - .map(|i| ListEntry { - hash: Hash::from_bytes([9u8; 32]), - name: format!("file-{i:05}.txt"), - origin: None, - uploaded_at: None, - }) - .collect(); - let payload = postcard::to_allocvec(&MetaResponse::List { items }).unwrap(); - assert!( - payload.len() > 1024 * 1024, - "payload {} bytes must exceed the old 1 MiB bound", - payload.len() - ); - - let server = endpoint(vec![TEST_ALPN.to_vec()]).await.unwrap(); - let client = endpoint(vec![]).await.unwrap(); - let served = serve_once(server.clone(), payload); - let buf = round_trip(&server, &client).await.unwrap(); - served.await.unwrap(); - client.close().await; - server.close().await; - - let resp: MetaResponse = postcard::from_bytes(&buf).unwrap(); - match resp { - MetaResponse::List { items } => { - assert_eq!(items.len(), 30_000); - assert_eq!(items[29_999].name, "file-29999.txt"); - } - _ => panic!("unexpected response"), - } - } - - /// A response past the shared cap must fail by name — the limit and its - /// size — not as noq's bare "stream too long". - #[test] - fn over_cap_error_names_the_limit() { - let err = capped_response_error(ReadToEndError::TooLong); - let msg = format!("{err}"); - assert_eq!( - msg, - format!("response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit"), - "the message must be exactly the named limit, with no leftover placeholder text" - ); - } -} diff --git a/pkgs/id/src/protocol.rs b/pkgs/id/src/protocol.rs index 9a9d7b954f..c07ed45425 100644 --- a/pkgs/id/src/protocol.rs +++ b/pkgs/id/src/protocol.rs @@ -1,1011 +1,13 @@ -//! Network protocol types for remote node communication. +//! The meta protocol, re-exported from `id-sync`. //! -//! This module defines the custom "meta" protocol used for peer-to-peer -//! metadata operations beyond basic blob transfer. While Iroh handles -//! blob content via its built-in protocol, this meta protocol enables: -//! -//! - **Tag management**: Create, list, delete, rename, and copy tags on remote nodes -//! - **Search operations**: Find blobs by name or hash with fuzzy matching -//! - **Metadata queries**: List all stored items on a remote node -//! - **Peer discovery**: Query a node's known peers from gossip-based discovery -//! -//! # Protocol Architecture -//! -//! ```text -//! ┌─────────────┐ ┌─────────────┐ -//! │ Client │ │ Server │ -//! │ │ │ │ -//! │ MetaRequest├───── QUIC ────────►│MetaProtocol │ -//! │ │ (postcard) │ handler │ -//! │ │◄───────────────────┤ │ -//! │ MetaResponse│ │ │ -//! └─────────────┘ └─────────────┘ -//! ``` -//! -//! Messages are serialized using [postcard](https://docs.rs/postcard) for -//! compact binary encoding. Each connection can handle multiple request/response -//! pairs using bidirectional QUIC streams. -//! -//! # Protocol Identifier -//! -//! The meta protocol uses the ALPN identifier defined in [`crate::META_ALPN`]: -//! `b"/iroh-meta/3"`. This allows nodes to negotiate the correct protocol handler. -//! -//! # Usage Example -//! -//! ```rust,ignore -//! use id::protocol::{MetaRequest, MetaResponse}; -//! -//! // Create a request to find files matching "config" -//! let request = MetaRequest::Find { -//! query: "config".to_string(), -//! prefer_name: true, -//! }; -//! -//! // Serialize and send over QUIC connection -//! let bytes = postcard::to_allocvec(&request)?; -//! send_stream.write_all(&bytes).await?; -//! -//! // Read and deserialize response -//! let response_bytes = recv_stream.read_to_end(64 * 1024).await?; -//! let response: MetaResponse = postcard::from_bytes(&response_bytes)?; -//! ``` -//! -//! # Match Quality -//! -//! Search operations return results ranked by [`MatchKind`]: -//! - [`MatchKind::Exact`]: Query exactly equals the name/hash (best) -//! - [`MatchKind::Prefix`]: Name/hash starts with query (good) -//! - [`MatchKind::Contains`]: Name/hash contains query anywhere (okay) - -use std::{sync::Arc, time::Duration}; - -use futures_lite::StreamExt; -use iroh::endpoint::Connection; -use iroh::protocol::{AcceptError, ProtocolHandler}; -use iroh_base::EndpointId; -use iroh_blobs::{Hash, api::Store}; -use serde::{Deserialize, Serialize}; -use tokio::{sync::Semaphore, task::JoinSet}; - -use crate::access::AccessPolicy; -use crate::discovery::{PeerAnnouncement, PeerDiscovery}; -use crate::fileops::{FileOpError, FileOps}; -use crate::tags::TagStore; - -/// Decode exactly one meta-protocol value, rejecting any trailing bytes. -/// -/// Meta requests and responses are one-message-per-stream. Accepting a valid -/// postcard prefix would let a padded or concatenated stream be interpreted as -/// a different, complete message. -pub fn decode_meta_exact(bytes: &[u8]) -> anyhow::Result { - let (value, rest) = postcard::take_from_bytes(bytes)?; - anyhow::ensure!( - rest.is_empty(), - "trailing bytes after meta-protocol value ({} bytes)", - rest.len() - ); - Ok(value) -} - -/// Maximum time for one network phase (request read or response write) of a -/// meta stream. The phases are bounded separately on purpose: once a request -/// has been fully read, its handler runs to completion, so the deadline can -/// never cancel a non-transactional mutation (e.g. a rename) midway through. -const META_STREAM_DEADLINE: Duration = Duration::from_secs(60); - -/// Concurrent meta requests allowed on one connection. -const MAX_META_STREAMS_PER_CONNECTION: usize = 16; - -/// Match quality for find/search operations. -/// -/// Represents how closely a search query matches a blob's name or hash. -/// The variants are ordered by quality, with [`Exact`](MatchKind::Exact) -/// being the best match. -/// -/// # Ordering -/// -/// `MatchKind` implements `Ord` such that better matches compare less: -/// -/// ```rust -/// use id::protocol::MatchKind; -/// -/// assert!(MatchKind::Exact < MatchKind::Prefix); -/// assert!(MatchKind::Prefix < MatchKind::Contains); -/// ``` -/// -/// This allows sorting search results by quality using the natural ordering. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub enum MatchKind { - /// Query exactly equals the target string. - /// - /// For example, query "config.json" matches name "config.json" exactly. - Exact, - /// Target string starts with the query. - /// - /// For example, query "config" matches name "config.json" as a prefix. - Prefix, - /// Target string contains the query somewhere. - /// - /// For example, query "fig" matches name "config.json" as contained. - Contains, -} - -/// A single match result from find/search operations. -/// -/// Represents one blob that matched a search query, including metadata -/// about how well it matched and whether the match was against the -/// blob's name or its hash. -/// -/// # Example -/// -/// ```rust -/// use id::protocol::{FindMatch, MatchKind}; -/// use iroh_blobs::Hash; -/// -/// let m = FindMatch { -/// hash: Hash::from_bytes([0u8; 32]), -/// name: "example.txt".to_string(), -/// kind: MatchKind::Exact, -/// is_hash_match: false, -/// }; -/// -/// // This was a name match, not a hash match -/// assert!(!m.is_hash_match); -/// ``` -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FindMatch { - /// The content hash of the matched blob. - pub hash: Hash, - /// The tag name associated with this blob. - pub name: String, - /// How well the query matched (exact, prefix, or contains). - pub kind: MatchKind, - /// Whether the match was against the hash (`true`) or name (`false`). - /// - /// When searching, both the name and hash are checked. This field - /// indicates which one matched the query, useful for understanding - /// the search result context. - pub is_hash_match: bool, -} - -/// A match result tagged with the query that produced it. -/// -/// When searching with multiple queries, this struct associates each -/// match with the specific query that found it. This is used internally -/// for grouping and formatting multi-query search results. -/// -/// # Example -/// -/// ```rust -/// use id::protocol::{TaggedMatch, MatchKind}; -/// use iroh_blobs::Hash; -/// -/// let m = TaggedMatch { -/// query: "config".to_string(), -/// hash: Hash::from_bytes([0u8; 32]), -/// name: "config.json".to_string(), -/// kind: MatchKind::Prefix, -/// is_hash_match: false, -/// }; -/// -/// // The query "config" matched "config.json" as a prefix -/// assert_eq!(m.query, "config"); -/// assert_eq!(m.kind, MatchKind::Prefix); -/// ``` -#[derive(Debug, Clone)] -pub struct TaggedMatch { - /// The search query that produced this match. - pub query: String, - /// The content hash of the matched blob. - pub hash: Hash, - /// The tag name associated with this blob. - pub name: String, - /// How well the query matched. - pub kind: MatchKind, - /// Whether the match was against the hash or name. - pub is_hash_match: bool, -} - -/// Requests that can be sent to a remote node via the meta protocol. -/// -/// Each variant represents an operation that can be performed on a remote -/// node's blob store. The request is serialized with postcard and sent -/// over a QUIC bidirectional stream. -/// -/// # Serialization -/// -/// All variants are serializable for network transmission: -/// -/// ```rust -/// use id::protocol::MetaRequest; -/// use iroh_blobs::Hash; -/// -/// let req = MetaRequest::List; -/// let bytes = postcard::to_allocvec(&req).unwrap(); -/// let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); -/// ``` -/// A metadata tag as carried on the wire. -/// -/// Subject, key and value are raw bytes. The tag store is binary-safe, and the -/// v2 wire format no longer forces a lossy UTF-8 conversion on the way out. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct WireTag { - /// The subject (usually a filename). - pub subject: Vec, - /// The tag key. - pub key: Vec, - /// The tag value, `None` for key-only tags. - pub value: Option>, -} - -impl WireTag { - /// Build a wire tag from UTF-8 strings (convenience for callers and tests). - pub fn from_strs(subject: &str, key: &str, value: Option<&str>) -> Self { - Self { - subject: subject.as_bytes().to_vec(), - key: key.as_bytes().to_vec(), - value: value.map(|v| v.as_bytes().to_vec()), - } - } -} - -impl From for WireTag { - fn from(t: crate::tags::Tag) -> Self { - Self { - subject: t.subject.into_bytes(), - key: t.key.into_bytes(), - value: t.value.map(crate::tags::TagValue::into_bytes), - } - } -} - -/// Maximum size of a single request on the meta protocol (1 MiB). -pub const MAX_REQUEST_BYTES: usize = 1024 * 1024; - -/// How long a server waits for a just-pushed blob to finish arriving before a -/// `Put` naming it is refused. -pub const DEFAULT_BLOB_WAIT: std::time::Duration = std::time::Duration::from_secs(5); - -/// Requests to a remote node via the meta protocol (`/iroh-meta/3`). -/// -/// **Compatibility rule:** postcard encodes enum variants by position. Within -/// a protocol version, new variants may only be *appended*; reordering, -/// inserting or changing a payload requires a new ALPN. The -/// `wire_format_is_pinned` test fixes every discriminant. -#[derive(Debug, Serialize, Deserialize)] -pub enum MetaRequest { - /// Create or update a name on the remote node. - /// - /// Associates `filename` with `hash`. The blob content must already be on - /// the remote (push it via the blobs protocol *first*): the server verifies - /// the blob is present and refuses to create a dangling name. - Put { - /// The tag name to create or update. - filename: String, - /// The content hash to associate with this tag. - hash: Hash, - }, - /// Look up a name on the remote node, returning its hash if it exists. - Get { - /// The tag name to look up. - filename: String, - }, - /// List all names on the remote node as (hash, name) pairs. - List, - /// Delete a name from the remote node (hard delete). - /// - /// Removes the name, its metadata tags and its archive tags. The blob - /// bytes remain until garbage collected. - Delete { - /// The tag name to delete. - filename: String, - }, - /// Rename a file on the remote node. - /// - /// Metadata follows the file; a file replaced at the destination and the - /// original name are archived as `.archive.`. - Rename { - /// The current tag name. - from: String, - /// The new tag name. - to: String, - }, - /// Copy a file on the remote node. - /// - /// Creates `to` pointing at the same hash and duplicates the metadata. - Copy { - /// The source tag name. - from: String, - /// The destination tag name. - to: String, - }, - /// Search for names and hashes matching a query, ranked by match quality. - Find { - /// The search query (matched case-insensitively). - query: String, - /// If `true`, prioritize name matches over hash matches in results. - prefer_name: bool, - }, - /// Set a metadata tag (global namespace). - SetTag { - /// The subject (usually a filename) to tag. - subject: Vec, - /// The tag key (e.g. "author", "status"). - key: Vec, - /// Optional tag value (arbitrary bytes). - value: Option>, - }, - /// Delete metadata tags (global namespace). - DelTag { - /// The subject (usually a filename). - subject: Vec, - /// The tag key to delete. - key: Vec, - /// A specific value to delete. `None` deletes **every** tag with this - /// subject and key (including a value-less key-only tag). - value: Option>, - }, - /// List metadata tags for a subject (or every tag when `None`). - GetTags { - /// The subject (filename) to list tags for. `None` = list all. - subject: Option>, - }, - /// Search metadata tags with the structured query syntax. - /// - /// Supports `key:`, `:value`, `key:value`, `"literal"` and bare words; - /// multiple terms are `AND`ed. - SearchTags { - /// The search query string. - query: String, - }, - /// Add `name`/`file` auto-tags to every blob name that lacks them. - MigrateTags, - /// Request the peers this node has discovered via gossip. - ListPeers, - /// Ask the node who it is and whether the caller may write to it. - /// - /// Lets clients give an actionable error instead of an opaque failure when - /// a write is refused. - Whoami, - /// Read the node's per-(local node, remote endpoint) frame/byte abuse - /// counters, split by direction, plus the policy rates that produced them. - /// - /// Read-only. The counters cover world-protocol traffic admitted - /// by the node's abuse evaluator; a node with no evaluator attached - /// (a plain serve without a world, or a build without the world - /// feature) records none and answers with an empty report. - AbuseCounters, -} - -impl MetaRequest { - /// Whether this request mutates the store (and therefore needs write access). - pub const fn is_write(&self) -> bool { - matches!( - self, - Self::Put { .. } - | Self::Delete { .. } - | Self::Rename { .. } - | Self::Copy { .. } - | Self::SetTag { .. } - | Self::DelTag { .. } - | Self::MigrateTags - ) - } -} - -/// Responses from a remote node via the meta protocol. -/// -/// Each variant corresponds to a [`MetaRequest`] variant. Any request may also -/// be answered with [`MetaResponse::Error`]. The same append-only rule as -/// [`MetaRequest`] applies. -/// One entry of a [`MetaResponse::List`] response (#4973). -/// -/// `origin` is the node that first wrote the file, recorded by the -/// `origin` metadata tag at write time; `uploaded_at` is the file's -/// upload time (unix seconds) from its `created` tag. Files written -/// before those tags existed carry `None` for both and list with -/// origin unknown — the values are never guessed. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ListEntry { - /// The content hash. - pub hash: Hash, - /// The tag name. - pub name: String, - /// Node id of the file's origin node, if recorded. - pub origin: Option, - /// Upload time (unix seconds), if recorded. - pub uploaded_at: Option, -} +//! Step 3b of the pkgs/id crate split (#4406): the implementation of +//! this module — the wire types, the [`MetaProtocol`] handler and the +//! framing limits — lives in `id_sync::protocol`. This facade module +//! holds the re-exports and the handler tests that run against the +//! facade's own `LocalNode` (which stays here until step 7), so every +//! historical `id::protocol` path is unchanged. -#[derive(Debug, Serialize, Deserialize)] -pub enum MetaResponse { - /// Response to [`MetaRequest::Put`]. - Put { - /// Whether the name was created/updated. - success: bool, - }, - /// Response to [`MetaRequest::Get`]. - Get { - /// The hash if found, or `None` if the name doesn't exist. - hash: Option, - }, - /// Response to [`MetaRequest::List`]. - List { - /// All names with their origin node and upload time (#4973). - items: Vec, - }, - /// Response to [`MetaRequest::Delete`]. - Delete { - /// Whether the name existed and was deleted. - success: bool, - }, - /// Response to [`MetaRequest::Rename`]. - Rename { - /// Whether the rename succeeded. - success: bool, - }, - /// Response to [`MetaRequest::Copy`]. - Copy { - /// Whether the copy succeeded. - success: bool, - }, - /// Response to [`MetaRequest::Find`]. - Find { - /// Matches, sorted by match quality. - matches: Vec, - }, - /// Response to [`MetaRequest::SetTag`]. - SetTag { - /// Whether the tag was set. - success: bool, - }, - /// Response to [`MetaRequest::DelTag`]. - DelTag { - /// Whether at least one tag was deleted. - success: bool, - /// How many tags were deleted. - deleted: u32, - }, - /// Response to [`MetaRequest::GetTags`]. - GetTags { - /// The matching tags. - tags: Vec, - }, - /// Response to [`MetaRequest::SearchTags`]. - SearchTags { - /// The matching tags. - tags: Vec, - }, - /// Response to [`MetaRequest::MigrateTags`]. - MigrateTags { - /// Number of subjects that were updated with auto-tags. - migrated: usize, - }, - /// Response to [`MetaRequest::ListPeers`]. - ListPeers { - /// Known peers as announcements. Empty if peer discovery is off. - peers: Vec, - }, - /// Response to [`MetaRequest::Whoami`]. - Whoami { - /// The responding node's ID. - node_id: EndpointId, - /// The responding node's `id` version. - version: String, - /// Whether the *caller* may perform mutating requests. - can_write: bool, - /// Whether the node lets every peer write. - open_writes: bool, - }, - /// The request was refused or failed; `message` explains why. - Error { - /// Human-readable reason. - message: String, - }, - /// Response to [`MetaRequest::AbuseCounters`]. - AbuseCounters { - /// One row per (local node, remote endpoint), already sorted by - /// local node then remote endpoint. - rows: Vec, - /// The policy rates the counters are charged against, or `None` - /// when the node exposes counters without a policy view. - policy: Option, - }, -} - -/// One row of [`MetaResponse::AbuseCounters`]: the frame and byte counters -/// admitted for one (local node, remote endpoint) pair, split by direction. -/// -/// `unattributed` holds traffic admitted through a check that does not know -/// its direction; it is never guessed into `inbound` or `outbound`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct AbuseCountersRow { - /// The local node's ID (32-byte verifying key). - pub local: [u8; 32], - /// The remote endpoint's ID (32-byte verifying key). - pub remote: [u8; 32], - /// Frames admitted inbound. - pub inbound_frames: u64, - /// Bytes admitted inbound. - pub inbound_bytes: u64, - /// Frames admitted outbound. - pub outbound_frames: u64, - /// Bytes admitted outbound. - pub outbound_bytes: u64, - /// Frames admitted without a known direction. - pub unattributed_frames: u64, - /// Bytes admitted without a known direction. - pub unattributed_bytes: u64, -} - -/// The authorized token-bucket policy rates shown alongside -/// [`AbuseCountersRow`]s. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct AbusePolicyView { - /// Authorized frames admitted per second. - pub frames_per_sec: u64, - /// Authorized frame burst. - pub frame_burst: u64, - /// Authorized bytes admitted per second. - pub bytes_per_sec: u64, - /// Authorized byte burst. - pub byte_burst: u64, -} - -impl MetaResponse { - /// If this is an [`MetaResponse::Error`], return its message. - pub fn error_message(&self) -> Option<&str> { - match self { - Self::Error { message } => Some(message), - _ => None, - } - } -} - -/// Protocol handler for the meta protocol. -/// -/// Implements Iroh's [`ProtocolHandler`] trait. When a remote node connects -/// with [`crate::META_ALPN`], each bidirectional stream carries one -/// [`MetaRequest`] and is answered with one [`MetaResponse`]. Mutating -/// requests are checked against the [`AccessPolicy`] using the authenticated -/// identity of the connection. -/// -/// ```text -/// Connection opened → identity = conn.remote_id() -/// ↓ -/// Accept bidirectional stream -/// ↓ -/// Read request → authorize (writes) → handle → send response -/// ↓ -/// Loop until connection closed -/// ``` -#[derive(Clone, Debug)] -pub struct MetaProtocol { - /// The blob store used for name operations. - pub store: Store, - /// Optional peer discovery table for the `ListPeers` RPC. - pub peer_discovery: Option, - /// Metadata tag store (iroh-docs backed). - pub tag_store: Arc, - /// Who may perform mutating requests. - pub access: AccessPolicy, - /// This node's ID (reported by `Whoami`). - pub node_id: EndpointId, - /// How long a `Put` waits for a blob that is still arriving (see - /// [`FileOps::with_blob_wait`]). Zero for in-process use. - pub blob_wait: std::time::Duration, - /// The node's abuse evaluator, when this surface exposes it. `None` - /// answers [`MetaRequest::AbuseCounters`] with an empty report. - pub abuse: Option>>, -} - -impl MetaProtocol { - /// Creates a new meta protocol handler. - /// - /// Returns an `Arc` for registration with Iroh's router. - pub fn new( - store: &Store, - peer_discovery: Option, - tag_store: Arc, - access: AccessPolicy, - node_id: EndpointId, - abuse: Option>>, - ) -> Arc { - Arc::new(Self { - store: store.clone(), - peer_discovery, - tag_store, - access, - node_id, - blob_wait: DEFAULT_BLOB_WAIT, - abuse, - }) - } - - /// Handle one request on behalf of `remote` and produce the response. - /// - /// This is the whole server-side behaviour of the protocol, independent of - /// QUIC, so it can be exercised directly in tests. - pub async fn handle(&self, remote: &EndpointId, req: MetaRequest) -> MetaResponse { - if req.is_write() && !self.access.can_write(remote) { - return MetaResponse::Error { - message: format!( - "permission denied: node {remote} may not modify this store \ - (ask the owner to run `id serve --allow-node {remote}`)" - ), - }; - } - let ops = FileOps::new(&self.store, &self.tag_store) - .with_blob_wait(self.blob_wait) - .with_origin(remote.to_string()); - let ts = &self.tag_store; - let ns = &ts.global; - match req { - MetaRequest::Put { filename, hash } => match ops.put(&filename, hash).await { - Ok(()) => MetaResponse::Put { success: true }, - Err(e) => MetaResponse::Error { - message: e.to_string(), - }, - }, - MetaRequest::Get { filename } => { - let hash = self - .store - .tags() - .get(&filename) - .await - .ok() - .flatten() - .map(|t| t.hash); - MetaResponse::Get { hash } - } - MetaRequest::List => { - let mut items = Vec::new(); - if let Ok(mut list) = self.store.tags().list().await { - while let Some(Ok(item)) = list.next().await { - let name = String::from_utf8_lossy(item.name.as_ref()).into_owned(); - items.push(ListEntry { - hash: item.hash, - name, - origin: None, - uploaded_at: None, - }); - } - } - // Enrich with origin + upload time from the metadata tags - // (#4973): `origin` is stamped at write time by FileOps, - // `created` is the upload time. Files written before the - // tags existed keep `None` and list as origin unknown. - if let Ok(tags) = self.tag_store.list_all(ns).await { - let mut origins: std::collections::HashMap = - std::collections::HashMap::new(); - let mut created: std::collections::HashMap = - std::collections::HashMap::new(); - for tag in &tags { - if tag.key == "origin" { - if let Some(value) = tag.value.as_ref().and_then(|v| v.as_str()) { - origins.insert(tag.subject.display_lossy(), value.to_owned()); - } - } else if tag.key == "created" - && let Some(ts) = tag - .value - .as_ref() - .and_then(|v| v.as_str()) - .and_then(|v| v.parse::().ok()) - { - created.insert(tag.subject.display_lossy(), ts); - } - } - for item in &mut items { - item.origin = origins.get(&item.name).cloned(); - item.uploaded_at = created.get(&item.name).copied(); - } - } - MetaResponse::List { items } - } - MetaRequest::Delete { filename } => match ops.delete(&filename).await { - Ok(outcome) => MetaResponse::Delete { - success: outcome.existed, - }, - Err(e) => MetaResponse::Error { - message: e.to_string(), - }, - }, - MetaRequest::Rename { from, to } => match ops.rename(&from, &to, true).await { - Ok(_) => MetaResponse::Rename { success: true }, - Err(FileOpError::NotFound(_)) => MetaResponse::Rename { success: false }, - Err(e) => MetaResponse::Error { - message: e.to_string(), - }, - }, - MetaRequest::Copy { from, to } => match ops.copy(&from, &to).await { - Ok(_) => MetaResponse::Copy { success: true }, - Err(FileOpError::NotFound(_)) => MetaResponse::Copy { success: false }, - Err(e) => MetaResponse::Error { - message: e.to_string(), - }, - }, - MetaRequest::Find { query, prefer_name } => MetaResponse::Find { - matches: self.find(&query, prefer_name).await, - }, - MetaRequest::SetTag { - subject, - key, - value, - } => match ts.set_tag(ns, &subject, &key, value.as_deref(), b"").await { - Ok(()) => MetaResponse::SetTag { success: true }, - Err(e) => MetaResponse::Error { - message: format!("{e:#}"), - }, - }, - MetaRequest::DelTag { - subject, - key, - value, - } => match ts - .delete_matching(ns, &subject, &key, value.as_deref()) - .await - { - Ok(n) => MetaResponse::DelTag { - success: n > 0, - deleted: u32::try_from(n).unwrap_or(u32::MAX), - }, - Err(e) => MetaResponse::Error { - message: format!("{e:#}"), - }, - }, - MetaRequest::GetTags { subject } => { - let result = match &subject { - Some(s) => ts.get_tags(ns, s).await, - None => ts.list_all(ns).await, - }; - match result { - Ok(list) => MetaResponse::GetTags { - tags: list.into_iter().map(WireTag::from).collect(), - }, - Err(e) => MetaResponse::Error { - message: format!("{e:#}"), - }, - } - } - MetaRequest::SearchTags { query } => match ts.search_by_query(ns, &query).await { - Ok(list) => MetaResponse::SearchTags { - tags: list.into_iter().map(WireTag::from).collect(), - }, - Err(e) => MetaResponse::Error { - message: format!("{e:#}"), - }, - }, - MetaRequest::MigrateTags => match ts.migrate_tags(&self.store, ns).await { - Ok(migrated) => MetaResponse::MigrateTags { migrated }, - Err(e) => MetaResponse::Error { - message: format!("{e:#}"), - }, - }, - MetaRequest::ListPeers => { - let peers = self - .peer_discovery - .as_ref() - .map(|pd| pd.peers().into_iter().map(|pi| pi.announcement).collect()) - .unwrap_or_default(); - MetaResponse::ListPeers { peers } - } - MetaRequest::Whoami => MetaResponse::Whoami { - node_id: self.node_id, - version: env!("CARGO_PKG_VERSION").to_owned(), - can_write: self.access.can_write(remote), - open_writes: self.access.is_open(), - }, - MetaRequest::AbuseCounters => { - // No evaluator attached means no world traffic is recorded: - // answer the empty report, not an error, so - // `id peers --abuse` against a plain serve succeeds. - let Some(abuse) = &self.abuse else { - return MetaResponse::AbuseCounters { - rows: Vec::new(), - policy: None, - }; - }; - // Copy the counters and the policy out under the lock, then - // release it before sorting and building rows: that work - // must not block world frame charges on the evaluator. - let (mut snapshot, authorized) = { - let Ok(guard) = abuse.lock() else { - return MetaResponse::Error { - message: - "abuse counters are unavailable: the evaluator lock is poisoned" - .to_owned(), - }; - }; - ( - guard.counters().copied_directional(), - guard.policy().authorized, - ) - }; - snapshot.sort_by(|a, b| a.0.cmp(&b.0)); - let rows = snapshot - .into_iter() - .map(|((local, remote), counters)| AbuseCountersRow { - local, - remote, - inbound_frames: counters.inbound.frames, - inbound_bytes: counters.inbound.bytes, - outbound_frames: counters.outbound.frames, - outbound_bytes: counters.outbound.bytes, - unattributed_frames: counters.unattributed.frames, - unattributed_bytes: counters.unattributed.bytes, - }) - .collect(); - MetaResponse::AbuseCounters { - rows, - policy: Some(AbusePolicyView { - frames_per_sec: authorized.frames_per_sec, - frame_burst: authorized.frame_burst, - bytes_per_sec: authorized.bytes_per_sec, - byte_burst: authorized.byte_burst, - }), - } - } - } - } - - /// Rank blob names and hashes against `query`. - async fn find(&self, query: &str, prefer_name: bool) -> Vec { - let mut matches = Vec::new(); - let query_lower = query.to_lowercase(); - if let Ok(mut list) = self.store.tags().list().await { - while let Some(Ok(item)) = list.next().await { - let name = String::from_utf8_lossy(item.name.as_ref()).into_owned(); - let hash_str = item.hash.to_string(); - if let Some(kind) = crate::match_kind(&name.to_lowercase(), &query_lower) { - matches.push(FindMatch { - hash: item.hash, - name, - kind, - is_hash_match: false, - }); - } else if let Some(kind) = crate::match_kind(&hash_str, &query_lower) { - matches.push(FindMatch { - hash: item.hash, - name, - kind, - is_hash_match: true, - }); - } - } - } - // Best kind first; ties prefer name matches (`prefer_name`) or hash matches. - matches.sort_by(|a, b| { - a.kind.cmp(&b.kind).then_with(|| { - if prefer_name { - a.is_hash_match.cmp(&b.is_hash_match) - } else { - b.is_hash_match.cmp(&a.is_hash_match) - } - }) - }); - matches - } - - async fn accept_connection( - &self, - conn: Connection, - stream_deadline: Duration, - ) -> Result<(), AcceptError> { - let remote = conn.remote_id(); - let permits = Arc::new(Semaphore::new(MAX_META_STREAMS_PER_CONNECTION)); - let mut streams = JoinSet::new(); - - loop { - tokio::select! { - incoming = conn.accept_bi() => { - let Ok((mut send, recv)) = incoming else { - break; - }; - let Ok(permit) = Arc::clone(&permits).try_acquire_owned() else { - // Refuse only this stream; the connection remains usable. - let _ = send.reset(1_u32.into()); - continue; - }; - let protocol = self.clone(); - streams.spawn(async move { - let _permit = permit; - protocol - .handle_stream(remote, send, recv, stream_deadline) - .await; - }); - } - Some(result) = streams.join_next(), if !streams.is_empty() => { - if let Err(error) = result { - tracing::warn!(%error, "meta stream handler task failed"); - } - } - } - } - - // The peer closed the connection. Drain admitted handlers instead - // of aborting them: shutdown() would cancel a handler at its next - // suspension point, and a mutating handler cancelled mid-flight - // (e.g. FileOps::rename, which deletes the source before awaiting - // the metadata transfer) can leave partial state behind. Each - // handler's network phases stay bounded by the stream deadline, - // so this drain terminates. - while let Some(result) = streams.join_next().await { - if let Err(error) = result { - tracing::warn!(%error, "meta stream handler task failed"); - } - } - Ok(()) - } - - async fn handle_stream( - &self, - remote: EndpointId, - mut send: iroh::endpoint::SendStream, - mut recv: iroh::endpoint::RecvStream, - stream_deadline: Duration, - ) { - // Phase 1: read the request under the deadline. A stalled or - // trickling peer is cut off here, without affecting other streams. - let buf = match tokio::time::timeout(stream_deadline, recv.read_to_end(MAX_REQUEST_BYTES)) - .await - { - Ok(Ok(buf)) => buf, - Ok(Err(error)) => { - tracing::debug!(%remote, %error, "meta stream read failed"); - return; - } - Err(_) => { - tracing::debug!(%remote, ?stream_deadline, "meta stream read deadline exceeded"); - let _ = send.reset(1_u32.into()); - return; - } - }; - - // Phase 2: handle the admitted request to completion. This is - // deliberately NOT wrapped in the deadline: handlers perform - // non-transactional mutations (e.g. FileOps::rename moves a blob and - // then transfers metadata), and cancelling one midway would corrupt - // state. The handler does no peer-controlled waiting — the network - // phases on either side of it carry the deadline. - let resp = match decode_meta_exact::(&buf) { - Ok(req) => self.handle(&remote, req).await, - Err(error) => MetaResponse::Error { - message: format!("malformed request: {error}"), - }, - }; - - // Phase 3: write the response under the deadline; a peer that stops - // reading is cut off and its stream reset. - let written = tokio::time::timeout(stream_deadline, async { - let bytes = postcard::to_allocvec(&resp).map_err(AcceptError::from_err)?; - send.write_all(&bytes) - .await - .map_err(AcceptError::from_err)?; - send.finish()?; - Ok::<(), AcceptError>(()) - }) - .await; - - match written { - Ok(Ok(())) => {} - Ok(Err(error)) => tracing::debug!(%remote, %error, "meta stream failed"), - Err(_) => { - tracing::debug!(%remote, ?stream_deadline, "meta stream write deadline exceeded"); - let _ = send.reset(1_u32.into()); - } - } - } -} - -impl ProtocolHandler for MetaProtocol { - /// Serves requests on a connection until the peer closes it. - /// Individual stream failures are isolated; active streams are stopped when - /// the peer closes the connection. - async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { - self.accept_connection(conn, META_STREAM_DEADLINE).await - } -} +pub use id_sync::protocol::*; #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -1016,11 +18,24 @@ mod tests { endpoint::{Endpoint, RelayMode, presets}, protocol::Router, }; - use iroh_base::{SecretKey, TransportAddr}; + use iroh_base::{EndpointId, SecretKey, TransportAddr}; use std::net::{Ipv4Addr, SocketAddr}; use crate::{META_ALPN, local::LocalNode}; + use anyhow::Result; + use iroh::endpoint::Connection; + use iroh::protocol::{AcceptError, ProtocolHandler}; + use iroh_blobs::Hash; + use std::sync::Arc; + use std::time::Duration; + + use crate::access::AccessPolicy; + + fn eid(n: u8) -> EndpointId { + iroh_base::SecretKey::from_bytes(&[n; 32]).public() + } + #[derive(Clone, Debug)] struct DeadlineMetaProtocol { protocol: Arc, @@ -1093,613 +108,6 @@ mod tests { server.node.shutdown().await.unwrap(); } - #[test] - fn test_find_match_struct() { - let hash = Hash::from_bytes([0u8; 32]); - let m = FindMatch { - hash, - name: "test.txt".to_owned(), - kind: MatchKind::Exact, - is_hash_match: false, - }; - assert_eq!(m.name, "test.txt"); - assert_eq!(m.kind, MatchKind::Exact); - assert!(!m.is_hash_match); - } - - #[test] - fn test_tagged_match_struct() { - let hash = Hash::from_bytes([0u8; 32]); - let m = TaggedMatch { - query: "test".to_owned(), - hash, - name: "test.txt".to_owned(), - kind: MatchKind::Prefix, - is_hash_match: true, - }; - assert_eq!(m.query, "test"); - assert_eq!(m.kind, MatchKind::Prefix); - assert!(m.is_hash_match); - } - - #[test] - fn meta_decode_requires_full_consumption() { - let list = postcard::to_allocvec(&MetaRequest::List).unwrap(); - assert!(matches!( - decode_meta_exact::(&list), - Ok(MetaRequest::List) - )); - - let mut padded_list = list.clone(); - padded_list.push(0); - assert!(decode_meta_exact::(&padded_list).is_err()); - - let mut garbage_list = list; - garbage_list.extend_from_slice(b"GARBAGE"); - assert!(decode_meta_exact::(&garbage_list).is_err()); - - let delete = MetaRequest::Delete { - filename: "victim.txt".to_owned(), - }; - let mut padded_delete = postcard::to_allocvec(&delete).unwrap(); - padded_delete.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); - assert!(decode_meta_exact::(&padded_delete).is_err()); - - let mut double_request = postcard::to_allocvec(&delete).unwrap(); - double_request.extend_from_slice(&postcard::to_allocvec(&MetaRequest::List).unwrap()); - assert!(decode_meta_exact::(&double_request).is_err()); - - let response = MetaResponse::Delete { success: true }; - let mut padded_response = postcard::to_allocvec(&response).unwrap(); - padded_response.extend_from_slice(b"EXTRA"); - assert!(decode_meta_exact::(&padded_response).is_err()); - - assert!(matches!( - decode_meta_exact::(&postcard::to_allocvec(&response).unwrap()), - Ok(MetaResponse::Delete { success: true }) - )); - } - - #[test] - fn test_meta_request_serialization() { - // Test Put - let req = MetaRequest::Put { - filename: "test.txt".to_owned(), - hash: Hash::from_bytes([0u8; 32]), - }; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaRequest::Put { filename, .. } => assert_eq!(filename, "test.txt"), - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_request_get_serialization() { - let req = MetaRequest::Get { - filename: "myfile.txt".to_owned(), - }; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaRequest::Get { filename } => assert_eq!(filename, "myfile.txt"), - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_request_list_serialization() { - let req = MetaRequest::List; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - assert!(matches!(decoded, MetaRequest::List)); - } - - #[test] - fn test_meta_request_delete_serialization() { - let req = MetaRequest::Delete { - filename: "to_delete.txt".to_owned(), - }; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaRequest::Delete { filename } => assert_eq!(filename, "to_delete.txt"), - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_request_rename_serialization() { - let req = MetaRequest::Rename { - from: "old.txt".to_owned(), - to: "new.txt".to_owned(), - }; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaRequest::Rename { from, to } => { - assert_eq!(from, "old.txt"); - assert_eq!(to, "new.txt"); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_request_copy_serialization() { - let req = MetaRequest::Copy { - from: "source.txt".to_owned(), - to: "dest.txt".to_owned(), - }; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaRequest::Copy { from, to } => { - assert_eq!(from, "source.txt"); - assert_eq!(to, "dest.txt"); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_request_find_serialization() { - let req = MetaRequest::Find { - query: "search term".to_owned(), - prefer_name: true, - }; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaRequest::Find { query, prefer_name } => { - assert_eq!(query, "search term"); - assert!(prefer_name); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_put_serialization() { - let resp = MetaResponse::Put { success: true }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::Put { success } => assert!(success), - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_get_serialization() { - let hash = Hash::from_bytes([1u8; 32]); - let resp = MetaResponse::Get { hash: Some(hash) }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::Get { hash: h } => { - assert!(h.is_some()); - assert_eq!(h.unwrap(), hash); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_get_none_serialization() { - let resp = MetaResponse::Get { hash: None }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::Get { hash } => assert!(hash.is_none()), - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_list_serialization() { - let hash1 = Hash::from_bytes([1u8; 32]); - let hash2 = Hash::from_bytes([2u8; 32]); - let resp = MetaResponse::List { - items: vec![ - ListEntry { - hash: hash1, - name: "file1.txt".to_owned(), - origin: Some("node-a".to_owned()), - uploaded_at: Some(1_700_000_000), - }, - ListEntry { - hash: hash2, - name: "file2.txt".to_owned(), - origin: None, - uploaded_at: None, - }, - ], - }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::List { items } => { - assert_eq!(items.len(), 2); - assert_eq!(items[0].name, "file1.txt"); - assert_eq!(items[0].origin.as_deref(), Some("node-a")); - assert_eq!(items[0].uploaded_at, Some(1_700_000_000)); - assert_eq!(items[1].name, "file2.txt"); - assert_eq!(items[1].origin, None); - assert_eq!(items[1].uploaded_at, None); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_find_serialization() { - let hash = Hash::from_bytes([0u8; 32]); - let matches = vec![FindMatch { - hash, - name: "found.txt".to_owned(), - kind: MatchKind::Exact, - is_hash_match: false, - }]; - let resp = MetaResponse::Find { matches }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::Find { matches } => { - assert_eq!(matches.len(), 1); - assert_eq!(matches[0].name, "found.txt"); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_match_kind_serialization() { - for kind in [MatchKind::Exact, MatchKind::Prefix, MatchKind::Contains] { - let bytes = postcard::to_allocvec(&kind).unwrap(); - let decoded: MatchKind = postcard::from_bytes(&bytes).unwrap(); - assert_eq!(decoded, kind); - } - } - - #[test] - fn test_find_match_serialization() { - let hash = Hash::from_bytes([5u8; 32]); - let m = FindMatch { - hash, - name: "serialized.txt".to_owned(), - kind: MatchKind::Contains, - is_hash_match: true, - }; - let bytes = postcard::to_allocvec(&m).unwrap(); - let decoded: FindMatch = postcard::from_bytes(&bytes).unwrap(); - assert_eq!(decoded.hash, hash); - assert_eq!(decoded.name, "serialized.txt"); - assert_eq!(decoded.kind, MatchKind::Contains); - assert!(decoded.is_hash_match); - } - - #[test] - fn test_meta_request_list_peers_serialization() { - let req = MetaRequest::ListPeers; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - assert!(matches!(decoded, MetaRequest::ListPeers)); - } - - #[test] - fn test_meta_response_list_peers_empty_serialization() { - let resp = MetaResponse::ListPeers { peers: vec![] }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::ListPeers { peers } => assert!(peers.is_empty()), - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_list_peers_with_peers_serialization() { - use iroh_base::SecretKey; - - let node_id_1 = SecretKey::from_bytes(&[1u8; 32]).public(); - let node_id_2 = SecretKey::from_bytes(&[2u8; 32]).public(); - - let peers = vec![ - PeerAnnouncement { - node_id: node_id_1, - name: Some("peer-alpha".to_owned()), - blob_count: 42, - timestamp_secs: 1_700_000_000, - }, - PeerAnnouncement { - node_id: node_id_2, - name: None, - blob_count: 0, - timestamp_secs: 1_700_000_030, - }, - ]; - let resp = MetaResponse::ListPeers { peers }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::ListPeers { - peers: decoded_peers, - } => { - assert_eq!(decoded_peers.len(), 2); - assert_eq!(decoded_peers[0].node_id, node_id_1); - assert_eq!(decoded_peers[0].name, Some("peer-alpha".to_owned())); - assert_eq!(decoded_peers[0].blob_count, 42); - assert_eq!(decoded_peers[1].node_id, node_id_2); - assert_eq!(decoded_peers[1].name, None); - assert_eq!(decoded_peers[1].blob_count, 0); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_request_abuse_counters_serialization() { - let req = MetaRequest::AbuseCounters; - let bytes = postcard::to_allocvec(&req).unwrap(); - let decoded: MetaRequest = postcard::from_bytes(&bytes).unwrap(); - assert!(matches!(decoded, MetaRequest::AbuseCounters)); - } - - #[test] - fn test_meta_response_abuse_counters_serialization() { - let resp = MetaResponse::AbuseCounters { - rows: vec![AbuseCountersRow { - local: [1u8; 32], - remote: [2u8; 32], - inbound_frames: 3, - inbound_bytes: 300, - outbound_frames: 4, - outbound_bytes: 400, - unattributed_frames: 5, - unattributed_bytes: 500, - }], - policy: Some(AbusePolicyView { - frames_per_sec: 100, - frame_burst: 180, - bytes_per_sec: 1_048_576, - byte_burst: 2_097_152, - }), - }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::AbuseCounters { rows, policy } => { - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].local, [1u8; 32]); - assert_eq!(rows[0].remote, [2u8; 32]); - assert_eq!(rows[0].inbound_frames, 3); - assert_eq!(rows[0].inbound_bytes, 300); - assert_eq!(rows[0].outbound_frames, 4); - assert_eq!(rows[0].outbound_bytes, 400); - assert_eq!(rows[0].unattributed_frames, 5); - assert_eq!(rows[0].unattributed_bytes, 500); - let view = policy.expect("policy"); - assert_eq!(view.frames_per_sec, 100); - assert_eq!(view.frame_burst, 180); - assert_eq!(view.bytes_per_sec, 1_048_576); - assert_eq!(view.byte_burst, 2_097_152); - } - _ => panic!("Wrong variant"), - } - } - - #[test] - fn test_meta_response_abuse_counters_empty_serialization() { - let resp = MetaResponse::AbuseCounters { - rows: vec![], - policy: None, - }; - let bytes = postcard::to_allocvec(&resp).unwrap(); - let decoded: MetaResponse = postcard::from_bytes(&bytes).unwrap(); - match decoded { - MetaResponse::AbuseCounters { rows, policy } => { - assert!(rows.is_empty()); - assert!(policy.is_none()); - } - _ => panic!("Wrong variant"), - } - } - - // ======================================================================== - // Wire format - // ======================================================================== - - fn eid(n: u8) -> EndpointId { - iroh_base::SecretKey::from_bytes(&[n; 32]).public() - } - - #[test] - fn wire_format_is_pinned() { - // postcard encodes the enum variant index as the first byte. These - // indices are the wire format of `/iroh-meta/3`: within a version only - // append new variants; anything else needs a new ALPN. - let h = Hash::from_bytes([0u8; 32]); - let s = String::from("x"); - let requests: Vec<(MetaRequest, u8)> = vec![ - ( - MetaRequest::Put { - filename: s.clone(), - hash: h, - }, - 0, - ), - ( - MetaRequest::Get { - filename: s.clone(), - }, - 1, - ), - (MetaRequest::List, 2), - ( - MetaRequest::Delete { - filename: s.clone(), - }, - 3, - ), - ( - MetaRequest::Rename { - from: s.clone(), - to: s.clone(), - }, - 4, - ), - ( - MetaRequest::Copy { - from: s.clone(), - to: s.clone(), - }, - 5, - ), - ( - MetaRequest::Find { - query: s.clone(), - prefer_name: false, - }, - 6, - ), - ( - MetaRequest::SetTag { - subject: vec![], - key: vec![], - value: None, - }, - 7, - ), - ( - MetaRequest::DelTag { - subject: vec![], - key: vec![], - value: None, - }, - 8, - ), - (MetaRequest::GetTags { subject: None }, 9), - (MetaRequest::SearchTags { query: s.clone() }, 10), - (MetaRequest::MigrateTags, 11), - (MetaRequest::ListPeers, 12), - (MetaRequest::Whoami, 13), - (MetaRequest::AbuseCounters, 14), - ]; - for (req, idx) in &requests { - let bytes = postcard::to_allocvec(req).unwrap(); - assert_eq!(bytes[0], *idx, "request {req:?}"); - } - let responses: Vec<(MetaResponse, u8)> = vec![ - (MetaResponse::Put { success: true }, 0), - (MetaResponse::Get { hash: None }, 1), - (MetaResponse::List { items: vec![] }, 2), - (MetaResponse::Delete { success: true }, 3), - (MetaResponse::Rename { success: true }, 4), - (MetaResponse::Copy { success: true }, 5), - (MetaResponse::Find { matches: vec![] }, 6), - (MetaResponse::SetTag { success: true }, 7), - ( - MetaResponse::DelTag { - success: true, - deleted: 1, - }, - 8, - ), - (MetaResponse::GetTags { tags: vec![] }, 9), - (MetaResponse::SearchTags { tags: vec![] }, 10), - (MetaResponse::MigrateTags { migrated: 0 }, 11), - (MetaResponse::ListPeers { peers: vec![] }, 12), - ( - MetaResponse::Whoami { - node_id: eid(1), - version: "0".to_owned(), - can_write: true, - open_writes: false, - }, - 13, - ), - (MetaResponse::Error { message: s }, 14), - ( - MetaResponse::AbuseCounters { - rows: vec![], - policy: None, - }, - 15, - ), - ]; - for (resp, idx) in &responses { - let bytes = postcard::to_allocvec(resp).unwrap(); - assert_eq!(bytes[0], *idx, "response {resp:?}"); - } - } - - #[test] - fn is_write_classifies_every_request() { - let h = Hash::from_bytes([0u8; 32]); - let s = String::from("x"); - for req in [ - MetaRequest::Put { - filename: s.clone(), - hash: h, - }, - MetaRequest::Delete { - filename: s.clone(), - }, - MetaRequest::Rename { - from: s.clone(), - to: s.clone(), - }, - MetaRequest::Copy { - from: s.clone(), - to: s.clone(), - }, - MetaRequest::SetTag { - subject: vec![], - key: vec![], - value: None, - }, - MetaRequest::DelTag { - subject: vec![], - key: vec![], - value: None, - }, - MetaRequest::MigrateTags, - ] { - assert!(req.is_write(), "{req:?} must require write access"); - } - for req in [ - MetaRequest::Get { - filename: s.clone(), - }, - MetaRequest::List, - MetaRequest::Find { - query: s.clone(), - prefer_name: true, - }, - MetaRequest::GetTags { subject: None }, - MetaRequest::SearchTags { query: s }, - MetaRequest::ListPeers, - MetaRequest::Whoami, - MetaRequest::AbuseCounters, - ] { - assert!(!req.is_write(), "{req:?} is read-only"); - } - } - - #[test] - fn wire_tag_keeps_binary_values_intact() { - let tag = WireTag { - subject: b"f".to_vec(), - key: b"k".to_vec(), - value: Some(vec![0xff, 0xfe, 0x00, 0x80]), - }; - let bytes = postcard::to_allocvec(&tag).unwrap(); - let back: WireTag = postcard::from_bytes(&bytes).unwrap(); - assert_eq!(back, tag); - } - // ======================================================================== // Handler behaviour against real iroh-blobs + iroh-docs (in memory) // ========================================================================