From f89b565629826d6081e124fb51c3416183cd52f4 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 05:16:09 -0600 Subject: [PATCH] pkgs/id crate split step 2b-1: create id-events with group-projection vocabulary (#4405) --- pkgs/id/Cargo.lock | 22 + pkgs/id/Cargo.toml | 7 +- pkgs/id/crates/id-events/Cargo.toml | 133 +++++ .../id-events}/src/groups/delegation.rs | 0 .../id-events}/src/groups/event.rs | 0 .../{ => crates/id-events}/src/groups/fold.rs | 6 +- .../id-events}/src/groups/friendship.rs | 0 pkgs/id/crates/id-events/src/groups/mod.rs | 245 ++++++++++ .../id-events}/src/groups/policy.rs | 4 +- .../id-events}/src/groups/tests.rs | 2 +- pkgs/id/crates/id-events/src/groups/wire.rs | 157 ++++++ pkgs/id/{ => crates/id-events}/src/idset.rs | 10 +- .../id-events}/src/idset/expand.rs | 4 +- .../{ => crates/id-events}/src/idset/view.rs | 2 +- pkgs/id/crates/id-events/src/lib.rs | 30 ++ .../id-events}/src/local_claims.rs | 6 +- pkgs/id/crates/id-events/src/pull_policy.rs | 454 ++++++++++++++++++ pkgs/id/crates/id-events/src/world_access.rs | 22 + pkgs/id/src/blob_gate.rs | 15 +- pkgs/id/src/groups/log.rs | 165 +------ pkgs/id/src/groups/mod.rs | 249 +--------- pkgs/id/src/lib.rs | 4 +- pkgs/id/src/pull_policy.rs | 248 +--------- 23 files changed, 1135 insertions(+), 650 deletions(-) create mode 100644 pkgs/id/crates/id-events/Cargo.toml rename pkgs/id/{ => crates/id-events}/src/groups/delegation.rs (100%) rename pkgs/id/{ => crates/id-events}/src/groups/event.rs (100%) rename pkgs/id/{ => crates/id-events}/src/groups/fold.rs (99%) rename pkgs/id/{ => crates/id-events}/src/groups/friendship.rs (100%) create mode 100644 pkgs/id/crates/id-events/src/groups/mod.rs rename pkgs/id/{ => crates/id-events}/src/groups/policy.rs (99%) rename pkgs/id/{ => crates/id-events}/src/groups/tests.rs (99%) create mode 100644 pkgs/id/crates/id-events/src/groups/wire.rs rename pkgs/id/{ => crates/id-events}/src/idset.rs (99%) rename pkgs/id/{ => crates/id-events}/src/idset/expand.rs (99%) rename pkgs/id/{ => crates/id-events}/src/idset/view.rs (99%) create mode 100644 pkgs/id/crates/id-events/src/lib.rs rename pkgs/id/{ => crates/id-events}/src/local_claims.rs (98%) create mode 100644 pkgs/id/crates/id-events/src/pull_policy.rs create mode 100644 pkgs/id/crates/id-events/src/world_access.rs diff --git a/pkgs/id/Cargo.lock b/pkgs/id/Cargo.lock index 1896d58894..7befd80297 100644 --- a/pkgs/id/Cargo.lock +++ b/pkgs/id/Cargo.lock @@ -3903,6 +3903,7 @@ dependencies = [ "hmac 0.13.0", "id-caps", "id-core", + "id-events", "id-store", "iroh", "iroh-base", @@ -4000,6 +4001,27 @@ dependencies = [ "vt100", ] +[[package]] +name = "id-events" +version = "0.1.0" +dependencies = [ + "anyhow", + "cbor-core", + "clap", + "id-core", + "id-store", + "iroh-base", + "iroh-blobs", + "p2panda-auth", + "p2panda-core", + "proptest", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", + "unicode-normalization", +] + [[package]] name = "id-native-shell" version = "0.1.0" diff --git a/pkgs/id/Cargo.toml b/pkgs/id/Cargo.toml index 6d64152be7..2505746eb8 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-native-shell"] +members = ["crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "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"] +default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events"] # ============================================================================= # Features @@ -74,6 +74,9 @@ id-caps = { path = "crates/id-caps", default-features = false } # Store-family modules extracted in step 2a of the crate split (#4405). # Re-exported at their historical crate:: paths in src/lib.rs. id-store = { path = "crates/id-store", default-features = false } +# Events-family modules extracted in step 2b of the crate split (#4405). +# Re-exported at their historical crate:: paths in src/lib.rs. +id-events = { path = "crates/id-events", default-features = false } anyhow = "1" cbor-core = { version = "=0.10.1", features = ["serde"] } # Calendar arithmetic and the IANA time-zone database for the did-it tracker's diff --git a/pkgs/id/crates/id-events/Cargo.toml b/pkgs/id/crates/id-events/Cargo.toml new file mode 100644 index 0000000000..ee4c04fc64 --- /dev/null +++ b/pkgs/id/crates/id-events/Cargo.toml @@ -0,0 +1,133 @@ +[package] +name = "id-events" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +description = "Events layer of the id crate: event store, group projection, writer sets and sync gating (pkgs/id crate split step 2b, #4405)" +license = "MIT OR Apache-2.0" + +# Step 2b of the pkgs/id crate split (#3447 umbrella, #4405): the events +# family lives here — the event store implementation, the local event +# log, event sync and attestation — together with the vocabulary the +# design ruling on #4405 assigns to the events layer: the group model +# and fold (group-projection vocabulary: `groups`), the writer-set +# surface the store's writer-set reads need (`idset`), and the +# sync-gating value types (`pull_policy`, `world_access`, +# `local_claims`). Step 4's id-groups will be the policy/enforcement +# remainder of the facade's group layer, depending on this crate. +# Dependencies per the design map: id-core, id-store, id-caps (the +# event family names no caps surface today, so only the first two are +# linked; id-caps joins when a moved module first names it). + +[features] +default = [] + +[dependencies] +anyhow = "1" +cbor-core = { version = "=0.10.1", features = ["serde"] } +clap = { version = "4", features = ["derive"] } +id-core = { path = "../id-core", default-features = false } +id-store = { path = "../id-store", default-features = false } +iroh-base = "1" +iroh-blobs = "0.103" +p2panda-auth = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc", features = ["serde"] } +p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +unicode-normalization = "0.1" + +[dev-dependencies] +proptest = "1.12" +tempfile = "3" + +[lints.rust] +# Rust compiler lints +unsafe_code = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } +rust_2024_compatibility = { level = "warn", priority = -1 } +missing_debug_implementations = "warn" +missing_docs = "warn" +trivial_casts = "warn" +trivial_numeric_casts = "warn" +unused_lifetimes = "warn" +unused_qualifications = "warn" +# Treat some warnings as errors in CI +# dead_code = "deny" +# unused_imports = "deny" + +[lints.clippy] +# Enable standard lint groups +all = { level = "warn", priority = -1 } +pedantic = { level = "warn", priority = -1 } +nursery = { level = "warn", priority = -1 } +cargo = { level = "warn", priority = -1 } + +# Deny critical issues - these indicate bugs or serious problems +# Test modules should add: #[allow(clippy::unwrap_used, clippy::expect_used)] +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +unimplemented = "deny" +todo = "deny" +dbg_macro = "deny" +# Allow print macros - this is a CLI application +print_stdout = "allow" +print_stderr = "allow" + +# Restriction lints - selectively enable valuable checks +clone_on_ref_ptr = "warn" +create_dir = "warn" +deref_by_slicing = "warn" +empty_structs_with_brackets = "warn" +filetype_is_file = "warn" +float_cmp_const = "warn" +fn_to_numeric_cast_any = "warn" +format_push_string = "warn" +get_unwrap = "warn" +if_then_some_else_none = "warn" +lossy_float_literal = "warn" +map_err_ignore = "warn" +mem_forget = "warn" +mixed_read_write_in_expression = "warn" +mutex_atomic = "warn" +rc_buffer = "warn" +rc_mutex = "warn" +redundant_type_annotations = "warn" +rest_pat_in_fully_bound_structs = "warn" +same_name_method = "warn" +self_named_module_files = "warn" +str_to_string = "warn" +string_add = "warn" +# string_to_string removed - clippy::implicit_clone covers it +suspicious_xor_used_as_pow = "warn" +try_err = "warn" +undocumented_unsafe_blocks = "warn" +unnecessary_safety_comment = "warn" +unnecessary_safety_doc = "warn" +unnecessary_self_imports = "warn" +unneeded_field_pattern = "warn" +verbose_file_reads = "warn" + +# Allow specific lints - too noisy or conflict with project style +module_name_repetitions = "allow" +must_use_candidate = "allow" +missing_errors_doc = "allow" +missing_panics_doc = "allow" +redundant_pub_crate = "allow" +significant_drop_tightening = "allow" +option_if_let_else = "allow" +multiple_crate_versions = "allow" +cargo_common_metadata = "allow" +too_many_lines = "allow" +# Allow these - they're reasonable for CLI app complexity +too_many_arguments = "allow" +fn_params_excessive_bools = "allow" +struct_excessive_bools = "allow" +cognitive_complexity = "allow" +future_not_send = "allow" +# TODO(P8.8): Clippy 1.99 fires these on about 50 `assert!(x.is_empty())` sites +# and 2 `chunks_exact` sites. Allowed until the lints review in plan step P8.8 +# (doc/2026-10-11T11-08-42Z_design_remaining_work/plan-phases.md). +assert_is_empty = "allow" +chunks_exact_to_as_chunks = "allow" diff --git a/pkgs/id/src/groups/delegation.rs b/pkgs/id/crates/id-events/src/groups/delegation.rs similarity index 100% rename from pkgs/id/src/groups/delegation.rs rename to pkgs/id/crates/id-events/src/groups/delegation.rs diff --git a/pkgs/id/src/groups/event.rs b/pkgs/id/crates/id-events/src/groups/event.rs similarity index 100% rename from pkgs/id/src/groups/event.rs rename to pkgs/id/crates/id-events/src/groups/event.rs diff --git a/pkgs/id/src/groups/fold.rs b/pkgs/id/crates/id-events/src/groups/fold.rs similarity index 99% rename from pkgs/id/src/groups/fold.rs rename to pkgs/id/crates/id-events/src/groups/fold.rs index e87b75e277..0f2a3c24e7 100644 --- a/pkgs/id/src/groups/fold.rs +++ b/pkgs/id/crates/id-events/src/groups/fold.rs @@ -12,7 +12,7 @@ //! rule for concurrent adds past the cap (design §5.1). The voiding track's rules for removal may //! refine how a removal meets a concurrent change. //! -//! Membership operations go to [`crate::membership`], which decides them on p2panda-auth. Each +//! Membership operations go to [`id_core::membership`], which decides them on p2panda-auth. Each //! event is handed to it once, so the causal index stays complete. An event this layer refuses is //! handed over as a no-op. //! @@ -29,11 +29,11 @@ use p2panda_auth::group::{GroupAction, GroupMember}; use p2panda_core::Hash; use thiserror::Error; -use crate::membership::{ +use id_core::membership::{ AuthId, CausalEvent, Membership, MembershipError, Outcome as Decided, Refusal as AuthRefusal, Role as Placement, }; -use crate::rejection::Reason; +use id_core::rejection::Reason; use super::delegation::{Grant, GrantVisibility, Removal, removed_member}; use super::friendship::{Pair, friendship_id}; diff --git a/pkgs/id/src/groups/friendship.rs b/pkgs/id/crates/id-events/src/groups/friendship.rs similarity index 100% rename from pkgs/id/src/groups/friendship.rs rename to pkgs/id/crates/id-events/src/groups/friendship.rs diff --git a/pkgs/id/crates/id-events/src/groups/mod.rs b/pkgs/id/crates/id-events/src/groups/mod.rs new file mode 100644 index 0000000000..4617acae23 --- /dev/null +++ b/pkgs/id/crates/id-events/src/groups/mod.rs @@ -0,0 +1,245 @@ +//! Groups (Phase 2, P2.4) — the group-projection module of `id-events` +//! (step 2b of the pkgs/id crate split, #4405; design ruling on #4405: +//! the group model and fold are group-projection vocabulary owned by +//! the events layer). The policy/enforcement remainder of the group +//! layer (actions, log, warnings, worlds, membership logic) stays in +//! the facade until step 4 (`id-groups`), which will depend on this +//! module through `id-events`. +//! +//! Groups (Phase 2, P2.4): members and roles, the signed policy record, the templates groups are +//! created from, and friendship as a two-member group (design §5). +//! +//! 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 event; +pub mod fold; +pub mod friendship; +pub mod policy; +pub mod wire; + +mod delegation; + +#[cfg(test)] +mod tests; + +use clap::ValueEnum; +use p2panda_core::Hash; +use serde::{Deserialize, Serialize}; + +pub use delegation::Grant; +pub use fold::{DeviceGrant, FoldError, GroupView, Outcome, Projection, Refusal, fold}; +pub use friendship::{Pair, friendship_id}; +pub use policy::{ + Delegation, History, Join, OnMemberRemoved, Policy, Removal, RemoveMode, RemoveModeKind, + RemovePolicy, RemoveSuccessor, RoleRules, Scheme, SuccessorKind, Template, TransferOpts, +}; + +/// The kind of a `device.add` event (P8.3). +pub const DEVICE_ADD_KIND: &str = "device.add"; + +/// The kind of a `device.revoke` event (P8.3). +pub const DEVICE_REVOKE_KIND: &str = "device.revoke"; + +/// A grant of a scope from the event's author to another account (design §7.1). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Delegate { + /// The account granted the scope. + #[serde(with = "wire::key")] + pub grantee: Key, + /// The access the grantee may exercise. Admin is a policy right and is not delegable. + pub scope: Role, + /// Whether the grantee may grant the scope on. Only a redelegatable grant extends a chain. + pub can_redelegate: bool, +} + +/// An account's key. Accounts are keys in this layer. +pub type Key = [u8; 32]; + +/// What a member may do, from least to most. `Admin` is a manager that may also change roles and +/// the policy record. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)] +pub enum Role { + /// Replicates ciphertext without keys. + Pull, + /// Reads content. + Read, + /// Edits content. + Write, + /// Adds and removes members. + Manage, + /// Manages, and changes roles and the policy record. + Admin, +} + +/// One signed group event, as the group layer sees it. The caller has verified it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Event { + /// The event's ID. + #[serde(with = "wire::hash")] + pub id: Hash, + /// The account that signed it. + #[serde(with = "wire::key")] + pub author: Key, + /// The `after` hashes, as signed. + #[serde(with = "wire::hashes")] + pub after: Vec, + /// The group it names. A normal group's create names none. A friendship's create names the + /// friendship's derived group. + #[serde(with = "wire::opt_hash")] + pub group: Option, + /// What it does. + pub body: Body, +} + +/// What a group event does. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Body { + /// Creates a group. Anyone may create one. + Create(Create), + /// Accepts a friendship request, as its other side. + Join, + /// Replaces the policy record. Admin only. + Policy(Policy), + /// Changes one member. + Member(MemberOp), + /// Grants a scope to an account. The author must hold the scope, and must reach it through a + /// chain of grants that can be passed on (design §7.2). + Delegate(Delegate), + /// Grants a scope that the grantee may use in another world (P2.7, see [`worlds`]). It is judged + /// in this event's world the way [`Body::Delegate`] is, but it gives its grantee nothing here. + Cross { + /// The grant. Its scope may be at most Write. + delegate: Delegate, + /// The world the grant names. It is not the event's own world. + world: String, + }, + /// Vetoes a grant the event has seen. The author must hold Manage and a chain (design §7). + /// From this event's causal position on, the grant and what depends on it fail. + Veto { + /// The grant's event ID. + #[serde(with = "wire::hash")] + grant: Hash, + }, + /// Authorizes or revokes a device on behalf of the account (P8.3). + Device(DeviceOp), +} + +/// What a device operation does (P8.3). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum DeviceOp { + /// Authorizes a device key to act on behalf of the account with the given scope. + Add { + /// The device key. + #[serde(with = "wire::key")] + device: Key, + /// The maximum scope the device may exercise. + scope: Role, + }, + /// Revokes a device's authorization to act on behalf of the account. + Revoke { + /// The device key. + #[serde(with = "wire::key")] + device: Key, + }, +} + +/// A group's creation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Create { + /// The template the group is created from. + pub template: Template, + /// The policy record, written out in full. + pub policy: Policy, + /// The members besides the author, with their roles. A friendship lists exactly one. + #[serde(with = "wire::members")] + pub members: Vec<(Key, Role)>, + /// Whether both friends start as Admin. Only a friendship may set it. + pub admins_on_create: bool, +} + +/// A change to one member. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub enum MemberOp { + /// Adds a member with a role. + Add { + /// The member added. + #[serde(with = "wire::key")] + member: Key, + /// Its role. + role: Role, + }, + /// Removes a member. The author may remove itself, which is leaving. The mode is concrete in + /// replicated events; `ServerDefault` is resolved before one is recorded. + Remove { + /// The member removed. + #[serde(with = "wire::key")] + member: Key, + /// What happens to the removed member's grants. + mode: RemoveMode, + }, + /// Sets a member's role. Admin only. + SetRole { + /// The member whose role changes. + #[serde(with = "wire::key")] + member: Key, + /// Its new role. + role: Role, + }, +} + +/// Wire form accepted by the event decoder. The optional legacy `successor` is read only when an +/// event has no `mode`; new events serialize only the concrete mode. +#[derive(Deserialize)] +enum MemberOpWire { + Add { + #[serde(with = "wire::key")] + member: Key, + role: Role, + }, + Remove { + #[serde(with = "wire::key")] + member: Key, + #[serde(default)] + mode: Option, + #[serde(default, with = "wire::opt_key")] + successor: Option, + }, + SetRole { + #[serde(with = "wire::key")] + member: Key, + role: Role, + }, +} + +impl<'de> Deserialize<'de> for MemberOp { + fn deserialize>(deserializer: D) -> Result { + Ok(match MemberOpWire::deserialize(deserializer)? { + MemberOpWire::Add { member, role } => Self::Add { member, role }, + MemberOpWire::Remove { + member, + mode, + successor, + } => Self::Remove { + member, + mode: mode.unwrap_or_else(|| { + successor.map_or(RemoveMode::Revoke, |key| { + RemoveMode::Transfer(TransferOpts { + successor: RemoveSuccessor::Member(key), + }) + }) + }), + }, + MemberOpWire::SetRole { member, role } => Self::SetRole { member, role }, + }) + } +} diff --git a/pkgs/id/src/groups/policy.rs b/pkgs/id/crates/id-events/src/groups/policy.rs similarity index 99% rename from pkgs/id/src/groups/policy.rs rename to pkgs/id/crates/id-events/src/groups/policy.rs index f28d9d594b..c202a96d95 100644 --- a/pkgs/id/src/groups/policy.rs +++ b/pkgs/id/crates/id-events/src/groups/policy.rs @@ -41,11 +41,11 @@ pub enum SuccessorKind { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum RemoveSuccessor { /// A specifically named member. - Member(#[serde(with = "super::log::wire::key")] Key), + Member(#[serde(with = "super::wire::key")] Key), /// A group administrator, resolved at the removal's causal position. Admin, /// A specifically designated account. - Designated(#[serde(with = "super::log::wire::key")] Key), + Designated(#[serde(with = "super::wire::key")] Key), /// The account performing the removal. Actor, } diff --git a/pkgs/id/src/groups/tests.rs b/pkgs/id/crates/id-events/src/groups/tests.rs similarity index 99% rename from pkgs/id/src/groups/tests.rs rename to pkgs/id/crates/id-events/src/groups/tests.rs index ff09198fc2..7c1c2b2b61 100644 --- a/pkgs/id/src/groups/tests.rs +++ b/pkgs/id/crates/id-events/src/groups/tests.rs @@ -16,7 +16,7 @@ use super::{ Body, Create, Delegate, DeviceOp, Event, Key, MemberOp, Outcome, Pair, Projection, Refusal, RemoveMode, RemoveSuccessor, Role, TransferOpts, fold, friendship_id, }; -use crate::rejection::Reason; +use id_core::rejection::Reason; fn key(n: u8) -> Key { [n; 32] diff --git a/pkgs/id/crates/id-events/src/groups/wire.rs b/pkgs/id/crates/id-events/src/groups/wire.rs new file mode 100644 index 0000000000..171a7a5bac --- /dev/null +++ b/pkgs/id/crates/id-events/src/groups/wire.rs @@ -0,0 +1,157 @@ +/// Serde adapters. A key or a hash is written as 64 hex characters, so a log line reads as text. +/// Each module is named for the type it adapts, and is used as `#[serde(with = "...")]`. +use p2panda_core::Hash; +use serde::de; + +use super::Key; + +fn key_text(key: &Key) -> String { + Hash::from_bytes(*key).to_hex() +} + +fn hash_text(hash: &Hash) -> String { + hash.to_hex() +} + +fn text_to_hash(text: &str) -> Result { + text.parse() + .map_err(|error| E::custom(format!("`{text}` is not 64 hex characters: {error}"))) +} + +fn text_to_key(text: &str) -> Result { + text_to_hash::(text).map(|hash| *hash.as_bytes()) +} + +/// A key, as hex. +pub mod key { + use serde::{Deserialize, Deserializer, Serializer}; + + use super::{Key, key_text, text_to_key}; + + pub fn serialize(key: &Key, serializer: S) -> Result { + serializer.serialize_str(&key_text(key)) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + text_to_key(&String::deserialize(deserializer)?) + } +} + +/// An optional key, as hex. +pub mod opt_key { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use super::{Key, key_text, text_to_key}; + + #[allow(clippy::ref_option)] // serde passes the field by reference. + pub fn serialize( + key: &Option, + serializer: S, + ) -> Result { + key.as_ref().map(key_text).serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .as_deref() + .map(text_to_key::) + .transpose() + } +} + +/// A hash, as hex. +pub mod hash { + use p2panda_core::Hash; + use serde::{Deserialize, Deserializer, Serializer}; + + use super::{hash_text, text_to_hash}; + + pub fn serialize(hash: &Hash, serializer: S) -> Result { + serializer.serialize_str(&hash_text(hash)) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + text_to_hash(&String::deserialize(deserializer)?) + } +} + +/// An optional hash, as hex. +pub mod opt_hash { + use p2panda_core::Hash; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use super::{hash_text, text_to_hash}; + + #[allow(clippy::ref_option)] // serde passes the field by reference. + pub fn serialize( + hash: &Option, + serializer: S, + ) -> Result { + hash.as_ref().map(hash_text).serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Option::::deserialize(deserializer)? + .as_deref() + .map(text_to_hash::) + .transpose() + } +} + +/// A list of hashes, as hex. +pub mod hashes { + use p2panda_core::Hash; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use super::{hash_text, text_to_hash}; + + pub fn serialize(hashes: &[Hash], serializer: S) -> Result { + hashes + .iter() + .map(hash_text) + .collect::>() + .serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Vec::::deserialize(deserializer)? + .iter() + .map(|text| text_to_hash::(text)) + .collect() + } +} + +/// A create's members, each with its role, as hex. +pub mod members { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use crate::groups::Role; + + use super::{Key, key_text, text_to_key}; + + pub fn serialize( + members: &[(Key, Role)], + serializer: S, + ) -> Result { + members + .iter() + .map(|(key, role)| (key_text(key), *role)) + .collect::>() + .serialize(serializer) + } + + pub fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + Vec::<(String, Role)>::deserialize(deserializer)? + .iter() + .map(|(text, role)| Ok((text_to_key::(text)?, *role))) + .collect() + } +} diff --git a/pkgs/id/src/idset.rs b/pkgs/id/crates/id-events/src/idset.rs similarity index 99% rename from pkgs/id/src/idset.rs rename to pkgs/id/crates/id-events/src/idset.rs index 7ddeac2830..ad488ad9ae 100644 --- a/pkgs/id/src/idset.rs +++ b/pkgs/id/crates/id-events/src/idset.rs @@ -5,8 +5,8 @@ //! A writer set is its own signed event kind, with the entry list in the event //! **body** — never in `ChainExt` — so the signed-header format, and therefore //! every existing verifier, is unchanged (spec §D1). Bodies produced here are -//! passed to [`crate::chain::sign`] as the event body and checked on receipt by -//! [`crate::chain::decode`] plus [`decode_writer_body`] / [`decode_rescind_body`]; +//! passed to [`id_store::chain::sign`] as the event body and checked on receipt by +//! [`id_store::chain::decode`] plus [`decode_writer_body`] / [`decode_rescind_body`]; //! no new crypto is involved. //! //! The body is a canonical CBOR array. A writer-set body is @@ -45,7 +45,7 @@ //! failing. Encoders always write the flag. //! //! Canonicality is judged at the CBOR value level, the way -//! [`crate::chain::decode`] judges a header: the bytes must be the canonical +//! [`id_store::chain::decode`] judges a header: the bytes must be the canonical //! encoding of the value they hold. That is what lets a legacy entry (a //! shorter array) be canonical bytes and still decode, while a re-encoded //! entry always carries the flag. @@ -66,7 +66,7 @@ use p2panda_core::Hash; use unicode_normalization::is_nfc; use crate::groups::Role; -use crate::waiting::AuthorKey; +use id_core::waiting::AuthorKey; /// Store-wired expansion over the membership layer (spec §9 item 2). pub mod expand; @@ -656,7 +656,7 @@ mod tests { use p2panda_core::SigningKey; use super::*; - use crate::chain::{ChainExt, decode, sign}; + use id_store::chain::{ChainExt, decode, sign}; fn owner() -> AuthorKey { std::array::from_fn(|i| u8::try_from(i).unwrap()) diff --git a/pkgs/id/src/idset/expand.rs b/pkgs/id/crates/id-events/src/idset/expand.rs similarity index 99% rename from pkgs/id/src/idset/expand.rs rename to pkgs/id/crates/id-events/src/idset/expand.rs index 7f5b94d28d..e2cb20d2c0 100644 --- a/pkgs/id/src/idset/expand.rs +++ b/pkgs/id/crates/id-events/src/idset/expand.rs @@ -51,8 +51,8 @@ use p2panda_auth::Access; use p2panda_core::Hash; use crate::groups::Role; -use crate::membership::{Membership, MembershipError}; -use crate::waiting::AuthorKey; +use id_core::membership::{Membership, MembershipError}; +use id_core::waiting::AuthorKey; use super::view::{GroupMembers, ProjectionError, expand_set}; use super::{Entry, WriterSet}; diff --git a/pkgs/id/src/idset/view.rs b/pkgs/id/crates/id-events/src/idset/view.rs similarity index 99% rename from pkgs/id/src/idset/view.rs rename to pkgs/id/crates/id-events/src/idset/view.rs index 8d272fe333..7d99736302 100644 --- a/pkgs/id/src/idset/view.rs +++ b/pkgs/id/crates/id-events/src/idset/view.rs @@ -8,7 +8,7 @@ use std::ops::Bound::{Excluded, Unbounded}; use p2panda_core::Hash; use crate::groups::Role; -use crate::waiting::AuthorKey; +use id_core::waiting::AuthorKey; use super::{Entry, Excludes, Rescind, WriterSet}; diff --git a/pkgs/id/crates/id-events/src/lib.rs b/pkgs/id/crates/id-events/src/lib.rs new file mode 100644 index 0000000000..9002017e7f --- /dev/null +++ b/pkgs/id/crates/id-events/src/lib.rs @@ -0,0 +1,30 @@ +//! Events layer of the `id` crate. +//! +//! Step 2b of the pkgs/id crate split (#3447 umbrella, #4405): the +//! event-store family lives here, together with the vocabulary the +//! design ruling on #4405 assigns to the events layer: +//! +//! - [`groups`]: the group model and [`groups::fold`] — a deterministic +//! projection over the event log. Resolution/roster inside the event +//! store consumes the fold, so the model and fold sit below the +//! policy/enforcement remainder of the group layer, which follows in +//! step 4 (`id-groups`) and will depend on this crate. +//! - [`idset`]: the writer-set surface. Its only group references were +//! [`groups::Role`] and [`groups::fold`], both here now, so its deps +//! resolve downward. +//! - [`pull_policy`], [`world_access`], [`local_claims`]: the +//! sync-gating value types — small leaf-like policy vocabulary the +//! event sync paths name. The facade's blob gate keeps its +//! enforcement logic and re-exports [`world_access::WorldAccess`]. +//! +//! The event-store implementation itself (`event_store`, +//! `local_events`, `event_sync`, `attestation`) joins this crate in +//! step 2b's second half. The facade re-exports each module at its +//! historical `id::` path, so no call site outside the moved modules +//! changed. + +pub mod groups; +pub mod idset; +pub mod local_claims; +pub mod pull_policy; +pub mod world_access; diff --git a/pkgs/id/src/local_claims.rs b/pkgs/id/crates/id-events/src/local_claims.rs similarity index 98% rename from pkgs/id/src/local_claims.rs rename to pkgs/id/crates/id-events/src/local_claims.rs index cfac1d4ff1..cf6560242c 100644 --- a/pkgs/id/src/local_claims.rs +++ b/pkgs/id/crates/id-events/src/local_claims.rs @@ -1,7 +1,7 @@ //! The node's own local-only tag claims (#1793, issue #1793 bullet 2). //! //! A tag claim's scope says where it lives. A shared claim is a signed `tag.set` event in the -//! event store ([`crate::tag_claims`]): it is in the sync set, so every peer receives it. A +//! event store ([`id_store::tag_claims`]): it is in the sync set, so every peer receives it. A //! **local** claim is the opposite in exactly one respect — it is never signed into the event //! store, so it is never in the sync set and never reaches another node. It is kept here, in a //! JSON file beside the event store, and only this node reads it. @@ -22,10 +22,10 @@ use std::path::{Path, PathBuf}; use p2panda_core::Hash; use serde::{Deserialize, Serialize}; -use crate::tag_claims::{ +use id_store::tag_claims::{ LocalClaim, MAX_NAME_BYTES, MAX_VALUE_BYTES, TagError, TagScope, check_text, }; -use crate::waiting::AuthorKey; +use id_core::waiting::AuthorKey; /// The file local claims live in, under the event store's directory. pub const FILE_NAME: &str = "local-claims.jsonl"; diff --git a/pkgs/id/crates/id-events/src/pull_policy.rs b/pkgs/id/crates/id-events/src/pull_policy.rs new file mode 100644 index 0000000000..8bf3502912 --- /dev/null +++ b/pkgs/id/crates/id-events/src/pull_policy.rs @@ -0,0 +1,454 @@ +//! Who may pull a world's events from this server (P6.5, decision 11). +//! +//! The policy is a local serving rule. It decides what this server sends, and a peer never sees +//! it. Nothing here goes on the wire, so two servers with different policies still sync. +//! +//! - **Open** (the default): any peer may pull the world's events. That is how sync works today. +//! - **Members**: a peer may pull only while it is a current member of the world. Membership is +//! read when each session starts, so a removed member is refused on the next pull. +//! +//! A [`PullGate`] binds a policy to one world and to the membership it is checked against. The +//! sync sessions check the gate before any event is sent. A refused peer gets no event, and the +//! refusal is clean. An open gate never reads membership. +//! +//! A gate may also carry the operator block list ([`id_store::event_types::BlockList`], #2245): +//! a peer blocked by key is refused under every policy, and a gate whose world's name is a +//! blocked topic tag serves nothing. The blocks compose with the policy — they only ever +//! narrow it. Without a list attached, a gate behaves exactly as it did before the list +//! existed. The list is read on each check, so a block or an unblock lands on the next +//! session, as a membership removal does. +//! +//! This is a config setting, not a protocol rule. The policy belongs with the world's policy. The +//! server config's `[policy]` table parses it (`id::server_config::ServerConfig::pull_policy`), +//! and `id serve` builds its live event-sync gate from that value +//! (`id::event_sync::gate`); the node's own event store is not a world and has no membership +//! source, so `members` there refuses every pull rather than serving open. Blobs are not +//! governed here. The blob gate (`id::blob_gate`) still requires membership to fetch, whatever +//! this policy says. Authorized pull is advisory: it stops an honest server from serving a +//! non-member. It does not stop re-serving, recall copies, or hide metadata. + +use std::sync::Arc; + +use iroh_base::EndpointId; + +use crate::world_access::WorldAccess; +use id_store::event_types::BlockList; + +/// Who may pull a world's events from this server. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PullPolicy { + /// Any peer may pull. The default, and today's behaviour. + #[default] + Open, + /// Only a current member of the world may pull. + Members, +} + +impl PullPolicy { + /// Whether `peer` may pull the events of `world`. Only [`PullPolicy::Members`] reads `access`, + /// and it reads it on each call, so a removal is seen by the next call. + pub fn admits(self, access: &dyn WorldAccess, world: &str, peer: &EndpointId) -> bool { + match self { + Self::Open => true, + Self::Members => access.is_current_member(world, peer), + } + } +} + +/// A policy bound to one world, and the membership it is checked against. +#[derive(Clone)] +pub struct PullGate { + policy: PullPolicy, + world: String, + access: Arc, + /// The operator block list, when the gate's owner attached one + /// ([`PullGate::with_blocks`]). Read on each check. + blocks: Option>, +} + +impl PullGate { + /// A gate for `world` under `policy`. `access` answers membership at the time of each check. + /// No operator block list is attached; [`PullGate::with_blocks`] adds one. + #[must_use] + pub fn new( + policy: PullPolicy, + world: impl Into, + access: Arc, + ) -> Self { + Self { + policy, + world: world.into(), + access, + blocks: None, + } + } + + /// Attaches the operator block list (#2245): a peer blocked by key is + /// refused under every policy, and a gate whose world's name is a + /// blocked topic tag serves nothing. The list is consulted live, so a + /// block added after the gate was built is seen by the next check. + #[must_use] + pub fn with_blocks(mut self, blocks: Arc) -> Self { + self.blocks = Some(blocks); + self + } + + /// The world this gate serves. + #[must_use] + pub fn world(&self) -> &str { + &self.world + } + + /// Whether the operator block list blocks `peer` by key. False when + /// no list is attached. + #[must_use] + pub fn peer_blocked(&self, peer: &EndpointId) -> bool { + self.blocks + .as_ref() + .is_some_and(|blocks| blocks.peer_blocked(peer.as_bytes())) + } + + /// Whether the operator block list blocks this topic tag (raw bytes: + /// a world name, or a sync topic's hash bytes). False when no list is + /// attached. Session seams that carry a topic the gate's world does + /// not name — the `log_sync` handshake — check the tag through here. + #[must_use] + pub fn topic_tag_blocked(&self, tag: &[u8]) -> bool { + self.blocks + .as_ref() + .is_some_and(|blocks| blocks.topic_tag_blocked(tag)) + } + + /// Whether `peer` may pull this world's events now: not blocked by + /// key, the world not blocked as a topic tag, and the policy admits + /// the peer. + #[must_use] + pub fn admits(&self, peer: &EndpointId) -> bool { + !self.peer_blocked(peer) + && !self.topic_tag_blocked(self.world.as_bytes()) + && self.policy.admits(self.access.as_ref(), &self.world, peer) + } +} + +impl std::fmt::Debug for PullGate { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PullGate") + .field("policy", &self.policy) + .field("world", &self.world) + .finish_non_exhaustive() + } +} + +/// A session the pull policy refused. No event was sent. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("the pull policy refuses this peer the events of world {0:?}")] +pub struct PullRefused(pub String); + +/// Fixtures for the pull tests and the session tests: a folded world, and membership a test can +/// change between two checks. +/// +/// Step 2b of the crate split (#4405): the fixture folds the same events +/// with the group-projection fold this crate now owns +/// ([`crate::groups::fold`]) and answers membership from the projection +/// directly. It previously folded through the facade's `groups::worlds` +/// and `blob_gate::FoldedWorlds`, which stay in the facade until step 4; +/// the membership the gate checks is the same set either way (the +/// fixture world has no grants, so projection membership is the whole +/// of `holds_here` there). +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +pub(crate) mod testing { + use std::collections::BTreeSet; + use std::sync::{Arc, Mutex}; + + use iroh_base::{EndpointId, SecretKey}; + use iroh_blobs::Hash; + use p2panda_core::Hash as EventHash; + + use super::{PullGate, PullPolicy}; + use crate::groups::policy::Policy; + use crate::groups::{Body, Create, Event, Key, MemberOp, Role, Template, fold}; + use crate::world_access::WorldAccess; + + /// The world every fixture names. + pub(crate) const WORLD: &str = "docs"; + + /// The identity with byte `n` repeated, so a test knows the endpoint ID before it dials. + pub(crate) fn key(n: u8) -> SecretKey { + SecretKey::from_bytes(&[n; 32]) + } + + /// The folded `docs` world: the accounts the group projection lists + /// as active members. + #[derive(Debug)] + pub(crate) struct FoldedWorlds { + members: BTreeSet, + } + + impl WorldAccess for FoldedWorlds { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + world == WORLD && self.members.contains(requester.as_bytes()) + } + + fn worlds_referencing(&self, _hash: &Hash) -> Vec { + Vec::new() + } + } + + /// The folded `docs` world, founded by `founder`, which adds `member` as a reader and, when + /// `removed`, removes them again. Folded as the store folds a world. + pub(crate) fn docs_world( + founder: EndpointId, + member: EndpointId, + removed: bool, + ) -> FoldedWorlds { + let (founder, member) = (*founder.as_bytes(), *member.as_bytes()); + let create = EventHash::digest(b"create"); + let add = EventHash::digest(b"add"); + let remove = EventHash::digest(b"remove"); + let mut events = vec![ + Event { + id: create, + author: founder, + after: Vec::new(), + group: None, + body: Body::Create(Create { + template: Template::Custom, + policy: Policy::default(), + members: Vec::new(), + admins_on_create: false, + }), + }, + Event { + id: add, + author: founder, + after: vec![create], + group: Some(create), + body: Body::Member(MemberOp::Add { + member, + role: Role::Read, + }), + }, + ]; + if removed { + events.push(Event { + id: remove, + author: founder, + after: vec![add], + group: Some(create), + body: Body::Member(MemberOp::Remove { + member, + mode: crate::groups::RemoveMode::Revoke, + }), + }); + } + let projection = fold(&events).expect("the fixture folds"); + let members = projection + .groups() + .filter(|(_, group)| group.is_active()) + .flat_map(|(_, group)| group.members.keys().copied()) + .collect(); + FoldedWorlds { members } + } + + /// Membership that a test can change between two checks, as a removal changes the fold. + #[derive(Debug)] + pub(crate) struct Live(Mutex); + + impl Live { + pub(crate) fn new(folded: FoldedWorlds) -> Self { + Self(Mutex::new(folded)) + } + + /// Replaces the membership, as the fold of a newer log does. + pub(crate) fn set(&self, folded: FoldedWorlds) { + *self.0.lock().expect("the fixture lock is not poisoned") = folded; + } + } + + impl WorldAccess for Live { + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool { + self.0 + .lock() + .is_ok_and(|folded| folded.is_current_member(world, requester)) + } + + fn worlds_referencing(&self, hash: &Hash) -> Vec { + self.0 + .lock() + .map(|folded| folded.worlds_referencing(hash)) + .unwrap_or_default() + } + } + + /// `folded` as shared membership that a gate can hold. + pub(crate) fn live(folded: FoldedWorlds) -> Arc { + Arc::new(Live::new(folded)) + } + + /// An operator block list with fixed rows, for the gate tests and the + /// session tests: the peers and topic tags it names are blocked, and + /// nothing else is. + #[derive(Debug, Default)] + pub(crate) struct StubBlocks { + /// Blocked endpoint keys. + pub peers: std::collections::HashSet<[u8; 32]>, + /// Blocked topic tags, as raw bytes. + pub topics: std::collections::HashSet>, + /// Blocked IPs, in the text form `BlockList::ip_blocked` + /// formats them in. + pub ips: std::collections::HashSet, + } + + impl id_store::event_types::BlockList for StubBlocks { + fn is_blocked(&self, kind: id_store::event_types::BlockKind, value: &[u8]) -> bool { + match kind { + id_store::event_types::BlockKind::PeerKey => { + <[u8; 32]>::try_from(value).is_ok_and(|key| self.peers.contains(&key)) + } + id_store::event_types::BlockKind::TopicTag => { + self.topics.iter().any(|t| t == value) + } + id_store::event_types::BlockKind::Ip => { + std::str::from_utf8(value).is_ok_and(|text| self.ips.contains(text)) + } + } + } + } + + /// A stub block list naming `peers` by key and `topics` by tag. + pub(crate) fn stub_blocks(peers: &[[u8; 32]], topics: &[&str]) -> Arc { + Arc::new(StubBlocks { + peers: peers.iter().copied().collect(), + topics: topics.iter().map(|t| t.as_bytes().to_vec()).collect(), + ips: std::collections::HashSet::new(), + }) + } + + /// A stub block list like [`stub_blocks`], additionally naming + /// `ips` as blocked. + pub(crate) fn stub_blocks_with_ips( + peers: &[[u8; 32]], + topics: &[&str], + ips: &[std::net::IpAddr], + ) -> Arc { + Arc::new(StubBlocks { + peers: peers.iter().copied().collect(), + topics: topics.iter().map(|t| t.as_bytes().to_vec()).collect(), + ips: ips.iter().map(|ip| ip.to_string()).collect(), + }) + } + + /// An open gate over an empty world. It never reads membership. + pub(crate) fn open_gate() -> PullGate { + PullGate::new( + PullPolicy::Open, + WORLD, + live(FoldedWorlds { + members: BTreeSet::new(), + }), + ) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::testing::{WORLD, docs_world, key, live}; + use super::*; + + #[test] + fn test_pull_policy_defaults_to_open() { + assert_eq!(PullPolicy::default(), PullPolicy::Open); + } + + /// Open pull admits a stranger: today's behaviour, pinned. + #[test] + fn test_pull_policy_open_admits_a_non_member() { + let gate = PullGate::new( + PullPolicy::Open, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ); + assert!(gate.admits(&key(9).public()), "a stranger may pull"); + assert!(gate.admits(&key(2).public()), "a member may pull"); + } + + /// The members option admits a current member, the founder included, and refuses a stranger. + #[test] + fn test_pull_policy_members_admits_only_a_current_member() { + let gate = PullGate::new( + PullPolicy::Members, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ); + assert!(gate.admits(&key(2).public()), "a member"); + assert!(gate.admits(&key(1).public()), "the founder is a member too"); + assert!(!gate.admits(&key(9).public()), "a stranger is refused"); + } + + /// The check reads membership when it runs, so a removal lands on the next check. + #[test] + fn test_pull_policy_members_refuses_a_removed_member_on_the_next_check() { + let access = live(docs_world(key(1).public(), key(2).public(), false)); + let gate = PullGate::new(PullPolicy::Members, WORLD, Arc::clone(&access)); + assert!(gate.admits(&key(2).public()), "before the removal"); + access.set(docs_world(key(1).public(), key(2).public(), true)); + assert!(!gate.admits(&key(2).public()), "after the removal"); + } + + /// #2245: a peer blocked by key is refused even under the open + /// policy, which admits every other peer. The block only narrows. + #[test] + fn test_pull_gate_refuses_a_blocked_peer_under_open_policy() { + let gate = PullGate::new( + PullPolicy::Open, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ) + .with_blocks(super::testing::stub_blocks( + &[*key(9).public().as_bytes()], + &[], + )); + assert!( + !gate.admits(&key(9).public()), + "the blocked peer is refused" + ); + assert!( + gate.admits(&key(2).public()), + "an unblocked peer still pulls" + ); + } + + /// #2245: a blocked topic tag is not pulled — a gate whose world is a + /// blocked tag serves nothing, to members included. + #[test] + fn test_pull_gate_refuses_every_peer_when_its_world_is_a_blocked_topic_tag() { + let gate = PullGate::new( + PullPolicy::Members, + WORLD, + live(docs_world(key(1).public(), key(2).public(), false)), + ) + .with_blocks(super::testing::stub_blocks(&[], &[WORLD])); + assert!( + !gate.admits(&key(2).public()), + "a member of a blocked topic" + ); + assert!( + !gate.admits(&key(1).public()), + "the founder of a blocked topic" + ); + } + + /// A gate names one world. A member of `docs` is not a member of another world. + #[test] + fn test_pull_policy_members_checks_only_the_gates_world() { + let gate = PullGate::new( + PullPolicy::Members, + "other", + live(docs_world(key(1).public(), key(2).public(), false)), + ); + assert_eq!(gate.world(), "other"); + assert!(!gate.admits(&key(2).public())); + } +} diff --git a/pkgs/id/crates/id-events/src/world_access.rs b/pkgs/id/crates/id-events/src/world_access.rs new file mode 100644 index 0000000000..b88c91783c --- /dev/null +++ b/pkgs/id/crates/id-events/src/world_access.rs @@ -0,0 +1,22 @@ +//! The two questions the blob gate and the pull policy ask of the +//! world graph (moved down in step 2b of the crate split, #4405). +//! +//! [`WorldAccess`] is sync-gating vocabulary: a leaf trait over an +//! endpoint ID and a blob hash, with no group-layer logic of its own. +//! The implementations stay where the folded worlds live — the +//! facade's `blob_gate::FoldedWorlds` until step 4 — and the facade +//! re-exports this trait at its historical `id::blob_gate::WorldAccess` +//! path. + +use iroh_base::EndpointId; +use iroh_blobs::Hash; + +/// The two questions the gate asks of the world graph. +pub trait WorldAccess: Send + Sync + 'static { + /// Whether `requester` is a current member of `world`. + fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool; + + /// The worlds whose content names `hash`. Empty for a hash that no world names, which + /// includes every unknown hash. + fn worlds_referencing(&self, hash: &Hash) -> Vec; +} diff --git a/pkgs/id/src/blob_gate.rs b/pkgs/id/src/blob_gate.rs index c006ba775c..8437fc98ee 100644 --- a/pkgs/id/src/blob_gate.rs +++ b/pkgs/id/src/blob_gate.rs @@ -37,15 +37,12 @@ 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. -pub trait WorldAccess: Send + Sync + 'static { - /// Whether `requester` is a current member of `world`. - fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool; - - /// The worlds whose content names `hash`. Empty for a hash that no world names, which - /// includes every unknown hash. - fn worlds_referencing(&self, hash: &Hash) -> Vec; -} +/// 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. /// diff --git a/pkgs/id/src/groups/log.rs b/pkgs/id/src/groups/log.rs index 0df7d5ec52..c86adbee55 100644 --- a/pkgs/id/src/groups/log.rs +++ b/pkgs/id/src/groups/log.rs @@ -19,6 +19,11 @@ use anyhow::{Context, Result}; 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. @@ -223,166 +228,6 @@ pub fn hash_from_hex(text: &str) -> Result { Hash::from_str(text.trim()).with_context(|| format!("`{text}` is not 64 hex characters")) } -/// Serde adapters. A key or a hash is written as 64 hex characters, so a log line reads as text. -/// Each module is named for the type it adapts, and is used as `#[serde(with = "...")]`. -pub(crate) mod wire { - use p2panda_core::Hash; - use serde::de; - - use crate::groups::Key; - - fn key_text(key: &Key) -> String { - Hash::from_bytes(*key).to_hex() - } - - fn hash_text(hash: &Hash) -> String { - hash.to_hex() - } - - fn text_to_hash(text: &str) -> Result { - text.parse() - .map_err(|error| E::custom(format!("`{text}` is not 64 hex characters: {error}"))) - } - - fn text_to_key(text: &str) -> Result { - text_to_hash::(text).map(|hash| *hash.as_bytes()) - } - - /// A key, as hex. - pub mod key { - use serde::{Deserialize, Deserializer, Serializer}; - - use super::{Key, key_text, text_to_key}; - - pub fn serialize(key: &Key, serializer: S) -> Result { - serializer.serialize_str(&key_text(key)) - } - - pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { - text_to_key(&String::deserialize(deserializer)?) - } - } - - /// An optional key, as hex. - pub mod opt_key { - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - - use super::{Key, key_text, text_to_key}; - - #[allow(clippy::ref_option)] // serde passes the field by reference. - pub fn serialize( - key: &Option, - serializer: S, - ) -> Result { - key.as_ref().map(key_text).serialize(serializer) - } - - pub fn deserialize<'de, D: Deserializer<'de>>( - deserializer: D, - ) -> Result, D::Error> { - Option::::deserialize(deserializer)? - .as_deref() - .map(text_to_key::) - .transpose() - } - } - - /// A hash, as hex. - pub mod hash { - use p2panda_core::Hash; - use serde::{Deserialize, Deserializer, Serializer}; - - use super::{hash_text, text_to_hash}; - - pub fn serialize(hash: &Hash, serializer: S) -> Result { - serializer.serialize_str(&hash_text(hash)) - } - - pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { - text_to_hash(&String::deserialize(deserializer)?) - } - } - - /// An optional hash, as hex. - pub mod opt_hash { - use p2panda_core::Hash; - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - - use super::{hash_text, text_to_hash}; - - #[allow(clippy::ref_option)] // serde passes the field by reference. - pub fn serialize( - hash: &Option, - serializer: S, - ) -> Result { - hash.as_ref().map(hash_text).serialize(serializer) - } - - pub fn deserialize<'de, D: Deserializer<'de>>( - deserializer: D, - ) -> Result, D::Error> { - Option::::deserialize(deserializer)? - .as_deref() - .map(text_to_hash::) - .transpose() - } - } - - /// A list of hashes, as hex. - pub mod hashes { - use p2panda_core::Hash; - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - - use super::{hash_text, text_to_hash}; - - pub fn serialize(hashes: &[Hash], serializer: S) -> Result { - hashes - .iter() - .map(hash_text) - .collect::>() - .serialize(serializer) - } - - pub fn deserialize<'de, D: Deserializer<'de>>( - deserializer: D, - ) -> Result, D::Error> { - Vec::::deserialize(deserializer)? - .iter() - .map(|text| text_to_hash::(text)) - .collect() - } - } - - /// A create's members, each with its role, as hex. - pub mod members { - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - - use crate::groups::Role; - - use super::{Key, key_text, text_to_key}; - - pub fn serialize( - members: &[(Key, Role)], - serializer: S, - ) -> Result { - members - .iter() - .map(|(key, role)| (key_text(key), *role)) - .collect::>() - .serialize(serializer) - } - - pub fn deserialize<'de, D: Deserializer<'de>>( - deserializer: D, - ) -> Result, D::Error> { - Vec::<(String, Role)>::deserialize(deserializer)? - .iter() - .map(|(text, role)| Ok((text_to_key::(text)?, *role))) - .collect() - } - } -} - #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { diff --git a/pkgs/id/src/groups/mod.rs b/pkgs/id/src/groups/mod.rs index 5b4e830348..327688c2b0 100644 --- a/pkgs/id/src/groups/mod.rs +++ b/pkgs/id/src/groups/mod.rs @@ -1,10 +1,20 @@ -//! Groups (Phase 2, P2.4): members and roles, the signed policy record, the templates groups are -//! created from, and friendship as a two-member group (design §5). +//! Groups (Phase 2, P2.4) — facade shim over `id-events`. //! -//! 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 -//! [`crate::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. +//! 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`. +//! +//! 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 +//! [`crate::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. @@ -14,227 +24,20 @@ //! canonical order. See [`fold`]. pub mod actions; -pub mod event; -pub mod fold; -pub mod friendship; pub mod log; -pub mod policy; pub mod warnings; pub mod worlds; -mod delegation; - -#[cfg(test)] -mod tests; - -use clap::ValueEnum; -use p2panda_core::Hash; -use serde::{Deserialize, Serialize}; - -pub use delegation::Grant; -pub use fold::{DeviceGrant, FoldError, GroupView, Outcome, Projection, Refusal, fold}; -pub use friendship::{Pair, friendship_id}; -pub use policy::{ +pub use id_events::groups::{event, fold, friendship, policy}; +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, }; - -/// The kind of a `device.add` event (P8.3). -pub const DEVICE_ADD_KIND: &str = "device.add"; - -/// The kind of a `device.revoke` event (P8.3). -pub const DEVICE_REVOKE_KIND: &str = "device.revoke"; - -/// A grant of a scope from the event's author to another account (design §7.1). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Delegate { - /// The account granted the scope. - #[serde(with = "log::wire::key")] - pub grantee: Key, - /// The access the grantee may exercise. Admin is a policy right and is not delegable. - pub scope: Role, - /// Whether the grantee may grant the scope on. Only a redelegatable grant extends a chain. - pub can_redelegate: bool, -} - -/// An account's key. Accounts are keys in this layer. -pub type Key = [u8; 32]; - -/// What a member may do, from least to most. `Admin` is a manager that may also change roles and -/// the policy record. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)] -pub enum Role { - /// Replicates ciphertext without keys. - Pull, - /// Reads content. - Read, - /// Edits content. - Write, - /// Adds and removes members. - Manage, - /// Manages, and changes roles and the policy record. - Admin, -} - -/// One signed group event, as the group layer sees it. The caller has verified it. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Event { - /// The event's ID. - #[serde(with = "log::wire::hash")] - pub id: Hash, - /// The account that signed it. - #[serde(with = "log::wire::key")] - pub author: Key, - /// The `after` hashes, as signed. - #[serde(with = "log::wire::hashes")] - pub after: Vec, - /// The group it names. A normal group's create names none. A friendship's create names the - /// friendship's derived group. - #[serde(with = "log::wire::opt_hash")] - pub group: Option, - /// What it does. - pub body: Body, -} - -/// What a group event does. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum Body { - /// Creates a group. Anyone may create one. - Create(Create), - /// Accepts a friendship request, as its other side. - Join, - /// Replaces the policy record. Admin only. - Policy(Policy), - /// Changes one member. - Member(MemberOp), - /// Grants a scope to an account. The author must hold the scope, and must reach it through a - /// chain of grants that can be passed on (design §7.2). - Delegate(Delegate), - /// Grants a scope that the grantee may use in another world (P2.7, see [`worlds`]). It is judged - /// in this event's world the way [`Body::Delegate`] is, but it gives its grantee nothing here. - Cross { - /// The grant. Its scope may be at most Write. - delegate: Delegate, - /// The world the grant names. It is not the event's own world. - world: String, - }, - /// Vetoes a grant the event has seen. The author must hold Manage and a chain (design §7). - /// From this event's causal position on, the grant and what depends on it fail. - Veto { - /// The grant's event ID. - #[serde(with = "log::wire::hash")] - grant: Hash, - }, - /// Authorizes or revokes a device on behalf of the account (P8.3). - Device(DeviceOp), -} - -/// What a device operation does (P8.3). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum DeviceOp { - /// Authorizes a device key to act on behalf of the account with the given scope. - Add { - /// The device key. - #[serde(with = "log::wire::key")] - device: Key, - /// The maximum scope the device may exercise. - scope: Role, - }, - /// Revokes a device's authorization to act on behalf of the account. - Revoke { - /// The device key. - #[serde(with = "log::wire::key")] - device: Key, - }, -} - -/// A group's creation. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Create { - /// The template the group is created from. - pub template: Template, - /// The policy record, written out in full. - pub policy: Policy, - /// The members besides the author, with their roles. A friendship lists exactly one. - #[serde(with = "log::wire::members")] - pub members: Vec<(Key, Role)>, - /// Whether both friends start as Admin. Only a friendship may set it. - pub admins_on_create: bool, -} - -/// A change to one member. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -pub enum MemberOp { - /// Adds a member with a role. - Add { - /// The member added. - #[serde(with = "log::wire::key")] - member: Key, - /// Its role. - role: Role, - }, - /// Removes a member. The author may remove itself, which is leaving. The mode is concrete in - /// replicated events; `ServerDefault` is resolved before one is recorded. - Remove { - /// The member removed. - #[serde(with = "log::wire::key")] - member: Key, - /// What happens to the removed member's grants. - mode: RemoveMode, - }, - /// Sets a member's role. Admin only. - SetRole { - /// The member whose role changes. - #[serde(with = "log::wire::key")] - member: Key, - /// Its new role. - role: Role, - }, -} - -/// Wire form accepted by the event decoder. The optional legacy `successor` is read only when an -/// event has no `mode`; new events serialize only the concrete mode. -#[derive(Deserialize)] -enum MemberOpWire { - Add { - #[serde(with = "log::wire::key")] - member: Key, - role: Role, - }, - Remove { - #[serde(with = "log::wire::key")] - member: Key, - #[serde(default)] - mode: Option, - #[serde(default, with = "log::wire::opt_key")] - successor: Option, - }, - SetRole { - #[serde(with = "log::wire::key")] - member: Key, - role: Role, - }, -} - -impl<'de> Deserialize<'de> for MemberOp { - fn deserialize>(deserializer: D) -> Result { - Ok(match MemberOpWire::deserialize(deserializer)? { - MemberOpWire::Add { member, role } => Self::Add { member, role }, - MemberOpWire::Remove { - member, - mode, - successor, - } => Self::Remove { - member, - mode: mode.unwrap_or_else(|| { - successor.map_or(RemoveMode::Revoke, |key| { - RemoveMode::Transfer(TransferOpts { - successor: RemoveSuccessor::Member(key), - }) - }) - }), - }, - MemberOpWire::SetRole { member, role } => Self::SetRole { member, role }, - }) - } -} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 770a39baf2..0f0d7c2810 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -202,14 +202,14 @@ pub mod grants; pub mod groups; pub mod helpers; pub mod hosted_binding; -pub mod idset; +pub use id_events::idset; pub mod input_framing; pub mod invite; pub mod invites; pub use id_store::issuer_rotation; pub(crate) mod key_envelope; pub mod local; -pub mod local_claims; +pub use id_events::local_claims; pub mod local_events; pub mod log_sync; mod peer_announcement; diff --git a/pkgs/id/src/pull_policy.rs b/pkgs/id/src/pull_policy.rs index 75f02662ae..27014785d1 100644 --- a/pkgs/id/src/pull_policy.rs +++ b/pkgs/id/src/pull_policy.rs @@ -1,148 +1,15 @@ -//! Who may pull a world's events from this server (P6.5, decision 11). +//! The pull policy, re-exported from `id-events`. //! -//! The policy is a local serving rule. It decides what this server sends, and a peer never sees -//! it. Nothing here goes on the wire, so two servers with different policies still sync. -//! -//! - **Open** (the default): any peer may pull the world's events. That is how sync works today. -//! - **Members**: a peer may pull only while it is a current member of the world. Membership is -//! read when each session starts, so a removed member is refused on the next pull. -//! -//! A [`PullGate`] binds a policy to one world and to the membership it is checked against. The -//! sync sessions check the gate before any event is sent. A refused peer gets no event, and the -//! refusal is clean. An open gate never reads membership. -//! -//! A gate may also carry the operator block list ([`crate::event_store::BlockList`], #2245): -//! a peer blocked by key is refused under every policy, and a gate whose world's name is a -//! blocked topic tag serves nothing. The blocks compose with the policy — they only ever -//! narrow it. Without a list attached, a gate behaves exactly as it did before the list -//! existed. The list is read on each check, so a block or an unblock lands on the next -//! session, as a membership removal does. -//! -//! This is a config setting, not a protocol rule. The policy belongs with the world's policy. The -//! server config's `[policy]` table parses it ([`crate::server_config::ServerConfig::pull_policy`]), -//! and `id serve` builds its live event-sync gate from that value -//! ([`crate::event_sync::gate`]); the node's own event store is not a world and has no membership -//! source, so `members` there refuses every pull rather than serving open. Blobs are not -//! governed here. The blob gate ([`crate::blob_gate`]) still requires membership to fetch, whatever -//! this policy says. Authorized pull is advisory: it stops an honest server from serving a -//! non-member. It does not stop re-serving, recall copies, or hide metadata. - -use std::sync::Arc; - -use iroh_base::EndpointId; +//! Step 2b of the pkgs/id crate split (#4405): the implementation of +//! this module — the policy value types and the gate — lives in +//! `id_events::pull_policy`, the sync-gating vocabulary the events +//! layer owns. This facade module holds the re-exports, the test +//! fixtures that fold through the facade's own `groups::worlds` (which +//! stays here until step 4), and the one gate test that runs against +//! the real event store, so every historical `id::pull_policy` path +//! is unchanged. -use crate::blob_gate::WorldAccess; -use crate::event_store::BlockList; - -/// Who may pull a world's events from this server. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum PullPolicy { - /// Any peer may pull. The default, and today's behaviour. - #[default] - Open, - /// Only a current member of the world may pull. - Members, -} - -impl PullPolicy { - /// Whether `peer` may pull the events of `world`. Only [`PullPolicy::Members`] reads `access`, - /// and it reads it on each call, so a removal is seen by the next call. - pub fn admits(self, access: &dyn WorldAccess, world: &str, peer: &EndpointId) -> bool { - match self { - Self::Open => true, - Self::Members => access.is_current_member(world, peer), - } - } -} - -/// A policy bound to one world, and the membership it is checked against. -#[derive(Clone)] -pub struct PullGate { - policy: PullPolicy, - world: String, - access: Arc, - /// The operator block list, when the gate's owner attached one - /// ([`PullGate::with_blocks`]). Read on each check. - blocks: Option>, -} - -impl PullGate { - /// A gate for `world` under `policy`. `access` answers membership at the time of each check. - /// No operator block list is attached; [`PullGate::with_blocks`] adds one. - #[must_use] - pub fn new( - policy: PullPolicy, - world: impl Into, - access: Arc, - ) -> Self { - Self { - policy, - world: world.into(), - access, - blocks: None, - } - } - - /// Attaches the operator block list (#2245): a peer blocked by key is - /// refused under every policy, and a gate whose world's name is a - /// blocked topic tag serves nothing. The list is consulted live, so a - /// block added after the gate was built is seen by the next check. - #[must_use] - pub fn with_blocks(mut self, blocks: Arc) -> Self { - self.blocks = Some(blocks); - self - } - - /// The world this gate serves. - #[must_use] - pub fn world(&self) -> &str { - &self.world - } - - /// Whether the operator block list blocks `peer` by key. False when - /// no list is attached. - #[must_use] - pub fn peer_blocked(&self, peer: &EndpointId) -> bool { - self.blocks - .as_ref() - .is_some_and(|blocks| blocks.peer_blocked(peer.as_bytes())) - } - - /// Whether the operator block list blocks this topic tag (raw bytes: - /// a world name, or a sync topic's hash bytes). False when no list is - /// attached. Session seams that carry a topic the gate's world does - /// not name — the `log_sync` handshake — check the tag through here. - #[must_use] - pub fn topic_tag_blocked(&self, tag: &[u8]) -> bool { - self.blocks - .as_ref() - .is_some_and(|blocks| blocks.topic_tag_blocked(tag)) - } - - /// Whether `peer` may pull this world's events now: not blocked by - /// key, the world not blocked as a topic tag, and the policy admits - /// the peer. - #[must_use] - pub fn admits(&self, peer: &EndpointId) -> bool { - !self.peer_blocked(peer) - && !self.topic_tag_blocked(self.world.as_bytes()) - && self.policy.admits(self.access.as_ref(), &self.world, peer) - } -} - -impl std::fmt::Debug for PullGate { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("PullGate") - .field("policy", &self.policy) - .field("world", &self.world) - .finish_non_exhaustive() - } -} - -/// A session the pull policy refused. No event was sent. -#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] -#[error("the pull policy refuses this peer the events of world {0:?}")] -pub struct PullRefused(pub String); +pub use id_events::pull_policy::{PullGate, PullPolicy, PullRefused}; /// Fixtures for the pull tests and the session tests: a folded world, and membership a test can /// change between two checks. @@ -324,89 +191,7 @@ pub(crate) mod testing { mod tests { use super::testing::{WORLD, docs_world, key, live}; use super::*; - - #[test] - fn test_pull_policy_defaults_to_open() { - assert_eq!(PullPolicy::default(), PullPolicy::Open); - } - - /// Open pull admits a stranger: today's behaviour, pinned. - #[test] - fn test_pull_policy_open_admits_a_non_member() { - let gate = PullGate::new( - PullPolicy::Open, - WORLD, - live(docs_world(key(1).public(), key(2).public(), false)), - ); - assert!(gate.admits(&key(9).public()), "a stranger may pull"); - assert!(gate.admits(&key(2).public()), "a member may pull"); - } - - /// The members option admits a current member, the founder included, and refuses a stranger. - #[test] - fn test_pull_policy_members_admits_only_a_current_member() { - let gate = PullGate::new( - PullPolicy::Members, - WORLD, - live(docs_world(key(1).public(), key(2).public(), false)), - ); - assert!(gate.admits(&key(2).public()), "a member"); - assert!(gate.admits(&key(1).public()), "the founder is a member too"); - assert!(!gate.admits(&key(9).public()), "a stranger is refused"); - } - - /// The check reads membership when it runs, so a removal lands on the next check. - #[test] - fn test_pull_policy_members_refuses_a_removed_member_on_the_next_check() { - let access = live(docs_world(key(1).public(), key(2).public(), false)); - let gate = PullGate::new(PullPolicy::Members, WORLD, Arc::clone(&access)); - assert!(gate.admits(&key(2).public()), "before the removal"); - access.set(docs_world(key(1).public(), key(2).public(), true)); - assert!(!gate.admits(&key(2).public()), "after the removal"); - } - - /// #2245: a peer blocked by key is refused even under the open - /// policy, which admits every other peer. The block only narrows. - #[test] - fn test_pull_gate_refuses_a_blocked_peer_under_open_policy() { - let gate = PullGate::new( - PullPolicy::Open, - WORLD, - live(docs_world(key(1).public(), key(2).public(), false)), - ) - .with_blocks(super::testing::stub_blocks( - &[*key(9).public().as_bytes()], - &[], - )); - assert!( - !gate.admits(&key(9).public()), - "the blocked peer is refused" - ); - assert!( - gate.admits(&key(2).public()), - "an unblocked peer still pulls" - ); - } - - /// #2245: a blocked topic tag is not pulled — a gate whose world is a - /// blocked tag serves nothing, to members included. - #[test] - fn test_pull_gate_refuses_every_peer_when_its_world_is_a_blocked_topic_tag() { - let gate = PullGate::new( - PullPolicy::Members, - WORLD, - live(docs_world(key(1).public(), key(2).public(), false)), - ) - .with_blocks(super::testing::stub_blocks(&[], &[WORLD])); - assert!( - !gate.admits(&key(2).public()), - "a member of a blocked topic" - ); - assert!( - !gate.admits(&key(1).public()), - "the founder of a blocked topic" - ); - } + use std::sync::Arc; /// #2245, against the real store-backed list: a permanent block /// refuses the peer, and an expired block does not — expiry is judged @@ -445,15 +230,4 @@ mod tests { assert!(gate.admits(&key(2).public()), "an unlisted peer pulls"); } - /// A gate names one world. A member of `docs` is not a member of another world. - #[test] - fn test_pull_policy_members_checks_only_the_gates_world() { - let gate = PullGate::new( - PullPolicy::Members, - "other", - live(docs_world(key(1).public(), key(2).public(), false)), - ); - assert_eq!(gate.world(), "other"); - assert!(!gate.admits(&key(2).public())); - } }