diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index e9fd67f4a6..2e4171435d 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -4172,6 +4172,8 @@ dependencies = [ "iroh", "iroh-base", "iroh-blobs", + "iroh-docs", + "iroh-gossip", "iroh-mainline-address-lookup", "iroh-tickets", "p2panda-auth", diff --git a/pkgs/id/crates/id-sync/Cargo.toml b/pkgs/id/crates/id-sync/Cargo.toml index 219bb0a86d..0d2af204a9 100644 --- a/pkgs/id/crates/id-sync/Cargo.toml +++ b/pkgs/id/crates/id-sync/Cargo.toml @@ -51,6 +51,8 @@ tokio = { version = "1", features = ["full"] } tracing = "0.1" [dev-dependencies] +iroh-docs = "0.101" +iroh-gossip = { version = "0.101", features = ["net"] } p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", features = [ "serde", ] } diff --git a/pkgs/id/crates/id-sync/src/fileops.rs b/pkgs/id/crates/id-sync/src/fileops.rs index 5dd3aa2f9f..9be9e89e8f 100644 --- a/pkgs/id/crates/id-sync/src/fileops.rs +++ b/pkgs/id/crates/id-sync/src/fileops.rs @@ -29,7 +29,7 @@ use thiserror::Error; use id_store::tags::{TagStore, TagValue, now_unix}; -const ARCHIVE_IDENTITY_TAG_KEYS: [&[u8]; 5] = [ +const ARCHIVE_IDENTITY_TAG_KEYS: [&[u8]; 6] = [ b"name", b"file", b"path", @@ -39,6 +39,9 @@ const ARCHIVE_IDENTITY_TAG_KEYS: [&[u8]; 5] = [ // every earlier archive from the live file's delete (#4574). b"archive.rename", b"archive.replace", + // The owner back-reference belongs to the archive it names; it + // must never travel onto another subject either. + b"archive.owner", ]; /// Errors from file operations, distinguishable so callers can map them to @@ -342,6 +345,22 @@ impl<'a> FileOps<'a> { .refresh_identity_tags(&self.tags.global, archive.as_bytes()) .await .with_context(|| format!("refreshing identity for archive {archive}"))?; + // Record the live file this archive belongs to (#8815 review): + // delete() trusts this back-reference, maintained across renames, + // not the archive's name alone. + if let Err(e) = self + .tags + .set_tag( + &self.tags.global, + archive.as_bytes(), + b"archive.owner", + Some(name.as_bytes()), + b"", + ) + .await + { + tracing::warn!("failed to set archive.owner tag on {archive}: {e:#}"); + } for (key, value) in &archive_refs { self.tags .set_tag( @@ -516,6 +535,36 @@ impl<'a> FileOps<'a> { } } + // Maintain the `archive.owner` back-references delete() trusts + // (#8815 review): archives created here belong to `to`, and + // archives already attributed to `from` follow the file to its + // new name. A reference that fails attribution is left + // untouched, so a forged reference can never adopt another + // file's archive by being carried through a rename. + for key in [&b"archive.rename"[..], &b"archive.replace"[..]] { + let refs = match self.tags.get_by_key(ns, to.as_bytes(), key).await { + Ok(tags) => tags, + Err(e) => { + tracing::warn!("failed to read archive references on {to}: {e:#}"); + continue; + } + }; + for tag in refs { + let Some(archive_name) = tag.value.as_ref().and_then(|value| value.as_str()) else { + continue; + }; + let current_owner = archive_owner(self.tags, archive_name).await.ok().flatten(); + let created_here = archived_original.as_deref() == Some(archive_name) + || archived_replaced.as_deref() == Some(archive_name); + let follows_from = current_owner.as_deref() == Some(from); + let legacy_owned = + current_owner.is_none() && is_owned_archive_tag_name(from, archive_name); + if created_here || follows_from || legacy_owned { + set_archive_owner(self.tags, archive_name, &to).await; + } + } + } + Ok(RenameOutcome { hash, archived_original, @@ -601,10 +650,20 @@ impl<'a> FileOps<'a> { .await? { if let Some(archive_name) = tag.value.as_ref().and_then(|value| value.as_str()) { - if is_archive_tag_name(archive_name) { + // Stored references are only actionable when FileOps + // attribution ties them to this file: either they point + // into this file's own archive namespace, or the + // archive carries an `archive.owner` back-reference + // naming this file (the provenance FileOps maintains + // across renames, #8815 review). Metadata may predate + // protocol-level reservation of these keys, so an + // unattributed foreign reference is never honored. + let owner_attributed = is_archive_tag_name(archive_name) + && archive_owner(self.tags, archive_name).await?.as_deref() == Some(name); + if is_owned_archive_tag_name(name, archive_name) || owner_attributed { archives.insert(archive_name.to_owned()); } else { - tracing::warn!("ignoring malformed archive reference on {name}"); + tracing::warn!("ignoring invalid or foreign archive reference on {name}"); } } } @@ -680,6 +739,65 @@ impl<'a> FileOps<'a> { } } +/// The live file an archive is attributed to, read from the +/// `archive.owner` back-reference FileOps stamps when it creates the +/// archive and maintains across renames (#8815). Peers cannot forge the +/// back-reference: the key is reserved at the protocol layer. +async fn archive_owner(tags: &TagStore, archive_name: &str) -> Result> { + let mut owner = None; + for tag in tags + .get_by_key(&tags.global, archive_name.as_bytes(), b"archive.owner") + .await? + { + if let Some(value) = tag.value.as_ref().and_then(|value| value.as_str()) { + owner = Some(value.to_owned()); + } + } + Ok(owner) +} + +/// Stamp the `archive.owner` back-reference on an archive (best-effort +/// metadata bookkeeping, like the other archive tags). +async fn set_archive_owner(tags: &TagStore, archive_name: &str, owner: &str) { + if let Err(e) = tags + .set_tag( + &tags.global, + archive_name.as_bytes(), + b"archive.owner", + Some(owner.as_bytes()), + b"", + ) + .await + { + tracing::warn!("failed to set archive.owner tag on {archive_name}: {e:#}"); + } +} + +/// Whether `archive_name` is a FileOps archive owned by `name`. +fn is_owned_archive_tag_name(name: &str, archive_name: &str) -> bool { + archive_name + .strip_prefix(&format!("{name}.archive.")) + .is_some_and(|suffix| !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit())) +} + +#[cfg(test)] +mod archive_reference_tests { + use super::is_owned_archive_tag_name; + + #[test] + fn deletion_ignores_foreign_archive_reference_but_accepts_owned_reference() { + assert!(!is_owned_archive_tag_name( + "my-file", + "other-file.archive.123" + )); + assert!(is_owned_archive_tag_name("my-file", "my-file.archive.123")); + assert!(!is_owned_archive_tag_name( + "my-file", + "my-file.archive.nope" + )); + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod archive_name_tests { diff --git a/pkgs/id/crates/id-sync/src/protocol.rs b/pkgs/id/crates/id-sync/src/protocol.rs index 0881a7bf9f..df57c5e3d1 100644 --- a/pkgs/id/crates/id-sync/src/protocol.rs +++ b/pkgs/id/crates/id-sync/src/protocol.rs @@ -71,6 +71,197 @@ use tokio::{sync::Semaphore, task::JoinSet}; use crate::fileops::{FileOpError, FileOps}; use id_core::access::AccessPolicy; use id_core::discovery::{PeerAnnouncement, PeerDiscovery}; + +/// Archive references are reserved for FileOps-generated metadata. Protocol +/// peers may neither create nor change them through the general tag API. +fn is_reserved_archive_reference_key(key: &[u8]) -> bool { + matches!( + key, + b"archive.rename" | b"archive.replace" | b"archive.owner" + ) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod archive_reference_behavior_tests { + use std::sync::Arc; + + use id_core::access::AccessPolicy; + use id_store::tags::TagStore; + use iroh::endpoint::{Endpoint, RelayMode, presets}; + use iroh_base::SecretKey; + use iroh_blobs::{Hash, api::Store, store::mem::MemStore}; + use iroh_docs::protocol::Docs; + use iroh_gossip::net::Gossip; + + use super::{MetaProtocol, MetaRequest, MetaResponse}; + + #[tokio::test] + async fn authorized_peer_cannot_forge_refs_and_delete_preserves_preexisting_foreign_archive() { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap(); + let store: Store = MemStore::new().into(); + let gossip = Gossip::builder().spawn(endpoint.clone()); + let docs = Docs::memory() + .spawn(endpoint.clone(), store.clone(), gossip) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tags = Arc::new( + TagStore::init_in(&docs, "archive-reference-test", dir.path().join("meta")) + .await + .unwrap(), + ); + let peer = SecretKey::from_bytes(&[42; 32]).public(); + let server = MetaProtocol::new( + &store, + None, + Arc::clone(&tags), + AccessPolicy::restricted([peer]), + endpoint.id(), + None, + ); + let foreign_hash = Hash::from([7; 32]); + let owned_hash = Hash::from([8; 32]); + store + .tags() + .set("my-file", Hash::from([1; 32])) + .await + .unwrap(); + store + .tags() + .set("other-file.archive.123", foreign_hash) + .await + .unwrap(); + store + .tags() + .set("my-file.archive.124", owned_hash) + .await + .unwrap(); + tags.set_tag( + &tags.global, + b"other-file.archive.123", + b"keep", + Some(b"foreign metadata"), + b"", + ) + .await + .unwrap(); + tags.set_tag( + &tags.global, + b"my-file.archive.124", + b"keep", + Some(b"owned metadata"), + b"", + ) + .await + .unwrap(); + tags.set_tag( + &tags.global, + b"my-file", + b"archive.replace", + Some(b"my-file.archive.124"), + b"", + ) + .await + .unwrap(); + + let rejected_set = server + .handle( + &peer, + MetaRequest::SetTag { + subject: b"my-file".to_vec(), + key: b"archive.replace".to_vec(), + value: Some(b"other-file.archive.123".to_vec()), + }, + ) + .await; + assert!(matches!(rejected_set, MetaResponse::Error { .. })); + let rejected_delete = server + .handle( + &peer, + MetaRequest::DelTag { + subject: b"my-file".to_vec(), + key: b"archive.replace".to_vec(), + value: None, + }, + ) + .await; + assert!(matches!(rejected_delete, MetaResponse::Error { .. })); + + // Model legacy/persisted forged metadata written before the protocol + // reserved these keys; deletion must still refuse to follow it. + tags.set_tag( + &tags.global, + b"my-file", + b"archive.replace", + Some(b"other-file.archive.123"), + b"", + ) + .await + .unwrap(); + let response = server + .handle( + &peer, + MetaRequest::Delete { + filename: "my-file".to_owned(), + }, + ) + .await; + assert!(matches!(response, MetaResponse::Delete { success: true })); + + assert_eq!( + store + .tags() + .get("other-file.archive.123") + .await + .unwrap() + .unwrap() + .hash, + foreign_hash + ); + let foreign_metadata = tags + .get_tags(&tags.global, b"other-file.archive.123") + .await + .unwrap(); + assert!( + foreign_metadata + .iter() + .any(|tag| tag.key.as_bytes() == b"keep") + ); + assert!( + store + .tags() + .get("my-file.archive.124") + .await + .unwrap() + .is_none() + ); + assert!( + tags.get_tags(&tags.global, b"my-file.archive.124") + .await + .unwrap() + .is_empty() + ); + endpoint.close().await; + } +} + +#[cfg(test)] +mod reserved_archive_reference_tests { + use super::is_reserved_archive_reference_key; + + #[test] + fn archive_reference_keys_are_reserved_for_fileops() { + assert!(is_reserved_archive_reference_key(b"archive.rename")); + assert!(is_reserved_archive_reference_key(b"archive.replace")); + assert!(is_reserved_archive_reference_key(b"archive.owner")); + assert!(!is_reserved_archive_reference_key(b"user.label")); + } +} use id_store::tags::TagStore; /// Decode exactly one meta-protocol value, rejecting any trailing bytes. @@ -789,6 +980,19 @@ impl MetaProtocol { MetaRequest::Find { query, prefer_name } => MetaResponse::Find { matches: self.find(&query, prefer_name).await, }, + MetaRequest::SetTag { key, .. } if is_reserved_archive_reference_key(&key) => { + // These keys are FileOps-owned references, not user metadata. + // Allowing protocol peers to write them lets a later delete + // remove an archive (and metadata) belonging to another file. + MetaResponse::Error { + message: "archive reference tags are reserved".to_owned(), + } + } + MetaRequest::DelTag { key, .. } if is_reserved_archive_reference_key(&key) => { + MetaResponse::Error { + message: "archive reference tags are reserved".to_owned(), + } + } MetaRequest::SetTag { subject, key,