From a3f6b1e0a488c5fc9332fd10768a4e5186bb9362 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 17:28:32 -0600 Subject: [PATCH] =?UTF-8?q?id:=20server-to-server=20file=20transfer=20(sen?= =?UTF-8?q?d)=20=E2=80=94=20#5345,=20ported=20to=20the=20crates=20layout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port of PR #7905 (queue/13937-5345-server-transfer @ 261352a) onto current main: main restructured pkgs/id into crates since the original implementation, so the send/transfer feature is re-homed — transfer.rs and push_and_name into id-sync (meta_client), MetaRequest/MetaResponse Send wire variants appended (req disc 15 / resp disc 16 per the append-only rule), CLI send command + REPL/serve/local wiring in id-cli, facade tests/transfer.rs. One borrow fix in the ported protocol discriminant test (s.clone()). Verified (queue task 17268): cargo check -p id-sync -p id-cli -p id passes; cargo test -p id-sync -p id: 49 suites ok, only failure is the pre-existing toolchain_pin docs test (README/WEB name Rust 1.99.0 vs pin 1.99.1, already so on the base commit); cargo test -p id --test transfer: 4 passed. --- pkgs/id/README.md | 1 + pkgs/id/crates/id-cli/src/cli/mod.rs | 40 ++++ pkgs/id/crates/id-cli/src/commands/mod.rs | 2 + pkgs/id/crates/id-cli/src/commands/put.rs | 84 +------- pkgs/id/crates/id-cli/src/commands/repl.rs | 47 +++++ pkgs/id/crates/id-cli/src/commands/send.rs | 98 +++++++++ pkgs/id/crates/id-cli/src/commands/serve.rs | 7 +- pkgs/id/crates/id-cli/src/local.rs | 14 +- pkgs/id/crates/id-cli/src/repl/runner.rs | 18 ++ pkgs/id/crates/id-sync/src/lib.rs | 1 + pkgs/id/crates/id-sync/src/meta_client.rs | 75 ++++++- pkgs/id/crates/id-sync/src/protocol.rs | 131 +++++++++++- pkgs/id/crates/id-sync/src/transfer.rs | 217 ++++++++++++++++++++ pkgs/id/src/lib.rs | 8 +- pkgs/id/src/main.rs | 8 + pkgs/id/tests/transfer.rs | 202 ++++++++++++++++++ 16 files changed, 873 insertions(+), 80 deletions(-) create mode 100644 pkgs/id/crates/id-cli/src/commands/send.rs create mode 100644 pkgs/id/crates/id-sync/src/transfer.rs create mode 100644 pkgs/id/tests/transfer.rs diff --git a/pkgs/id/README.md b/pkgs/id/README.md index e8ad5f640c..035bb252e4 100644 --- a/pkgs/id/README.md +++ b/pkgs/id/README.md @@ -141,6 +141,7 @@ it is — a valid world capability, minted by the host's admin with | `repl` | `shell` | Interactive REPL with pipes and subshells | | `put` | `in`, `add`, `store`, `import` | Store files in blob store | | `put-hash` | | Store content by hash only (no named tag) | +| `send` | | Copy a file from one server to another | | `get` | | Retrieve files by name or hash | | `get-hash` | | Retrieve file by hash with explicit output path | | `cat` | `output`, `out` | Output file content to stdout | diff --git a/pkgs/id/crates/id-cli/src/cli/mod.rs b/pkgs/id/crates/id-cli/src/cli/mod.rs index 9ce60021ed..14e1f3f45d 100644 --- a/pkgs/id/crates/id-cli/src/cli/mod.rs +++ b/pkgs/id/crates/id-cli/src/cli/mod.rs @@ -14,6 +14,7 @@ //! repl Interactive REPL (alias: shell) //! put Store files (aliases: in, add, store, import) //! put-hash Store content by hash only +//! send Copy a file from one server to another //! get Retrieve files by name or hash //! get-hash Retrieve by hash (shortcut) //! cat Output files to stdout (aliases: output, out) @@ -747,6 +748,45 @@ pub enum Command { /// File path to store, or "-" for stdin. source: String, }, + /// Copy a file from one running server to another (server-to-server send). + /// + /// The *source server* performs the transfer with its own identity: + /// it pushes the file's blob to the destination and registers the + /// name there. The destination's write policy must allow the source + /// server's node ID, and that node is recorded as the copy's origin. + /// No file bytes pass through this client. + /// + /// # Examples + /// + /// ```bash + /// # Copy report.txt from server A to server B under the same name + /// id send A_NODE_ID report.txt --to B_NODE_ID + /// + /// # Copy under a different destination name + /// id send A_NODE_ID report.txt --to B_NODE_ID --as summary.txt + /// + /// # Replace an existing destination name (old file is archived first) + /// id send A_NODE_ID report.txt --to B_NODE_ID --replace + /// ``` + Send { + /// Source server node ID (64 hex characters). + source: String, + /// Name of the file on the source server. + name: String, + /// Destination server node ID (64 hex characters). + #[arg(long)] + to: String, + /// Name to register on the destination (defaults to the source name). + #[arg(long = "as")] + dest_name: Option, + /// Replace an existing, different destination file; the old file + /// is preserved under an archive name on the destination first. + #[arg(long)] + replace: bool, + /// Disable relay servers for the connection to the source. + #[arg(long)] + no_relay: bool, + }, /// Retrieve one or more files by name or hash. /// /// Files can be written to different output paths using `source:output`. diff --git a/pkgs/id/crates/id-cli/src/commands/mod.rs b/pkgs/id/crates/id-cli/src/commands/mod.rs index 89498753e5..e9f42fd7b5 100644 --- a/pkgs/id/crates/id-cli/src/commands/mod.rs +++ b/pkgs/id/crates/id-cli/src/commands/mod.rs @@ -69,6 +69,7 @@ pub mod match_audit; pub mod peers; pub mod put; pub mod repl; +pub mod send; pub mod serve; pub mod tag; pub mod text; @@ -95,6 +96,7 @@ pub use put::{ cmd_put_one_remote, }; pub use repl::{ReplContext, ReplContextInner}; +pub use send::cmd_send; pub use serve::{ ServeInfo, ServeOptions, build_access_policy, cmd_serve, create_serve_lock, get_serve_info, is_process_alive, remove_serve_lock, diff --git a/pkgs/id/crates/id-cli/src/commands/put.rs b/pkgs/id/crates/id-cli/src/commands/put.rs index 675e24f63a..86e9598c22 100644 --- a/pkgs/id/crates/id-cli/src/commands/put.rs +++ b/pkgs/id/crates/id-cli/src/commands/put.rs @@ -63,16 +63,6 @@ use std::io::IsTerminal; use std::path::PathBuf; use tokio::fs as afs; -use crate::local::LocalNode; -use crate::meta_client::{expect_ok, request_over}; -use crate::{ - CLIENT_KEY_FILE, META_ALPN, MetaRequest, MetaResponse, create_local_client_endpoint, - get_serve_info, is_node_id, load_or_create_keypair, open_store, parse_put_spec, - parse_stdin_items, read_input, -}; - -const PUT_FINALIZATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2 * 60); - /// Add `data` to `store` as a raw blob; returns its hash and a guard that keeps /// the blob protected until dropped (hold it until the blob has been named). pub async fn add_raw(store: &Store, data: Vec) -> Result<(Hash, TempTag)> { @@ -89,70 +79,16 @@ pub async fn add_raw(store: &Store, data: Vec) -> Result<(Hash, TempTag)> { Ok((guard.hash(), guard)) } -/// Upload `hash` to `target`, **then** register `name` for it. -/// -/// Two ordering rules make this safe: -/// -/// 1. **Bytes before name.** The server verifies the blob is present before it -/// creates a name, so a failed upload can never leave a dangling name. -/// 2. **Keep the blobs connection open until the server confirms.** A push is -/// one-way — the server sends no acknowledgement — and closing the QUIC -/// connection right after the last write can abort the server's import of -/// data it has buffered but not yet processed. The `Put` request is the -/// acknowledgement: the server answers it once the blob is complete, so we -/// close the blobs connection only after that. -/// -/// A `Put` for a blob that is still being finalized is retried for up to two -/// minutes (large blobs take a moment to finish on the server). -pub async fn push_and_name( - store: &Store, - endpoint: &Endpoint, - target: EndpointAddr, - name: &str, - hash: Hash, -) -> Result<()> { - let blobs_conn = id_core::connectivity::connect(endpoint, target.clone(), BLOBS_ALPN).await?; - let push_request = PushRequest::new(hash, ChunkRangesSeq::from_ranges([ChunkRanges::all()])); - store - .remote() - .execute_push(blobs_conn.clone(), push_request) - .await - .context( - "blob push rejected: the server only accepts writes from allowed nodes \ - (run `id id --client` on this machine and add the printed ID to the \ - server's `--allow-node` or `.iroh-allowed`)", - )?; - - let meta_conn = id_core::connectivity::connect(endpoint, target, META_ALPN).await?; - let req = MetaRequest::Put { - filename: name.to_owned(), - hash, - }; - let outcome = id_core::connectivity::within( - PUT_FINALIZATION_TIMEOUT, - "registering the blob name", - async { - loop { - match request_over(&meta_conn, &req).await? { - MetaResponse::Error { message } - if id_sync::fileops::is_blob_missing_message(&message) => - { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - } - response => return Ok(response), - } - } - }, - ) - .await; - meta_conn.close(0u32.into(), b"done"); - blobs_conn.close(0u32.into(), b"done"); - match expect_ok(outcome?)? { - MetaResponse::Put { success: true } => Ok(()), - MetaResponse::Put { success: false } => bail!("server rejected"), - _ => bail!("unexpected response"), - } -} +pub use id_sync::meta_client::push_and_name; + +use crate::local::LocalNode; +use crate::meta_client::{expect_ok, request_over}; +use crate::{ + CLIENT_KEY_FILE, META_ALPN, MetaRequest, MetaResponse, create_local_client_endpoint, + get_serve_info, is_node_id, load_or_create_keypair, open_store, parse_put_spec, + parse_stdin_items, read_input, +}; + /// Trim a name typed at the forgiving CLI surface before FileOps sees it. /// diff --git a/pkgs/id/crates/id-cli/src/commands/repl.rs b/pkgs/id/crates/id-cli/src/commands/repl.rs index 4295bb4d6b..837b77329d 100644 --- a/pkgs/id/crates/id-cli/src/commands/repl.rs +++ b/pkgs/id/crates/id-cli/src/commands/repl.rs @@ -738,6 +738,53 @@ impl ReplContext { Ok(()) } + /// Ask this context's node (the source) to copy a file to another + /// server (#5345). + /// + /// The source server performs the transfer with its own identity; see + /// [`id_sync::transfer`]. `dest_name` defaults to `name`; with + /// `replace`, an existing different destination file is archived and + /// replaced instead of refusing the send. + pub async fn send( + &mut self, + name: &str, + dest_str: &str, + dest_name: Option<&str>, + replace: bool, + ) -> Result<()> { + if !is_node_id(dest_str) { + bail!("invalid destination node ID: must be 64 hex characters"); + } + let dest: EndpointId = dest_str.parse()?; + let req = MetaRequest::Send { + name: name.to_owned(), + dest, + dest_name: dest_name.map(ToOwned::to_owned), + replace, + }; + match expect_ok(self.request(req).await?)? { + MetaResponse::Send { + hash, + name: registered, + already_present, + replaced, + .. + } => { + if already_present { + println!("already present: {name} -> {dest}:{registered} ({hash})"); + } else if replaced { + println!( + "sent: {name} -> {dest}:{registered} ({hash}); previous file archived" + ); + } else { + println!("sent: {name} -> {dest}:{registered} ({hash})"); + } + Ok(()) + } + _ => bail!("unexpected response"), + } + } + /// Search for blobs matching a query. /// /// Performs case-insensitive matching against tag names and blob hashes. diff --git a/pkgs/id/crates/id-cli/src/commands/send.rs b/pkgs/id/crates/id-cli/src/commands/send.rs new file mode 100644 index 0000000000..a535a0b4d6 --- /dev/null +++ b/pkgs/id/crates/id-cli/src/commands/send.rs @@ -0,0 +1,98 @@ +//! `id send` — copy a file from one running server to another (#5345). +//! +//! The command only *asks* the source server to perform the transfer: the +//! source server reads its stored file and pushes it to the destination +//! with its own server identity (see [`id_sync::transfer`]). The local CLI +//! client key is never the sending identity, and no file bytes pass +//! through this process. +//! +//! ```bash +//! # Copy report.txt from server A to server B under the same name +//! id send A_NODE_ID report.txt --to B_NODE_ID +//! +//! # Copy under a different destination name +//! id send A_NODE_ID report.txt --to B_NODE_ID --as summary.txt +//! +//! # Replace an existing destination name (the old file is archived first) +//! id send A_NODE_ID report.txt --to B_NODE_ID --replace +//! ``` + +use anyhow::{Result, bail}; +use iroh_base::EndpointId; + +use crate::is_node_id; +use crate::meta_client::{MetaClient, MetaRequester, expect_ok}; +use crate::protocol::{MetaRequest, MetaResponse}; + +/// Trim a name typed at the CLI surface (FileOps stores names verbatim and +/// refuses padding, so a stray space is a typing slip, as in `id put`). +fn trim_surface_name(name: &str) -> &str { + name.trim() +} + +/// Ask the server `source` to copy its file `name` to the server `to`. +/// +/// `dest_name` defaults to `name`. With `replace`, an existing different +/// file at the destination name is archived and replaced; without it, a +/// conflict is an error and nothing is sent. +pub async fn cmd_send( + source: &str, + name: &str, + to: &str, + dest_name: Option, + replace: bool, + no_relay: bool, +) -> Result<()> { + if !is_node_id(source) { + bail!("invalid source node ID: must be 64 hex characters"); + } + if !is_node_id(to) { + bail!("invalid destination node ID: must be 64 hex characters"); + } + let source_id: EndpointId = source.parse()?; + let dest_id: EndpointId = to.parse()?; + let name = trim_surface_name(name); + let dest_name = dest_name.as_deref().map(trim_surface_name); + + let mut client = MetaClient::connect_node(source_id, no_relay).await?; + let resp = client + .request(MetaRequest::Send { + name: name.to_owned(), + dest: dest_id, + dest_name: dest_name.map(ToOwned::to_owned), + replace, + }) + .await; + let resp = match resp { + Ok(resp) => resp, + Err(e) => { + let _ = client.close().await; + return Err(e); + } + }; + let result = match expect_ok(resp)? { + MetaResponse::Send { + hash, + name: registered, + dest, + already_present, + replaced, + } => { + if already_present { + println!( + "already present: {name} -> {dest}:{registered} ({hash}); nothing to send" + ); + } else if replaced { + println!( + "sent: {name} -> {dest}:{registered} ({hash}); previous file archived on the destination" + ); + } else { + println!("sent: {name} -> {dest}:{registered} ({hash})"); + } + Ok(()) + } + _ => bail!("unexpected response"), + }; + client.close().await?; + result +} diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index fbe90fa869..531821dad9 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -1852,7 +1852,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { let abuse_handle: Option>> = None; - let meta = MetaProtocol::new( + let mut meta = MetaProtocol::new( &store_handle, Some(peer_discovery.clone()), Arc::clone(&tag_store), @@ -1860,6 +1860,11 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { node_id, abuse_handle, ); + // Server-to-server transfers (#5345) are initiated from this handler + // with the server's own endpoint and identity. + if let Some(inner) = Arc::get_mut(&mut meta) { + inner.endpoint = Some(endpoint.clone()); + } #[cfg(all(feature = "world", feature = "ssh"))] let (ssh_tunnel, ssh_tunnel_port) = id_worlds::world_ssh::SshTunnelProtocol::deferred(); diff --git a/pkgs/id/crates/id-cli/src/local.rs b/pkgs/id/crates/id-cli/src/local.rs index 0cdd69e4da..a3ed8e259f 100644 --- a/pkgs/id/crates/id-cli/src/local.rs +++ b/pkgs/id/crates/id-cli/src/local.rs @@ -134,6 +134,9 @@ impl LocalNode { // Nothing is in flight for an in-process node: a missing blob is missing. if let Some(inner) = Arc::get_mut(&mut m) { inner.blob_wait = std::time::Duration::ZERO; + // The in-process handler answers with this node's own + // endpoint, so an offline `send` behaves like an online one. + inner.endpoint = Some(endpoint.clone()); } m }; @@ -194,6 +197,12 @@ impl LocalNode { self.node_id } + /// This node's QUIC endpoint (bound on loopback; its identity is the + /// node's key). Used by the transfer module to dial peers as this node. + pub fn endpoint(&self) -> &Endpoint { + &self.endpoint + } + /// Dialable address of this node on loopback (for in-process tests and /// same-machine clients; no discovery is involved). pub fn addr(&self) -> EndpointAddr { @@ -212,7 +221,7 @@ impl LocalNode { /// Used by tests and by programs embedding an `id` node. Shut the returned /// router down before [`LocalNode::shutdown`]. pub fn serve(&self, access: AccessPolicy) -> Router { - let meta = MetaProtocol::new( + let mut meta = MetaProtocol::new( &self.blobs, None, Arc::clone(&self.tags), @@ -220,6 +229,9 @@ impl LocalNode { self.node_id, None, ); + if let Some(inner) = Arc::get_mut(&mut meta) { + inner.endpoint = Some(self.endpoint.clone()); + } // With a gate, blob fetches and observes are membership-checked (#173) and // pushes keep this policy; without one, pushes alone are gated, as before. let blobs = match &self.blob_gate { diff --git a/pkgs/id/crates/id-cli/src/repl/runner.rs b/pkgs/id/crates/id-cli/src/repl/runner.rs index 26ebefbbae..f4ced70b90 100644 --- a/pkgs/id/crates/id-cli/src/repl/runner.rs +++ b/pkgs/id/crates/id-cli/src/repl/runner.rs @@ -222,6 +222,7 @@ pub enum ReplAction { /// - `delete`, `rm `: Delete a file /// - `rename `: Rename a file /// - `copy`, `cp `: Copy a file +/// - `send [--replace] [DEST_NAME]`: Copy a file to another server /// /// ## Discovery Commands /// - `peers`: List discovered peers @@ -335,6 +336,22 @@ async fn execute_repl_command( ctx.rename(from, to).await?; Ok(ReplAction::Continue) } + (None, ["send", name, dest]) => { + ctx.send(name, dest, None, false).await?; + Ok(ReplAction::Continue) + } + (None, ["send", name, dest, dest_name]) => { + ctx.send(name, dest, Some(dest_name), false).await?; + Ok(ReplAction::Continue) + } + (None, ["send", "--replace", name, dest]) => { + ctx.send(name, dest, None, true).await?; + Ok(ReplAction::Continue) + } + (None, ["send", "--replace", name, dest, dest_name]) => { + ctx.send(name, dest, Some(dest_name), true).await?; + Ok(ReplAction::Continue) + } (None, ["copy" | "cp", from, to]) => { ctx.copy(from, to).await?; Ok(ReplAction::Continue) @@ -519,6 +536,7 @@ fn print_help() { println!(" gethash - Retrieve by hash (- for stdout)"); println!(" delete - Delete a file (alias: rm)"); println!(" rename - Rename a file"); + println!(" send [--replace] [DEST_NAME] - Copy a file to another server"); println!(" copy - Copy a file (alias: cp)"); println!(" peers - List discovered peers"); println!(" find ... - Find & output matches"); diff --git a/pkgs/id/crates/id-sync/src/lib.rs b/pkgs/id/crates/id-sync/src/lib.rs index 3ffb84334c..1979a03161 100644 --- a/pkgs/id/crates/id-sync/src/lib.rs +++ b/pkgs/id/crates/id-sync/src/lib.rs @@ -33,3 +33,4 @@ pub mod host; pub mod log_sync; pub mod meta_client; pub mod protocol; +pub mod transfer; diff --git a/pkgs/id/crates/id-sync/src/meta_client.rs b/pkgs/id/crates/id-sync/src/meta_client.rs index b22c3a059f..cc83ffdbb5 100644 --- a/pkgs/id/crates/id-sync/src/meta_client.rs +++ b/pkgs/id/crates/id-sync/src/meta_client.rs @@ -21,7 +21,13 @@ use iroh::{ }; use iroh_base::EndpointId; -use crate::protocol::{MetaRequest, MetaResponse}; +use iroh_blobs::{ + ALPN as BLOBS_ALPN, Hash, + api::Store, + protocol::{ChunkRanges, ChunkRangesSeq, PushRequest}, +}; + +use crate::protocol::{META_ALPN, MetaRequest, MetaResponse}; /// Maximum accepted size of a single response (64 MiB). pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; @@ -319,3 +325,70 @@ mod tests { ); } } + +const PUT_FINALIZATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2 * 60); + +/// Upload `hash` to `target`, **then** register `name` for it. +/// +/// Two ordering rules make this safe: +/// +/// 1. **Bytes before name.** The server verifies the blob is present before it +/// creates a name, so a failed upload can never leave a dangling name. +/// 2. **Keep the blobs connection open until the server confirms.** A push is +/// one-way — the server sends no acknowledgement — and closing the QUIC +/// connection right after the last write can abort the server's import of +/// data it has buffered but not yet processed. The `Put` request is the +/// acknowledgement: the server answers it once the blob is complete, so we +/// close the blobs connection only after that. +/// +/// A `Put` for a blob that is still being finalized is retried for up to two +/// minutes (large blobs take a moment to finish on the server). +pub async fn push_and_name( + store: &Store, + endpoint: &Endpoint, + target: EndpointAddr, + name: &str, + hash: Hash, +) -> Result<()> { + let blobs_conn = id_core::connectivity::connect(endpoint, target.clone(), BLOBS_ALPN).await?; + let push_request = PushRequest::new(hash, ChunkRangesSeq::from_ranges([ChunkRanges::all()])); + store + .remote() + .execute_push(blobs_conn.clone(), push_request) + .await + .context( + "blob push rejected: the server only accepts writes from allowed nodes \ + (run `id id --client` on this machine and add the printed ID to the \ + server's `--allow-node` or `.iroh-allowed`)", + )?; + + let meta_conn = id_core::connectivity::connect(endpoint, target, META_ALPN).await?; + let req = MetaRequest::Put { + filename: name.to_owned(), + hash, + }; + let outcome = id_core::connectivity::within( + PUT_FINALIZATION_TIMEOUT, + "registering the blob name", + async { + loop { + match request_over(&meta_conn, &req).await? { + MetaResponse::Error { message } + if crate::fileops::is_blob_missing_message(&message) => + { + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + response => return Ok(response), + } + } + }, + ) + .await; + meta_conn.close(0u32.into(), b"done"); + blobs_conn.close(0u32.into(), b"done"); + match expect_ok(outcome?)? { + MetaResponse::Put { success: true } => Ok(()), + MetaResponse::Put { success: false } => bail!("server rejected"), + _ => bail!("unexpected response"), + } +} diff --git a/pkgs/id/crates/id-sync/src/protocol.rs b/pkgs/id/crates/id-sync/src/protocol.rs index df57c5e3d1..1871ddbae2 100644 --- a/pkgs/id/crates/id-sync/src/protocol.rs +++ b/pkgs/id/crates/id-sync/src/protocol.rs @@ -61,7 +61,8 @@ use std::{sync::Arc, time::Duration}; use futures_lite::StreamExt; -use iroh::endpoint::Connection; +use iroh::EndpointAddr; +use iroh::endpoint::{Connection, Endpoint}; use iroh::protocol::{AcceptError, ProtocolHandler}; use iroh_base::EndpointId; use iroh_blobs::{Hash, api::Store}; @@ -628,6 +629,31 @@ pub enum MetaRequest { /// (a plain serve without a world, or a build without the world /// feature) records none and answers with an empty report. AbuseCounters, + /// Ask this node (the source) to copy one of its files to another node + /// (server-to-server transfer, #5345). + /// + /// The source performs the transfer with its own server identity: it + /// pushes the blob to `dest` over the blobs protocol and registers + /// `dest_name` (default: `name`) there over this protocol. The + /// destination's write policy therefore authorizes the *source server*, + /// and the copy's recorded origin is the source server. The initiating + /// caller is authorized at the source by the usual write gate + /// ([`MetaRequest::is_write`] includes this variant): world membership + /// or discovery alone never grants the right to send a file. + /// + /// A conflicting destination name refuses unless `replace` is set; a + /// replacement archives the existing destination file first. + Send { + /// The file name on the source node. + name: String, + /// The destination node. + dest: EndpointId, + /// Name to register on the destination. `None` = same as `name`. + dest_name: Option, + /// Whether an existing, different destination file may be archived + /// and replaced. + replace: bool, + }, } impl MetaRequest { @@ -642,6 +668,7 @@ impl MetaRequest { | Self::SetTag { .. } | Self::DelTag { .. } | Self::MigrateTags + | Self::Send { .. } ) } } @@ -764,6 +791,22 @@ pub enum MetaResponse { /// when the node exposes counters without a policy view. policy: Option, }, + /// Response to [`MetaRequest::Send`]: the transfer completed (or was + /// already complete) and the destination registered the name. + Send { + /// The transferred content hash. + hash: Hash, + /// The name registered on the destination. + name: String, + /// The destination node. + dest: EndpointId, + /// The destination already had the name pointing at `hash`; + /// nothing was pushed. + already_present: bool, + /// An existing, different destination file was archived and + /// replaced. + replaced: bool, + }, } /// One row of [`MetaResponse::AbuseCounters`]: the frame and byte counters @@ -850,6 +893,11 @@ pub struct MetaProtocol { /// The node's abuse evaluator, when this surface exposes it. `None` /// answers [`MetaRequest::AbuseCounters`] with an empty report. pub abuse: Option>>, + /// This node's own endpoint, when the handler may initiate outbound + /// transfers ([`MetaRequest::Send`]). `None` for purely in-process + /// handlers: a `Send` request then fails with an explanatory error + /// instead of silently doing nothing. + pub endpoint: Option, } impl MetaProtocol { @@ -872,6 +920,7 @@ impl MetaProtocol { node_id, blob_wait: DEFAULT_BLOB_WAIT, abuse, + endpoint: None, }) } @@ -1055,6 +1104,59 @@ impl MetaProtocol { .unwrap_or_default(); MetaResponse::ListPeers { peers } } + MetaRequest::Send { + name, + dest, + dest_name, + replace, + } => { + // The write gate above has already authorized the initiator + // at this (source) node. The transfer itself is performed + // with this node's server identity by the transfer module. + let hash = self + .store + .tags() + .get(&name) + .await + .ok() + .flatten() + .map(|t| t.hash); + match (hash, &self.endpoint) { + (None, _) => MetaResponse::Error { + message: format!("not found: {name}"), + }, + (Some(_), None) => MetaResponse::Error { + message: "this node cannot initiate server-to-server \ + transfers (no endpoint configured)" + .to_owned(), + }, + (Some(hash), Some(endpoint)) => { + let dest_name = dest_name.unwrap_or_else(|| name.clone()); + match crate::transfer::send_file( + &self.store, + endpoint, + EndpointAddr::from(dest), + &name, + hash, + &dest_name, + replace, + ) + .await + { + Ok(receipt) => MetaResponse::Send { + hash: receipt.hash, + name: receipt.dest_name, + dest: receipt.dest, + already_present: receipt.already_present, + replaced: receipt.replaced, + }, + Err(e) => MetaResponse::Error { + message: format!("{e:#}"), + }, + } + } + } + } MetaRequest::Whoami => MetaResponse::Whoami { node_id: self.node_id, version: env!("CARGO_PKG_VERSION").to_owned(), @@ -1777,6 +1879,15 @@ mod tests { (MetaRequest::ListPeers, 12), (MetaRequest::Whoami, 13), (MetaRequest::AbuseCounters, 14), + ( + MetaRequest::Send { + name: s.clone(), + dest: eid(2), + dest_name: None, + replace: false, + }, + 15, + ), ]; for (req, idx) in &requests { let bytes = postcard::to_allocvec(req).unwrap(); @@ -1811,7 +1922,7 @@ mod tests { }, 13, ), - (MetaResponse::Error { message: s }, 14), + (MetaResponse::Error { message: s.clone() }, 14), ( MetaResponse::AbuseCounters { rows: vec![], @@ -1819,6 +1930,16 @@ mod tests { }, 15, ), + ( + MetaResponse::Send { + hash: h, + name: s.clone(), + dest: eid(2), + already_present: false, + replaced: false, + }, + 16, + ), ]; for (resp, idx) in &responses { let bytes = postcard::to_allocvec(resp).unwrap(); @@ -1857,6 +1978,12 @@ mod tests { value: None, }, MetaRequest::MigrateTags, + MetaRequest::Send { + name: s.clone(), + dest: eid(2), + dest_name: None, + replace: false, + }, ] { assert!(req.is_write(), "{req:?} must require write access"); } diff --git a/pkgs/id/crates/id-sync/src/transfer.rs b/pkgs/id/crates/id-sync/src/transfer.rs new file mode 100644 index 0000000000..66198b81e0 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/transfer.rs @@ -0,0 +1,217 @@ +//! Server-to-server file transfer (#5345; design #4975). +//! +//! A user-initiated, single-file *copy* from one running `id` server to +//! another. The source server performs the transfer with its own identity: +//! it looks the name up in its store, pushes the blob to the destination +//! over the existing blobs protocol (`BLOBS_ALPN`), and only then registers +//! the destination name over the meta protocol (`/iroh-meta/3`). The +//! destination's existing write policy therefore sees the authenticated +//! *source-server* node ID — never the initiating CLI's client key — and +//! the destination records that node as the copy's `origin` with its own +//! first-write time as `created` (#4973/#5191 listing contract). +//! +//! Contract (from #5345 and the #4975 decision): +//! +//! - Bytes before name: the complete blob is pushed and confirmed before +//! the destination name is registered, so an interrupted send never +//! leaves a visible dangling name. +//! - The source is never modified or deleted; a send is a copy. +//! - Repeating the same transfer is idempotent: if the destination name +//! already points at the same hash, the send reports +//! [`TransferReceipt::already_present`] without pushing anything. +//! - Name conflicts refuse by default. Replacement must be explicit +//! (`replace`); the new file is staged and then copied onto the +//! destination name, and the copy preserves the replaced file under +//! the file store's canonical `.archive.` archive name. +//! - No new transport channel: bytes ride `BLOBS_ALPN`, control and +//! registration ride `/iroh-meta/3`, exactly like `id put` to a remote +//! node ([`crate::meta_client::push_and_name`] does the push+register +//! ordering); this module adds the conflict policy and the receipt. +//! +//! The one known race is the same one the rest of the meta protocol +//! accepts: the conflict pre-check and the final registration are separate +//! requests, so a third party writing the same destination name in +//! between can still be overwritten by the registration. The pre-check +//! exists so the *ordinary* conflict — the name was taken long before the +//! send started — is refused before any bytes move. + +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, bail}; +use iroh::{EndpointAddr, endpoint::Endpoint}; +use iroh_base::EndpointId; +use iroh_blobs::{Hash, api::Store}; + +use crate::protocol::META_ALPN; +use crate::meta_client::push_and_name; +use crate::meta_client::{expect_ok, request_over}; +use crate::protocol::{MetaRequest, MetaResponse}; + +/// What a completed (or already-completed) transfer did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TransferReceipt { + /// Content hash that was transferred. + pub hash: Hash, + /// Name of the file on the source server. + pub source_name: String, + /// Name registered on the destination. + pub dest_name: String, + /// Destination node ID. + pub dest: EndpointId, + /// The destination already had `dest_name` pointing at `hash`; nothing + /// was pushed. This is what makes a retry of the same send safe. + pub already_present: bool, + /// An existing, different file at `dest_name` was archived and replaced + /// (only possible when the send opted into replacement). + pub replaced: bool, +} + +/// The staging name a replacement transfer registers on the destination +/// before copying onto the real destination name. Copying onto an +/// existing name is the file store's archive behaviour: the old file is +/// preserved under `.archive.` and the copy lands +/// atomically after it, so staging through a copy is what makes a +/// replacement preserve the old file instead of overwriting it. +pub fn staging_name_for(name: &str, unix_ts: u64) -> String { + format!("{name}.incoming.{unix_ts}") +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Copy `hash` from this node's `store` to the destination node at `dest`, +/// registering it there as `dest_name`. +/// +/// `endpoint` must carry the *source server's* identity: the destination +/// authorizes the push and the registration against that node ID, and +/// records it as the copy's origin. +/// +/// Refuses (before pushing any bytes) when `dest_name` already names +/// different content on the destination and `replace` is false. +pub async fn send_file( + store: &Store, + endpoint: &Endpoint, + dest: EndpointAddr, + source_name: &str, + hash: Hash, + dest_name: &str, + replace: bool, +) -> Result { + let dest_id = dest.id; + + // Conflict pre-check on a short-lived meta connection, before any + // bytes move: an ordinary conflict must not cost a full blob push, + // and a refused send must leave the destination untouched. + let meta_conn = id_core::connectivity::connect(endpoint, dest.clone(), META_ALPN) + .await + .context("connecting to the destination for the conflict pre-check")?; + let existing = match expect_ok( + request_over( + &meta_conn, + &MetaRequest::Get { + filename: dest_name.to_owned(), + }, + ) + .await?, + )? { + MetaResponse::Get { hash } => hash, + _ => bail!("unexpected response to destination name lookup"), + }; + meta_conn.close(0u32.into(), b"done"); + + let replaced = match existing { + Some(existing_hash) if existing_hash == hash => { + return Ok(TransferReceipt { + hash, + source_name: source_name.to_owned(), + dest_name: dest_name.to_owned(), + dest: dest_id, + already_present: true, + replaced: false, + }); + } + Some(_) if !replace => { + bail!( + "destination already has a different file named {dest_name:?}; \ + refusing to replace it (retry with replacement enabled to \ + archive the existing file and replace it)" + ); + } + Some(_) => true, + None => false, + }; + + if !replaced { + // Bytes before name, confirmed before success: push_and_name + // pushes the complete blob and returns only after the + // destination's Put response confirms registration, so a failure + // here leaves no visible name behind. + push_and_name(store, endpoint, dest, dest_name, hash) + .await + .context("pushing the blob to the destination and registering its name")?; + } else { + // Replacement: register the new file under a staging name first + // (same bytes-before-name ordering), then copy it onto the + // destination name. The copy archives the existing destination + // file under `.archive.` before landing, so the + // old content is preserved by the store's own archive behaviour; + // the staging name is deleted once the copy has landed. + let staging_name = staging_name_for(dest_name, now_unix()); + push_and_name(store, endpoint, dest.clone(), &staging_name, hash) + .await + .context("pushing the blob to the destination and staging its name")?; + + let meta_conn = id_core::connectivity::connect(endpoint, dest, META_ALPN) + .await + .context("connecting to the destination to land the replacement")?; + let copied = expect_ok( + request_over( + &meta_conn, + &MetaRequest::Copy { + from: staging_name.clone(), + to: dest_name.to_owned(), + }, + ) + .await?, + )?; + match copied { + MetaResponse::Copy { success: true } => {} + MetaResponse::Copy { success: false } => { + meta_conn.close(0u32.into(), b"done"); + bail!("destination refused the replacement copy onto {dest_name:?}"); + } + _ => bail!("unexpected response to the replacement copy"), + } + // The copy landed and the old file is archived; remove the + // staging name. A cleanup failure does not un-send the file, but + // it leaves a duplicate name behind, so it is reported as an + // error rather than hidden. + let cleaned = expect_ok( + request_over( + &meta_conn, + &MetaRequest::Delete { + filename: staging_name.clone(), + }, + ) + .await?, + )?; + meta_conn.close(0u32.into(), b"done"); + match cleaned { + MetaResponse::Delete { .. } => {} + _ => bail!("unexpected response removing the staging name"), + } + } + + Ok(TransferReceipt { + hash, + source_name: source_name.to_owned(), + dest_name: dest_name.to_owned(), + dest: dest_id, + already_present: false, + replaced, + }) +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 11570e8bff..df446d425d 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -355,7 +355,8 @@ pub use id_cli::commands::{ ServeOptions, cmd_find, cmd_find_matches, cmd_get_local, cmd_get_multi, cmd_get_one, cmd_get_one_remote, cmd_gethash, cmd_id, cmd_list, cmd_list_remote, cmd_migrate_tags, cmd_peek, cmd_peers, cmd_put_hash, cmd_put_local_file, cmd_put_local_stdin, cmd_put_multi, cmd_put_one, - cmd_put_one_remote, cmd_search, cmd_serve, cmd_show, cmd_tag, create_local_client_endpoint, + cmd_put_one_remote, cmd_search, cmd_send, cmd_serve, cmd_show, cmd_tag, + create_local_client_endpoint, create_serve_lock, get_serve_info, is_process_alive, remove_serve_lock, }; pub use id_cli::helpers::{ @@ -382,6 +383,11 @@ pub use id_store::STORE_PATH; pub use id_sync::protocol::META_ALPN; +/// Server-to-server file transfer (#5345), implemented in `id-sync` +/// since the crate split (the meta handler and the transfer engine must +/// live in the same crate); re-exported at its historical `id::` path. +pub use id_sync::transfer; + // ============================================================================ // Utility Functions // ============================================================================ diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index dd15416dc6..6bdb707a39 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -453,6 +453,14 @@ async fn main() -> Result<()> { no_relay, }) => cmd_put_multi(files, content, stdin, hash_only, no_relay).await, Some(Command::PutHash { source }) => cmd_put_hash(&source).await, + Some(Command::Send { + source, + name, + to, + dest_name, + replace, + no_relay, + }) => id::commands::cmd_send(&source, &name, &to, dest_name, replace, no_relay).await, Some(Command::Get { sources, stdin, diff --git a/pkgs/id/tests/transfer.rs b/pkgs/id/tests/transfer.rs new file mode 100644 index 0000000000..960bc87a29 --- /dev/null +++ b/pkgs/id/tests/transfer.rs @@ -0,0 +1,202 @@ +//! End-to-end tests of server-to-server file transfer (#5345), ported +//! from the transfer module's unit tests: two in-process `LocalNode`s, +//! the source sends with its own server identity, and the destination's +//! write policy decides. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use id::access::AccessPolicy; +use id::commands::put::add_raw; +use id::local::LocalNode; +use id::transfer::send_file; +use id::{MetaRequest, MetaResponse}; +use iroh_blobs::Hash; + + +/// Put `data` on `node` under `name`; returns the content hash. +async fn put_named(node: &LocalNode, name: &str, data: &[u8]) -> Hash { + let (hash, _guard) = add_raw(&node.blobs(), data.to_vec()).await.unwrap(); + node.ops().put(name, hash).await.unwrap(); + hash +} + +async fn dest_hash(node: &LocalNode, name: &str) -> Option { + node.blobs().tags().get(name).await.unwrap().map(|t| t.hash) +} + +#[tokio::test] +async fn send_copies_blob_registers_name_and_stamps_source_as_origin() { + let source = LocalNode::open(true).await.unwrap(); + let dest = LocalNode::open(true).await.unwrap(); + // The destination admits the source server (and only it) as writer. + let dest_router = dest.serve(AccessPolicy::restricted([source.node_id()])); + let hash = put_named(&source, "report.txt", b"hello transfer").await; + + let receipt = send_file( + &source.blobs(), + source.endpoint(), + dest.addr(), + "report.txt", + hash, + "report.txt", + false, + ) + .await + .unwrap(); + + assert_eq!(receipt.hash, hash); + assert!(!receipt.already_present); + assert!(!receipt.replaced); + assert_eq!(dest_hash(&dest, "report.txt").await, Some(hash)); + + // Listing contract (#4973): the copy's origin is the authenticated + // sending server, not the initiating user. + let resp = dest.request(MetaRequest::List).await; + match resp { + MetaResponse::List { items } => { + let entry = items.iter().find(|i| i.name == "report.txt").unwrap(); + assert_eq!( + entry.origin.as_deref(), + Some(source.node_id().to_string().as_str()) + ); + assert!(entry.uploaded_at.is_some()); + } + _ => panic!("unexpected list response"), + } + + // The source is untouched: a send is a copy, never a move. + assert_eq!(dest_hash(&source, "report.txt").await, Some(hash)); + + dest_router.shutdown().await.unwrap(); + source.shutdown().await.unwrap(); + dest.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn resend_is_idempotent() { + let source = LocalNode::open(true).await.unwrap(); + let dest = LocalNode::open(true).await.unwrap(); + let router = dest.serve(AccessPolicy::restricted([source.node_id()])); + let hash = put_named(&source, "a.txt", b"same bytes").await; + + let first = send_file( + &source.blobs(), + source.endpoint(), + dest.addr(), + "a.txt", + hash, + "a.txt", + false, + ) + .await + .unwrap(); + assert!(!first.already_present); + + let second = send_file( + &source.blobs(), + source.endpoint(), + dest.addr(), + "a.txt", + hash, + "a.txt", + false, + ) + .await + .unwrap(); + assert!(second.already_present); + assert_eq!(dest_hash(&dest, "a.txt").await, Some(hash)); + + router.shutdown().await.unwrap(); + source.shutdown().await.unwrap(); + dest.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn conflict_refuses_by_default_and_replace_archives_the_old_file() { + let source = LocalNode::open(true).await.unwrap(); + let dest = LocalNode::open(true).await.unwrap(); + let router = dest.serve(AccessPolicy::restricted([source.node_id()])); + let new_hash = put_named(&source, "data.bin", b"new content").await; + let old_hash = put_named(&dest, "data.bin", b"old content").await; + + let refused = send_file( + &source.blobs(), + source.endpoint(), + dest.addr(), + "data.bin", + new_hash, + "data.bin", + false, + ) + .await; + assert!(refused.is_err(), "conflict without replace must refuse"); + // The refused send changed nothing on the destination. + assert_eq!(dest_hash(&dest, "data.bin").await, Some(old_hash)); + + let receipt = send_file( + &source.blobs(), + source.endpoint(), + dest.addr(), + "data.bin", + new_hash, + "data.bin", + true, + ) + .await + .unwrap(); + assert!(receipt.replaced); + assert_eq!(dest_hash(&dest, "data.bin").await, Some(new_hash)); + // The replaced file survives under an archive name, and the + // staging duplicate used during the replacement is gone. + let resp = dest.request(MetaRequest::List).await; + match resp { + MetaResponse::List { items } => { + assert!( + items + .iter() + .any(|i| i.name.starts_with("data.bin.archive.") && i.hash == old_hash), + "old file must be preserved under an archive name: {items:?}" + ); + assert!( + !items + .iter() + .any(|i| i.name.starts_with("data.bin.incoming.")), + "staging duplicate must be cleaned up: {items:?}" + ); + } + _ => panic!("unexpected list response"), + } + + router.shutdown().await.unwrap(); + source.shutdown().await.unwrap(); + dest.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn destination_that_does_not_allow_the_source_denies_the_send() { + let source = LocalNode::open(true).await.unwrap(); + let dest = LocalNode::open(true).await.unwrap(); + // Nobody may write to this destination. + let router = dest.serve(AccessPolicy::restricted([])); + let hash = put_named(&source, "secret.txt", b"classified").await; + + let denied = send_file( + &source.blobs(), + source.endpoint(), + dest.addr(), + "secret.txt", + hash, + "secret.txt", + false, + ) + .await; + assert!( + denied.is_err(), + "a destination that does not allowlist the source must deny the send" + ); + assert_eq!(dest_hash(&dest, "secret.txt").await, None); + + router.shutdown().await.unwrap(); + source.shutdown().await.unwrap(); + dest.shutdown().await.unwrap(); +} \ No newline at end of file