diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 69a73e8078..9c6146670f 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -3904,6 +3904,7 @@ dependencies = [ "id-caps", "id-core", "id-events", + "id-groups", "id-store", "id-sync", "iroh", @@ -3918,7 +3919,6 @@ dependencies = [ "n0-mainline", "p2panda-auth", "p2panda-core", - "p2panda-encryption", "p2panda-store", "p2panda-sync", "postcard", @@ -4027,6 +4027,28 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "id-groups" +version = "0.1.0" +dependencies = [ + "anyhow", + "id-core", + "id-events", + "id-store", + "iroh-base", + "iroh-blobs", + "p2panda-core", + "p2panda-encryption", + "postcard", + "proptest", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tracing", +] + [[package]] name = "id-native-shell" version = "0.1.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 74f3530226..05a155e142 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-sync", "crates/id-native-shell"] +members = ["crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "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", "crates/id-sync"] +default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "crates/id-sync"] # ============================================================================= # Features @@ -80,6 +80,9 @@ 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 } +# Groups-family modules extracted in step 4 of the crate split (#4407). +# Re-exported at their historical crate:: paths in src/lib.rs. +id-groups = { path = "crates/id-groups", 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 @@ -111,11 +114,9 @@ p2panda-sync = { path = "vendor/p2panda-sync" } p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", features = [ "serde", ] } -# DataScheme group encryption (P4.1, src/encryption/). `data_scheme` is on because the adapter is the -# scheme. `test_utils` and `message_scheme` stay off: the adapter brings its own orderer and membership. -p2panda-encryption = { path = "vendor/p2panda-encryption", default-features = false, features = [ - "data_scheme", -] } +# DataScheme group encryption (P4.1) moved to id-groups in step 4 of the +# crate split (#4407): the vendored p2panda-encryption dependency is +# declared there now, with the same features. postcard = { version = "1", features = ["alloc"] } rand = "0.10" redb = "=4.3.0" diff --git a/pkgs/id/crates/id-groups/Cargo.toml b/pkgs/id/crates/id-groups/Cargo.toml new file mode 100644 index 0000000000..032224048a --- /dev/null +++ b/pkgs/id/crates/id-groups/Cargo.toml @@ -0,0 +1,134 @@ +[package] +name = "id-groups" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +description = "Groups layer of the id crate: group actions and log, local warnings, blob gate and group encryption (pkgs/id crate split step 4, #4407)" +license = "MIT OR Apache-2.0" + +# Step 4 of the pkgs/id crate split (#3447 umbrella, #4407): the +# policy/enforcement remainder of the group layer lives here, over the +# group model and fold in id-events (step 2b ruling on #4405: the model +# does not move again). Contents: the groups remainder (`groups`: +# actions, the group log, local warnings), the blob gate's enforcement +# logic (`blob_gate`; the `FoldedWorlds` adapter over `groups::worlds` +# stays in the facade with worlds.rs until step 5 extracts id-worlds), +# and the DataScheme group encryption (`encryption`). Dependencies per +# the design map: id-core, id-store, id-events. + +[features] +default = [] + +[dependencies] +anyhow = "1" +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-base = "1" +iroh-blobs = "0.103" +p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc" } +p2panda-encryption = { path = "../../vendor/p2panda-encryption", default-features = false, features = [ + "data_scheme", +] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +tokio = { version = "1", features = ["full"] } +tracing = "0.1" + +[dev-dependencies] +postcard = { version = "1", features = ["alloc"] } +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/crates/id-groups/src/blob_gate.rs b/pkgs/id/crates/id-groups/src/blob_gate.rs new file mode 100644 index 0000000000..51f0913820 --- /dev/null +++ b/pkgs/id/crates/id-groups/src/blob_gate.rs @@ -0,0 +1,488 @@ +//! Who may fetch or observe a blob (P3.4, decision 5). +//! +//! iroh-blobs serves a `get` for any hash to any peer that connects. Under its default +//! observe mode it also answers `observe` with the blob's size and held ranges, for anyone. +//! This module decides each of those requests from the requester's [`EndpointId`] and the hash: +//! +//! - **Fetch** (`get`, and every hash of a `get_many`) is allowed only to a current member of a +//! world that references the hash. A world references a blob when one of its artifacts or +//! documents names the hash. +//! - **Observe** needs the same membership, and the server policy must serve observe for that +//! world. Observe is off by default. A world can narrow it off for its own blobs, but cannot +//! switch it on. +//! - **Refusals look the same.** A hash that no world references and a hash the requester may +//! not reach get the same verdict. The decision reads only the reference index and the +//! membership table, never the blob store. +//! - **Fails closed.** A request from a connection with no known `EndpointId` is refused, and so +//! is one whose verdict cannot be delivered. +//! +//! The reference index and the membership query are behind [`WorldAccess`]. The facade's +//! `blob_gate::FoldedWorlds` answers membership from the folded worlds. Its reference index +//! has no producer yet, so +//! [`blob_events`] is not wired into `id serve`. + +use std::{ + collections::{BTreeSet, HashMap}, + sync::Arc, +}; + +use iroh_base::EndpointId; +use iroh_blobs::{ + Hash, + provider::events::{ + AbortReason, ConnectMode, EventMask, EventSender, ObserveMode, ProviderMessage, RequestMode, + }, +}; + +use id_core::access::AccessPolicy; +use id_events::event_store::BlockList; + +/// The two questions the gate asks of the world graph. The trait is +/// sync-gating vocabulary owned by the events layer since step 2b of +/// the crate split (#4405); it is re-exported here at its historical +/// path. The implementation over the folded worlds (`FoldedWorlds`) +/// stays in the facade with `groups::worlds` until step 5. +pub use id_events::world_access::WorldAccess; + +/// The server's blob policy. +/// +/// `observe` is the server default and is off unless enabled. A world in `narrowed` refuses +/// observe for its blobs even when the server allows it. Fetch has no switch: every fetch is +/// decided by membership. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BlobPolicy { + observe: bool, + narrowed: BTreeSet, +} + +impl BlobPolicy { + /// Serve observe for every world that does not narrow it. + #[must_use] + pub const fn with_observe(mut self) -> Self { + self.observe = true; + self + } + + /// Refuse observe for the blobs `world` references, whatever the server default. + #[must_use] + pub fn narrow_observe(mut self, world: impl Into) -> Self { + self.narrowed.insert(world.into()); + self + } + + /// Whether observe may be served for the blobs `world` references. + pub fn observe_allowed(&self, world: &str) -> bool { + self.observe && !self.narrowed.contains(world) + } +} + +/// The two request kinds the gate decides. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Request { + /// A `get` or one hash of a `get_many`. + Fetch, + /// An `observe`. + Observe, +} + +/// Whether `requester` may make `request` for `hash`. +/// +/// Allowed when some world that references `hash` has the requester as a current member and, +/// for an observe, the policy serves observe for that world. +pub fn decide( + access: &impl WorldAccess, + policy: &BlobPolicy, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + decide_with_blocks(access, policy, None, requester, hash, request) +} + +/// [`decide`], with the operator block list composed in (#2245): a +/// requester blocked by endpoint key is refused fetch and observe alike, +/// member or not. The seam's shape stays the crate's bool verdict (the +/// provider's `AbortReason::Permission` is what a refusal becomes in +/// [`blob_events_with_blocks`]). Pushes are not decided here: a block +/// changes serving only, never what the store ingests. +/// +/// `blocks` is `None` for a gate with no list attached — exactly +/// [`decide`]'s behaviour. +pub fn decide_with_blocks( + access: &impl WorldAccess, + policy: &BlobPolicy, + blocks: Option<&dyn BlockList>, + requester: &EndpointId, + hash: &Hash, + request: Request, +) -> bool { + if blocks.is_some_and(|blocks| blocks.peer_blocked(requester.as_bytes())) { + return false; + } + access.worlds_referencing(hash).iter().any(|world| { + access.is_current_member(world, requester) + && match request { + Request::Fetch => true, + Request::Observe => policy.observe_allowed(world), + } + }) +} + +/// The verdict for a request from `peer`: allowed only when the peer is known and `allow` +/// says so. An unknown peer is refused. +fn admit( + peer: Option<&EndpointId>, + allow: impl FnOnce(&EndpointId) -> bool, +) -> Result<(), AbortReason> { + match peer { + Some(id) if allow(id) => Ok(()), + _ => Err(AbortReason::Permission), + } +} + +/// Build the [`EventSender`] that a provider passes to `BlobsProtocol::new`. +/// +/// Fetch, `get_many` and observe are decided by [`decide`] over `access`. Pushes are decided by +/// `writes`, as in [`id_core::access::blobs_events`]. Every request is intercepted, so no store +/// read happens before the verdict. +/// +/// A background task is spawned on the current Tokio runtime and ends when the sender is +/// dropped. +pub fn blob_events( + access: Arc, + policy: BlobPolicy, + writes: AccessPolicy, +) -> EventSender { + blob_events_with_blocks(access, policy, writes, None) +} + +/// [`blob_events`], with the operator block list composed into every +/// serving verdict (#2245): a blocked endpoint is refused `get`, +/// `get_many`, and `observe` through the same `AbortReason::Permission` +/// as a non-member, so a refusal still does not reveal which rule made +/// it. Push verdicts are unchanged — writes are ingest, and a block +/// never rejects what a peer sends, only what it is served. +pub fn blob_events_with_blocks( + access: Arc, + policy: BlobPolicy, + writes: AccessPolicy, + blocks: Option>, +) -> EventSender { + let (tx, mut rx) = tokio::sync::mpsc::channel::(64); + let mask = EventMask { + connected: ConnectMode::Notify, + get: RequestMode::Intercept, + get_many: RequestMode::Intercept, + push: RequestMode::Intercept, + observe: ObserveMode::Intercept, + ..EventMask::DEFAULT + }; + tokio::spawn(async move { + let mut peers: HashMap = HashMap::new(); + while let Some(msg) = rx.recv().await { + match msg { + ProviderMessage::ClientConnectedNotify(m) => { + if let Some(id) = m.endpoint_id { + peers.insert(m.connection_id, id); + } + } + ProviderMessage::ConnectionClosed(m) => { + peers.remove(&m.connection_id); + } + ProviderMessage::GetRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| { + decide_with_blocks( + &*access, + &policy, + blocks.as_deref(), + id, + &m.request.hash, + Request::Fetch, + ) + }); + let _ = m.tx.send(verdict).await; + } + ProviderMessage::GetManyRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| { + m.request.hashes.iter().all(|hash| { + decide_with_blocks( + &*access, + &policy, + blocks.as_deref(), + id, + hash, + Request::Fetch, + ) + }) + }); + let _ = m.tx.send(verdict).await; + } + ProviderMessage::ObserveRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| { + decide_with_blocks( + &*access, + &policy, + blocks.as_deref(), + id, + &m.request.hash, + Request::Observe, + ) + }); + let _ = m.tx.send(verdict).await; + } + ProviderMessage::PushRequestReceived(m) => { + let verdict = admit(peers.get(&m.connection_id), |id| writes.can_write(id)); + let _ = m.tx.send(verdict).await; + } + _ => {} + } + } + }); + EventSender::new(tx, mask) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use iroh_base::SecretKey; + use proptest::prelude::*; + + use super::*; + + const WORLDS: [&str; 3] = ["alpha", "beta", "gamma"]; + + /// An operator block list naming fixed peers by key (the local + /// stand-in for the facade's `pull_policy::testing::stub_blocks`, + /// which folds through the facade's worlds and cannot live here). + #[derive(Debug, Default)] + struct StubBlocks { + peers: std::collections::HashSet<[u8; 32]>, + } + + impl BlockList for StubBlocks { + fn is_blocked(&self, kind: id_events::event_store::BlockKind, value: &[u8]) -> bool { + match kind { + id_events::event_store::BlockKind::PeerKey => { + <[u8; 32]>::try_from(value).is_ok_and(|key| self.peers.contains(&key)) + } + _ => false, + } + } + } + + fn stub_blocks(peers: &[[u8; 32]]) -> Arc { + Arc::new(StubBlocks { + peers: peers.iter().copied().collect(), + }) + } + + fn id(n: u8) -> EndpointId { + SecretKey::from_bytes(&[n; 32]).public() + } + + fn blob(n: u8) -> Hash { + Hash::from_bytes([n; 32]) + } + + /// Membership and references as plain lists, read by both `decide` and [`spec`]. + #[derive(Debug, Default)] + struct Table { + members: Vec<(String, EndpointId)>, + refs: Vec<(Hash, String)>, + } + + impl WorldAccess for Table { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.members + .iter() + .any(|(w, m)| w == world && m == requester) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.refs + .iter() + .filter(|(h, _)| h == hash) + .map(|(_, w)| w.clone()) + .collect() + } + } + + /// The rule as a scan of the lists: some world names the hash, the requester is a member + /// of it, and an observe is served only where the policy serves observe. + fn spec(t: &Table, p: &BlobPolicy, r: &EndpointId, h: &Hash, req: Request) -> bool { + t.refs.iter().any(|(rh, w)| { + rh == h + && t.members.iter().any(|(mw, m)| mw == w && m == r) + && (req == Request::Fetch || (p.observe && !p.narrowed.contains(w))) + }) + } + + fn one_world(member: EndpointId, hash: Hash) -> Table { + Table { + members: vec![("docs".to_owned(), member)], + refs: vec![(hash, "docs".to_owned())], + } + } + + #[test] + fn a_non_member_is_refused_fetch_and_observe() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + assert!(!decide(&t, &p, &id(2), &blob(9), Request::Fetch)); + assert!(!decide(&t, &p, &id(2), &blob(9), Request::Observe)); + } + + #[test] + fn a_member_of_the_referencing_world_fetches() { + let t = one_world(id(1), blob(9)); + assert!(decide( + &t, + &BlobPolicy::default(), + &id(1), + &blob(9), + Request::Fetch + )); + } + + #[test] + fn a_blocked_member_is_refused_fetch_and_observe() { + // #2245: the block composes over membership — a current member + // blocked by endpoint key is served nothing. + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + let blocks = stub_blocks(&[*id(1).as_bytes()]); + for request in [Request::Fetch, Request::Observe] { + assert!(!decide_with_blocks( + &t, + &p, + Some(&*blocks), + &id(1), + &blob(9), + request + )); + } + // A list that blocks someone else leaves the member's verdict + // exactly what membership decides. + let blocks = stub_blocks(&[*id(2).as_bytes()]); + assert!(decide_with_blocks( + &t, + &p, + Some(&*blocks), + &id(1), + &blob(9), + Request::Fetch + )); + } + + #[test] + fn a_member_of_an_unrelated_world_is_refused() { + let t = Table { + members: vec![("other".to_owned(), id(1))], + refs: vec![(blob(9), "docs".to_owned())], + }; + let p = BlobPolicy::default().with_observe(); + assert!(!decide(&t, &p, &id(1), &blob(9), Request::Fetch)); + assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); + } + + #[test] + fn observe_is_refused_by_default_even_for_a_member() { + let t = one_world(id(1), blob(9)); + assert!(!BlobPolicy::default().observe_allowed("docs")); + assert!(!decide( + &t, + &BlobPolicy::default(), + &id(1), + &blob(9), + Request::Observe + )); + assert!(decide( + &t, + &BlobPolicy::default(), + &id(1), + &blob(9), + Request::Fetch + )); + } + + #[test] + fn observe_is_allowed_for_a_member_when_the_server_enables_it() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); + } + + #[test] + fn a_world_can_narrow_observe_off_while_the_server_allows_it() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe().narrow_observe("docs"); + assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); + assert!(decide(&t, &p, &id(1), &blob(9), Request::Fetch)); + } + + #[test] + fn a_narrowed_world_does_not_hide_observe_from_another_referencing_world() { + let t = Table { + members: vec![("docs".to_owned(), id(1)), ("team".to_owned(), id(1))], + refs: vec![(blob(9), "docs".to_owned()), (blob(9), "team".to_owned())], + }; + let p = BlobPolicy::default().with_observe().narrow_observe("docs"); + assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); + } + + #[test] + fn an_unknown_hash_is_refused_like_a_denied_one() { + let t = one_world(id(1), blob(9)); + let p = BlobPolicy::default().with_observe(); + for request in [Request::Fetch, Request::Observe] { + // Unknown: no world names blob(5). Denied: a stranger asks for blob(9). + let unknown = decide(&t, &p, &id(1), &blob(5), request); + let denied = decide(&t, &p, &id(2), &blob(9), request); + assert!(!unknown && !denied, "{request:?}"); + } + } + + proptest! { + #[test] + fn decide_matches_the_spec_for_every_pair( + members in proptest::collection::vec((0usize..3, 1u8..6), 0..12), + refs in proptest::collection::vec((1u8..6, 0usize..3), 0..12), + observe in any::(), + narrowed in proptest::collection::vec(0usize..3, 0..3), + ) { + let t = Table { + members: members + .iter() + .map(|&(w, k)| (WORLDS[w].to_owned(), id(k))) + .collect(), + refs: refs + .iter() + .map(|&(h, w)| (blob(h), WORLDS[w].to_owned())) + .collect(), + }; + let mut p = BlobPolicy::default(); + if observe { + p = p.with_observe(); + } + for &w in &narrowed { + p = p.narrow_observe(WORLDS[w]); + } + for requester in 1u8..=6 { + for hash in 1u8..=5 { + for request in [Request::Fetch, Request::Observe] { + let got = decide(&t, &p, &id(requester), &blob(hash), request); + let want = spec(&t, &p, &id(requester), &blob(hash), request); + prop_assert_eq!( + got, + want, + "requester {} hash {} {:?}", + requester, + hash, + request + ); + } + } + } + } + } +} diff --git a/pkgs/id/src/encryption/history.rs b/pkgs/id/crates/id-groups/src/encryption/history.rs similarity index 98% rename from pkgs/id/src/encryption/history.rs rename to pkgs/id/crates/id-groups/src/encryption/history.rs index 8960938ea7..a020086ab7 100644 --- a/pkgs/id/src/encryption/history.rs +++ b/pkgs/id/crates/id-groups/src/encryption/history.rs @@ -3,7 +3,7 @@ //! A welcome carries the group secrets the joiner may read. `Full` carries every secret the adder //! holds, so the joiner reads the whole history. `Recent(n)` carries the newest `n`, so the joiner //! reads the last `n` epochs and no older ones. A world sets its mode in its policy -//! ([`crate::groups::policy::History`]). The default is `full`. +//! ([`id_store::policy::History`]). The default is `full`. //! //! An epoch is a group secret. Creating the group, a removal and an explicit update each mint one, //! and an add does not, so a window of `n` covers the last `n` rotations and not the last `n` @@ -23,7 +23,7 @@ use p2panda_encryption::data_scheme::group_secret::{ use serde::{Deserialize, Serialize}; use thiserror::Error; -use crate::groups::policy::History; +use id_store::policy::History; /// How long a joiner waits for a member to answer a history request before it gives up (P4.6). pub const HISTORY_WAIT: Duration = Duration::from_secs(30); diff --git a/pkgs/id/src/encryption/mod.rs b/pkgs/id/crates/id-groups/src/encryption/mod.rs similarity index 100% rename from pkgs/id/src/encryption/mod.rs rename to pkgs/id/crates/id-groups/src/encryption/mod.rs diff --git a/pkgs/id/src/encryption/notice.rs b/pkgs/id/crates/id-groups/src/encryption/notice.rs similarity index 100% rename from pkgs/id/src/encryption/notice.rs rename to pkgs/id/crates/id-groups/src/encryption/notice.rs diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/crates/id-groups/src/encryption/ordering.rs similarity index 100% rename from pkgs/id/src/encryption/ordering.rs rename to pkgs/id/crates/id-groups/src/encryption/ordering.rs diff --git a/pkgs/id/src/encryption/roster.rs b/pkgs/id/crates/id-groups/src/encryption/roster.rs similarity index 100% rename from pkgs/id/src/encryption/roster.rs rename to pkgs/id/crates/id-groups/src/encryption/roster.rs diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/crates/id-groups/src/encryption/scheme.rs similarity index 99% rename from pkgs/id/src/encryption/scheme.rs rename to pkgs/id/crates/id-groups/src/encryption/scheme.rs index 753b3f3f5a..3e85c8657a 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/crates/id-groups/src/encryption/scheme.rs @@ -49,7 +49,7 @@ use super::history::{HistoryAnswer, HistoryError, HistoryMode, HistoryRequest, a use super::ordering::{Envelope, MAX_PARENTS, Orderer}; use super::roster::Roster; use crate::groups::{GroupView, Key, Policy}; -use crate::rejection::Reason; +use id_core::rejection::Reason; /// The name the group policy gives this scheme. pub const DATASCHEME: &str = "datascheme"; diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/crates/id-groups/src/encryption/tests.rs similarity index 99% rename from pkgs/id/src/encryption/tests.rs rename to pkgs/id/crates/id-groups/src/encryption/tests.rs index f4b266526f..7edcd68b81 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/crates/id-groups/src/encryption/tests.rs @@ -28,7 +28,7 @@ use super::*; use crate::groups::{ Body, Create, Event, GroupView, Key, MemberOp, Policy, Role, Scheme, Template, fold, }; -use crate::rejection::Reason; +use id_core::rejection::Reason; fn person(seed: u8) -> (Key, VerifyingKey) { let verifying = SigningKey::from_bytes(&[seed; 32]).verifying_key(); @@ -904,7 +904,7 @@ fn test_a_full_welcome_above_the_cap_is_split_and_reassembled() { fn test_a_welcome_within_one_frame_is_one_chunk() { let mut cast = Cast::new(&[1, 2, 3, 4]); let (add, _) = full_welcome(&mut cast, 2); - let chunks = split(&add, crate::world_session::MAX_FRAME_BYTES).expect("split"); + let chunks = split(&add, id_core::frames::MAX_FRAME_BYTES).expect("split"); assert_eq!(chunks.len(), 1); let mut joiner = Reassembly::default(); assert!(joiner.push(&chunks[0]).expect("one chunk").is_some()); diff --git a/pkgs/id/src/encryption/welcome.rs b/pkgs/id/crates/id-groups/src/encryption/welcome.rs similarity index 99% rename from pkgs/id/src/encryption/welcome.rs rename to pkgs/id/crates/id-groups/src/encryption/welcome.rs index 8df0767191..db0456bb9e 100644 --- a/pkgs/id/src/encryption/welcome.rs +++ b/pkgs/id/crates/id-groups/src/encryption/welcome.rs @@ -26,7 +26,7 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; use super::ordering::Envelope; -use crate::world_session::MAX_FRAME_BYTES; +use id_core::frames::MAX_FRAME_BYTES; /// Bytes a chunk spends on everything but its payload: its position, the total, the two digests /// and their CBOR framing. diff --git a/pkgs/id/src/groups/actions.rs b/pkgs/id/crates/id-groups/src/groups/actions.rs similarity index 100% rename from pkgs/id/src/groups/actions.rs rename to pkgs/id/crates/id-groups/src/groups/actions.rs diff --git a/pkgs/id/src/groups/log.rs b/pkgs/id/crates/id-groups/src/groups/log.rs similarity index 98% rename from pkgs/id/src/groups/log.rs rename to pkgs/id/crates/id-groups/src/groups/log.rs index c86adbee55..43e06e2e1b 100644 --- a/pkgs/id/src/groups/log.rs +++ b/pkgs/id/crates/id-groups/src/groups/log.rs @@ -7,7 +7,7 @@ //! comes after every event before it. The fold needs that: it refuses an `after` it cannot place. //! //! Events are not signed here. The caller names the author, and the log is trusted as the file the -//! node keeps. Signature checks belong to the event store (see [`crate::chain`]). +//! node keeps. Signature checks belong to the event store (see [`id_store::chain`]). use std::collections::BTreeSet; use std::fs::OpenOptions; @@ -20,10 +20,6 @@ use p2panda_core::Hash; use super::fold::{FoldError, Outcome, Projection, fold}; -/// The serde adapters for the group model types, re-exported from -/// `id-events` (step 2b of the crate split, #4405): the model they -/// serialize moved down with the fold, and the adapters moved with it. -pub(crate) use id_events::groups::wire; use super::{Body, Event, Key}; /// The file a node keeps its group log in, under its data directory. diff --git a/pkgs/id/crates/id-groups/src/groups/mod.rs b/pkgs/id/crates/id-groups/src/groups/mod.rs new file mode 100644 index 0000000000..4d2afdd048 --- /dev/null +++ b/pkgs/id/crates/id-groups/src/groups/mod.rs @@ -0,0 +1,42 @@ +//! Groups (Phase 2, P2.4) — the policy/enforcement remainder of the +//! group layer, in `id-groups` since step 4 of the pkgs/id crate +//! split (#4407). +//! +//! The group model types and [`fold`] are group-projection +//! vocabulary owned by the events layer (step 2b, #4405), so the +//! model, `policy`, `event`, `fold`, `friendship` and the private +//! `delegation` module live in `id_events::groups`, and this module +//! re-exports them at the paths the facade has always presented. +//! What lives here is the remainder over that projection: +//! [`actions`], [`log`] and [`warnings`]. The cross-world bridge +//! (`worlds`) stays in the facade until step 5 extracts `id-worlds`. +//! +//! A group changes only by events. [`fold`] computes its state from +//! the whole set of events, so the result does not depend on the order +//! the events arrived in. Membership operations go through +//! [`id_core::membership`], which wraps p2panda-auth. The rules +//! p2panda-auth does not have are ours: the Admin role, the policy +//! record, the member cap, and dissolve. +//! +//! - Anyone may create a group. A normal group makes its creator Admin. +//! - Only an Admin may change a role or the policy, including the member cap. +//! - A friendship has no Admin unless its create asks for one (`admins_on_create`). +//! +//! Authority and the cap are checked against the events that come before each event in the +//! canonical order. See [`fold`]. + +pub mod actions; +pub mod log; +pub mod warnings; + +pub use id_events::groups::{ + Body, Create, DEVICE_ADD_KIND, DEVICE_REVOKE_KIND, Delegate, DeviceOp, Event, Grant, Key, + MemberOp, Role, +}; +pub use id_events::groups::{ + Delegation, History, Join, OnMemberRemoved, Policy, Removal, RemoveMode, RemoveModeKind, + RemovePolicy, RemoveSuccessor, RoleRules, Scheme, SuccessorKind, Template, TransferOpts, +}; +pub use id_events::groups::{DeviceGrant, FoldError, GroupView, Outcome, Projection, Refusal}; +pub use id_events::groups::{Pair, friendship_id}; +pub use id_events::groups::{event, fold, friendship, policy}; diff --git a/pkgs/id/src/groups/warnings.rs b/pkgs/id/crates/id-groups/src/groups/warnings.rs similarity index 100% rename from pkgs/id/src/groups/warnings.rs rename to pkgs/id/crates/id-groups/src/groups/warnings.rs diff --git a/pkgs/id/crates/id-groups/src/lib.rs b/pkgs/id/crates/id-groups/src/lib.rs new file mode 100644 index 0000000000..08704a8699 --- /dev/null +++ b/pkgs/id/crates/id-groups/src/lib.rs @@ -0,0 +1,32 @@ +//! Groups layer of the `id` crate. +//! +//! Step 4 of the pkgs/id crate split (#3447 umbrella, #4407): the +//! policy/enforcement remainder of the group layer lives here, over +//! the group model and fold in `id-events` (step 2b ruling on #4405: +//! the model, `fold`, `policy`, `friendship` and the writer-set +//! vocabulary are group-projection vocabulary owned by the events +//! layer, and do not move again): +//! +//! - [`groups`]: the actions a user takes on groups, the group log +//! one node keeps for its groups, and the local size/churn warnings. +//! The submodule re-exports the `id_events::groups` model at the +//! same paths the facade has always presented. +//! - [`blob_gate`]: who may fetch or observe a blob — the gate's +//! policy, verdicts and provider event wiring over the +//! [`blob_gate::WorldAccess`] trait from `id-events`. The +//! `FoldedWorlds` implementation of that trait stays in the facade +//! with `groups::worlds` until step 5 extracts `id-worlds`. +//! - [`encryption`]: group encryption on the `DataScheme` of +//! `p2panda-encryption` — the session adapter, causal ordering, +//! history modes and welcome chunking. Its one upward reference was +//! the frame cap: `MAX_FRAME_BYTES` already lives in +//! `id_core::frames` since step 3a (frames moved to id-core; the +//! facade's `world_session` only re-exports it), so the welcome +//! chunking names it there. +//! +//! The facade re-exports each module at its historical `id::` path, +//! so no call site outside the moved modules changed. + +pub mod blob_gate; +pub mod encryption; +pub mod groups; diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index 8437fc98ee..0262322de3 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -1,132 +1,39 @@ -//! Who may fetch or observe a blob (P3.4, decision 5). +//! Who may fetch or observe a blob (P3.4, decision 5) — facade shim +//! over `id-groups`, plus the folded-worlds adapter. //! -//! iroh-blobs serves a `get` for any hash to any peer that connects. Under its default -//! observe mode it also answers `observe` with the blob's size and held ranges, for anyone. -//! This module decides each of those requests from the requester's [`EndpointId`] and the hash: +//! Step 4 of the pkgs/id crate split (#4407): the gate itself — +//! [`BlobPolicy`], [`Request`], [`decide`], [`decide_with_blocks`] and +//! the provider wiring in [`blob_events`] — lives in +//! `id_groups::blob_gate`, over the [`WorldAccess`] trait the events +//! layer owns (step 2b). What stays here is [`FoldedWorlds`], the +//! `WorldAccess` implementation over the folded worlds: it folds +//! through [`crate::groups::worlds::Worlds`], which is seam 6's +//! bridge file and leaves for `id-worlds` in step 5, so the adapter +//! stays in the facade with it (the same split step 2a used for the +//! store traits: trait and gate below, world-folding adapter above). +//! Step 5 moves `FoldedWorlds` together with `worlds.rs`. //! -//! - **Fetch** (`get`, and every hash of a `get_many`) is allowed only to a current member of a -//! world that references the hash. A world references a blob when one of its artifacts or -//! documents names the hash. -//! - **Observe** needs the same membership, and the server policy must serve observe for that -//! world. Observe is off by default. A world can narrow it off for its own blobs, but cannot -//! switch it on. -//! - **Refusals look the same.** A hash that no world references and a hash the requester may -//! not reach get the same verdict. The decision reads only the reference index and the -//! membership table, never the blob store. -//! - **Fails closed.** A request from a connection with no known `EndpointId` is refused, and so -//! is one whose verdict cannot be delivered. -//! -//! The reference index and the membership query are behind [`WorldAccess`]. [`FoldedWorlds`] -//! answers membership from the folded worlds. Its reference index has no producer yet, so -//! [`blob_events`] is not wired into `id serve`. +//! The gate's own documentation, in `id_groups::blob_gate`: a fetch +//! is allowed only to a current member of a world that references +//! the hash; observe needs the same membership and a server policy +//! that serves observe for that world; refusals look the same +//! whether the hash is unreferenced or the requester may not reach +//! it; and an unknown requester is refused. -use std::{ - collections::{BTreeSet, HashMap}, - sync::Arc, -}; +use std::collections::{BTreeSet, HashMap}; use iroh_base::EndpointId; -use iroh_blobs::{ - Hash, - provider::events::{ - AbortReason, ConnectMode, EventMask, EventSender, ObserveMode, ProviderMessage, RequestMode, - }, -}; +use iroh_blobs::Hash; -use crate::access::AccessPolicy; -use crate::event_store::BlockList; use crate::groups::{Role, worlds::Worlds}; -/// The two questions the gate asks of the world graph. The trait is -/// sync-gating vocabulary owned by the events layer since step 2b of -/// the crate split (#4405); it is re-exported here at its historical -/// path, and the implementations (below, over the folded worlds) stay -/// with the gate until step 4. -pub use id_events::world_access::WorldAccess; - -/// The server's blob policy. -/// -/// `observe` is the server default and is off unless enabled. A world in `narrowed` refuses -/// observe for its blobs even when the server allows it. Fetch has no switch: every fetch is -/// decided by membership. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct BlobPolicy { - observe: bool, - narrowed: BTreeSet, -} - -impl BlobPolicy { - /// Serve observe for every world that does not narrow it. - #[must_use] - pub const fn with_observe(mut self) -> Self { - self.observe = true; - self - } - - /// Refuse observe for the blobs `world` references, whatever the server default. - #[must_use] - pub fn narrow_observe(mut self, world: impl Into) -> Self { - self.narrowed.insert(world.into()); - self - } - - /// Whether observe may be served for the blobs `world` references. - pub fn observe_allowed(&self, world: &str) -> bool { - self.observe && !self.narrowed.contains(world) - } -} - -/// The two request kinds the gate decides. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Request { - /// A `get` or one hash of a `get_many`. - Fetch, - /// An `observe`. - Observe, -} - -/// Whether `requester` may make `request` for `hash`. -/// -/// Allowed when some world that references `hash` has the requester as a current member and, -/// for an observe, the policy serves observe for that world. -pub fn decide( - access: &impl WorldAccess, - policy: &BlobPolicy, - requester: &EndpointId, - hash: &Hash, - request: Request, -) -> bool { - decide_with_blocks(access, policy, None, requester, hash, request) -} +pub use id_groups::blob_gate::{ + BlobPolicy, Request, blob_events, blob_events_with_blocks, decide, decide_with_blocks, +}; -/// [`decide`], with the operator block list composed in (#2245): a -/// requester blocked by endpoint key is refused fetch and observe alike, -/// member or not. The seam's shape stays the crate's bool verdict (the -/// provider's `AbortReason::Permission` is what a refusal becomes in -/// [`blob_events_with_blocks`]). Pushes are not decided here: a block -/// changes serving only, never what the store ingests. -/// -/// `blocks` is `None` for a gate with no list attached — exactly -/// [`decide`]'s behaviour. -pub fn decide_with_blocks( - access: &impl WorldAccess, - policy: &BlobPolicy, - blocks: Option<&dyn BlockList>, - requester: &EndpointId, - hash: &Hash, - request: Request, -) -> bool { - if blocks.is_some_and(|blocks| blocks.peer_blocked(requester.as_bytes())) { - return false; - } - access.worlds_referencing(hash).iter().any(|world| { - access.is_current_member(world, requester) - && match request { - Request::Fetch => true, - Request::Observe => policy.observe_allowed(world), - } - }) -} +/// The two questions the gate asks of the world graph, re-exported at +/// its historical path (the trait itself is `id_events::world_access`). +pub use id_events::world_access::WorldAccess; /// [`WorldAccess`] over the folded worlds. /// @@ -164,133 +71,17 @@ impl WorldAccess for FoldedWorlds { } } -/// The verdict for a request from `peer`: allowed only when the peer is known and `allow` -/// says so. An unknown peer is refused. -fn admit( - peer: Option<&EndpointId>, - allow: impl FnOnce(&EndpointId) -> bool, -) -> Result<(), AbortReason> { - match peer { - Some(id) if allow(id) => Ok(()), - _ => Err(AbortReason::Permission), - } -} - -/// Build the [`EventSender`] that a provider passes to `BlobsProtocol::new`. -/// -/// Fetch, `get_many` and observe are decided by [`decide`] over `access`. Pushes are decided by -/// `writes`, as in [`crate::access::blobs_events`]. Every request is intercepted, so no store -/// read happens before the verdict. -/// -/// A background task is spawned on the current Tokio runtime and ends when the sender is -/// dropped. -pub fn blob_events( - access: Arc, - policy: BlobPolicy, - writes: AccessPolicy, -) -> EventSender { - blob_events_with_blocks(access, policy, writes, None) -} - -/// [`blob_events`], with the operator block list composed into every -/// serving verdict (#2245): a blocked endpoint is refused `get`, -/// `get_many`, and `observe` through the same `AbortReason::Permission` -/// as a non-member, so a refusal still does not reveal which rule made -/// it. Push verdicts are unchanged — writes are ingest, and a block -/// never rejects what a peer sends, only what it is served. -pub fn blob_events_with_blocks( - access: Arc, - policy: BlobPolicy, - writes: AccessPolicy, - blocks: Option>, -) -> EventSender { - let (tx, mut rx) = tokio::sync::mpsc::channel::(64); - let mask = EventMask { - connected: ConnectMode::Notify, - get: RequestMode::Intercept, - get_many: RequestMode::Intercept, - push: RequestMode::Intercept, - observe: ObserveMode::Intercept, - ..EventMask::DEFAULT - }; - tokio::spawn(async move { - let mut peers: HashMap = HashMap::new(); - while let Some(msg) = rx.recv().await { - match msg { - ProviderMessage::ClientConnectedNotify(m) => { - if let Some(id) = m.endpoint_id { - peers.insert(m.connection_id, id); - } - } - ProviderMessage::ConnectionClosed(m) => { - peers.remove(&m.connection_id); - } - ProviderMessage::GetRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_blocks( - &*access, - &policy, - blocks.as_deref(), - id, - &m.request.hash, - Request::Fetch, - ) - }); - let _ = m.tx.send(verdict).await; - } - ProviderMessage::GetManyRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| { - m.request.hashes.iter().all(|hash| { - decide_with_blocks( - &*access, - &policy, - blocks.as_deref(), - id, - hash, - Request::Fetch, - ) - }) - }); - let _ = m.tx.send(verdict).await; - } - ProviderMessage::ObserveRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| { - decide_with_blocks( - &*access, - &policy, - blocks.as_deref(), - id, - &m.request.hash, - Request::Observe, - ) - }); - let _ = m.tx.send(verdict).await; - } - ProviderMessage::PushRequestReceived(m) => { - let verdict = admit(peers.get(&m.connection_id), |id| writes.can_write(id)); - let _ = m.tx.send(verdict).await; - } - _ => {} - } - } - }); - EventSender::new(tx, mask) -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { - use std::collections::BTreeMap; + use std::collections::{BTreeMap, HashMap}; use iroh_base::SecretKey; - use proptest::prelude::*; use super::*; use crate::groups::policy::Policy; use crate::groups::{Body, Create, Event, MemberOp, Template}; - const WORLDS: [&str; 3] = ["alpha", "beta", "gamma"]; - fn id(n: u8) -> EndpointId { SecretKey::from_bytes(&[n; 32]).public() } @@ -299,164 +90,6 @@ mod tests { Hash::from_bytes([n; 32]) } - /// Membership and references as plain lists, read by both `decide` and [`spec`]. - #[derive(Debug, Default)] - struct Table { - members: Vec<(String, EndpointId)>, - refs: Vec<(Hash, String)>, - } - - impl WorldAccess for Table { - fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { - self.members - .iter() - .any(|(w, m)| w == world && m == requester) - } - - fn worlds_referencing(&self, hash: &Hash) -> Vec { - self.refs - .iter() - .filter(|(h, _)| h == hash) - .map(|(_, w)| w.clone()) - .collect() - } - } - - /// The rule as a scan of the lists: some world names the hash, the requester is a member - /// of it, and an observe is served only where the policy serves observe. - fn spec(t: &Table, p: &BlobPolicy, r: &EndpointId, h: &Hash, req: Request) -> bool { - t.refs.iter().any(|(rh, w)| { - rh == h - && t.members.iter().any(|(mw, m)| mw == w && m == r) - && (req == Request::Fetch || (p.observe && !p.narrowed.contains(w))) - }) - } - - fn one_world(member: EndpointId, hash: Hash) -> Table { - Table { - members: vec![("docs".to_owned(), member)], - refs: vec![(hash, "docs".to_owned())], - } - } - - #[test] - fn a_non_member_is_refused_fetch_and_observe() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - assert!(!decide(&t, &p, &id(2), &blob(9), Request::Fetch)); - assert!(!decide(&t, &p, &id(2), &blob(9), Request::Observe)); - } - - #[test] - fn a_member_of_the_referencing_world_fetches() { - let t = one_world(id(1), blob(9)); - assert!(decide( - &t, - &BlobPolicy::default(), - &id(1), - &blob(9), - Request::Fetch - )); - } - - #[test] - fn a_blocked_member_is_refused_fetch_and_observe() { - // #2245: the block composes over membership — a current member - // blocked by endpoint key is served nothing. - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - let blocks = crate::pull_policy::testing::stub_blocks(&[*id(1).as_bytes()], &[]); - for request in [Request::Fetch, Request::Observe] { - assert!(!decide_with_blocks( - &t, - &p, - Some(&*blocks), - &id(1), - &blob(9), - request - )); - } - // A list that blocks someone else leaves the member's verdict - // exactly what membership decides. - let blocks = crate::pull_policy::testing::stub_blocks(&[*id(2).as_bytes()], &[]); - assert!(decide_with_blocks( - &t, - &p, - Some(&*blocks), - &id(1), - &blob(9), - Request::Fetch - )); - } - - #[test] - fn a_member_of_an_unrelated_world_is_refused() { - let t = Table { - members: vec![("other".to_owned(), id(1))], - refs: vec![(blob(9), "docs".to_owned())], - }; - let p = BlobPolicy::default().with_observe(); - assert!(!decide(&t, &p, &id(1), &blob(9), Request::Fetch)); - assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); - } - - #[test] - fn observe_is_refused_by_default_even_for_a_member() { - let t = one_world(id(1), blob(9)); - assert!(!BlobPolicy::default().observe_allowed("docs")); - assert!(!decide( - &t, - &BlobPolicy::default(), - &id(1), - &blob(9), - Request::Observe - )); - assert!(decide( - &t, - &BlobPolicy::default(), - &id(1), - &blob(9), - Request::Fetch - )); - } - - #[test] - fn observe_is_allowed_for_a_member_when_the_server_enables_it() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); - } - - #[test] - fn a_world_can_narrow_observe_off_while_the_server_allows_it() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe().narrow_observe("docs"); - assert!(!decide(&t, &p, &id(1), &blob(9), Request::Observe)); - assert!(decide(&t, &p, &id(1), &blob(9), Request::Fetch)); - } - - #[test] - fn a_narrowed_world_does_not_hide_observe_from_another_referencing_world() { - let t = Table { - members: vec![("docs".to_owned(), id(1)), ("team".to_owned(), id(1))], - refs: vec![(blob(9), "docs".to_owned()), (blob(9), "team".to_owned())], - }; - let p = BlobPolicy::default().with_observe().narrow_observe("docs"); - assert!(decide(&t, &p, &id(1), &blob(9), Request::Observe)); - } - - #[test] - fn an_unknown_hash_is_refused_like_a_denied_one() { - let t = one_world(id(1), blob(9)); - let p = BlobPolicy::default().with_observe(); - for request in [Request::Fetch, Request::Observe] { - // Unknown: no world names blob(5). Denied: a stranger asks for blob(9). - let unknown = decide(&t, &p, &id(1), &blob(5), request); - let denied = decide(&t, &p, &id(2), &blob(9), request); - assert!(!unknown && !denied, "{request:?}"); - } - } - /// The world `docs`, founded by `founder`, which adds `member` as a reader and, when /// `removed`, removes them again. Folded as the store folds a world. fn folded(founder: EndpointId, member: EndpointId, removed: bool) -> Worlds { @@ -553,48 +186,4 @@ mod tests { let p = BlobPolicy::default().with_observe(); assert!(decide(&g, &p, &id(2), &blob(9), Request::Observe)); } - - proptest! { - #[test] - fn decide_matches_the_spec_for_every_pair( - members in proptest::collection::vec((0usize..3, 1u8..6), 0..12), - refs in proptest::collection::vec((1u8..6, 0usize..3), 0..12), - observe in any::(), - narrowed in proptest::collection::vec(0usize..3, 0..3), - ) { - let t = Table { - members: members - .iter() - .map(|&(w, k)| (WORLDS[w].to_owned(), id(k))) - .collect(), - refs: refs - .iter() - .map(|&(h, w)| (blob(h), WORLDS[w].to_owned())) - .collect(), - }; - let mut p = BlobPolicy::default(); - if observe { - p = p.with_observe(); - } - for &w in &narrowed { - p = p.narrow_observe(WORLDS[w]); - } - for requester in 1u8..=6 { - for hash in 1u8..=5 { - for request in [Request::Fetch, Request::Observe] { - let got = decide(&t, &p, &id(requester), &blob(hash), request); - let want = spec(&t, &p, &id(requester), &blob(hash), request); - prop_assert_eq!( - got, - want, - "requester {} hash {} {:?}", - requester, - hash, - request - ); - } - } - } - } - } } diff --git a/pkgs/id/src/encryption.rs b/pkgs/id/src/encryption.rs new file mode 100644 index 0000000000..6ef7001ef3 --- /dev/null +++ b/pkgs/id/src/encryption.rs @@ -0,0 +1,14 @@ +//! Group encryption — facade re-export of `id_groups::encryption` +//! (moved in step 4 of the crate split, #4407). +//! +//! The implementation — the `DataScheme` adapter ([`scheme`]), the +//! membership roster, causal ordering, history modes, welcome +//! chunking and the scheme-none notice — lives in the `id-groups` +//! crate over `id-events`' group model. Its one upward reference was +//! the frame cap: `MAX_FRAME_BYTES` has lived in `id_core::frames` +//! since step 3a (the facade's `world_session` only re-exports it), +//! so the moved code names it there and no session type crossed. +//! +//! [`scheme`]: id_groups::encryption::scheme + +pub use id_groups::encryption::*; diff --git a/pkgs/id/src/groups/mod.rs b/pkgs/id/src/groups/mod.rs index 327688c2b0..0fadb36eaa 100644 --- a/pkgs/id/src/groups/mod.rs +++ b/pkgs/id/src/groups/mod.rs @@ -1,13 +1,16 @@ -//! Groups (Phase 2, P2.4) — facade shim over `id-events`. +//! Groups (Phase 2, P2.4) — facade shim over `id-events` and `id-groups`. //! //! Step 2b of the pkgs/id crate split (#4405; design ruling on #4405): //! the group model types and [`fold`] are group-projection vocabulary //! owned by the events layer, so `groups::mod`'s model, `policy`, //! `event`, `fold`, `friendship` and the private `delegation` module -//! live in `id_events::groups` now, and this module re-exports them at -//! their historical paths. The policy/enforcement remainder of the -//! group layer — [`actions`], [`log`], [`warnings`], [`worlds`] — -//! stays here until step 4 extracts `id-groups` over `id-events`. +//! live in `id_events::groups`, and this module re-exports them at +//! their historical paths. Step 4 (#4407) extracted the +//! policy/enforcement remainder — [`actions`], [`log`], [`warnings`] — +//! into `id-groups` over `id-events`, re-exported here likewise. +//! [`worlds`] alone stays in the facade: seam 6 of the design sends +//! the cross-world bridge to `id-worlds` in step 5, and it is the +//! only submodule still defined in this directory. //! //! A group changes only by events. [`fold`] computes its state from //! the whole set of events, so the result does not depend on the order @@ -23,21 +26,18 @@ //! Authority and the cap are checked against the events that come before each event in the //! canonical order. See [`fold`]. -pub mod actions; -pub mod log; -pub mod warnings; pub mod worlds; -pub use id_events::groups::{event, fold, friendship, policy}; +pub use id_groups::groups::{actions, log, warnings}; + pub use id_events::groups::{ Body, Create, DEVICE_ADD_KIND, DEVICE_REVOKE_KIND, Delegate, DeviceOp, Event, Grant, Key, MemberOp, Role, }; -pub use id_events::groups::{ - DeviceGrant, FoldError, GroupView, Outcome, Projection, Refusal, -}; -pub use id_events::groups::{Pair, friendship_id}; pub use id_events::groups::{ Delegation, History, Join, OnMemberRemoved, Policy, Removal, RemoveMode, RemoveModeKind, RemovePolicy, RemoveSuccessor, RoleRules, Scheme, SuccessorKind, Template, TransferOpts, }; +pub use id_events::groups::{DeviceGrant, FoldError, GroupView, Outcome, Projection, Refusal}; +pub use id_events::groups::{Pair, friendship_id}; +pub use id_events::groups::{event, fold, friendship, policy};