Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions pkgs/id/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions pkgs/id/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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-groups", "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-worlds", "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-groups", "crates/id-sync"]
default-members = [".", "crates/id-core", "crates/id-caps", "crates/id-store", "crates/id-events", "crates/id-groups", "crates/id-sync", "crates/id-worlds"]

# =============================================================================
# Features
Expand Down Expand Up @@ -83,6 +83,9 @@ 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 }
# Worlds-family modules extracted in step 5 of the crate split (#4408).
# Re-exported at their historical crate:: paths in src/lib.rs.
id-worlds = { path = "crates/id-worlds", 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
Expand Down
2 changes: 1 addition & 1 deletion pkgs/id/crates/id-groups/src/groups/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! 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`.
//! (`worlds`) lives in `id-worlds` since step 5 (seam 6).
//!
//! 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
Expand Down
110 changes: 110 additions & 0 deletions pkgs/id/crates/id-worlds/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
[package]
name = "id-worlds"
version = "0.1.0"
edition = "2024"
rust-version = "1.96"
description = "Worlds layer of the id crate: the world runtime, sessions, sandbox and cross-world authority (pkgs/id crate split step 5, #4408)"
license = "MIT OR Apache-2.0"

# Step 5 of the pkgs/id crate split (#3447 umbrella, #4408): the world
# family lives here. Dependencies per the design map: id-core, id-caps,
# id-store, id-events, id-groups, id-sync. This first step-5 PR brings
# the leaves that name nothing above them (the compiled-world cache,
# the line/terminal helpers), seam 6's cross-world bridge
# (`groups::worlds` — the consumer side of the groups/worlds
# relationship, per the design), and the blob gate's `FoldedWorlds`
# adapter over that bridge (parked in the facade by step 4 to move
# together with the bridge). The world core, sessions and the rest of
# the family follow in later step-5 PRs.

[features]
default = []

[dependencies]
anyhow = "1"
blake3 = "1"
id-events = { path = "../id-events", default-features = false }
id-groups = { path = "../id-groups", default-features = false }
iroh-base = "1"
iroh-blobs = "0.103"
libc = "0.2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
p2panda-core = { git = "https://github.com/p2panda/p2panda", rev = "da80c05b95269926bf58121cf6a2d3dd5ca41dfc" }
proptest = "1.12"
tempfile = "3"

[lints.rust]
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"

[lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
cargo = { level = "warn", priority = -1 }
unwrap_used = "deny"
expect_used = "deny"
panic = "deny"
unimplemented = "deny"
todo = "deny"
dbg_macro = "deny"
print_stdout = "allow"
print_stderr = "allow"
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"
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"
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"
too_many_arguments = "allow"
fn_params_excessive_bools = "allow"
struct_excessive_bools = "allow"
cognitive_complexity = "allow"
future_not_send = "allow"
assert_is_empty = "allow"
chunks_exact_to_as_chunks = "allow"
175 changes: 175 additions & 0 deletions pkgs/id/crates/id-worlds/src/blob_gate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//! The blob gate's folded-worlds adapter.
//!
//! Step 4 of the pkgs/id crate split (#4407) extracted the gate
//! itself — policy, verdicts and provider wiring — into
//! `id_groups::blob_gate`, over the [`WorldAccess`] trait the events
//! layer owns. What stayed in the facade was [`FoldedWorlds`], the
//! `WorldAccess` implementation over the folded worlds, because it
//! folds through [`crate::groups::worlds::Worlds`]: seam 6's bridge
//! file, which the design sends to the worlds crate. Step 5 moves
//! the adapter together with the bridge, here. (`FoldedWorlds`
//! cannot live in `id-groups`: that crate is below this one and
//! must not name world types.)

use std::collections::{BTreeSet, HashMap};

use iroh_base::EndpointId;
use iroh_blobs::Hash;

use id_events::world_access::WorldAccess;

use crate::groups::{Role, worlds::Worlds};

/// [`WorldAccess`] over the folded worlds.
///
/// Membership is the world's own authority, as [`Worlds::holds_here`] gives it: a member of its
/// group, or a grant in its own chains. A crossing from another world does not count.
///
/// The reference index maps a blob hash to the worlds that name it. Nothing in the store writes
/// it yet. Artifacts carry SHA-256 hashes, not BLAKE3 blob hashes, and only WASM modules are
/// pinned, without a record of their world. So the index is passed in, and a hash it does not
/// hold is unreferenced, which refuses it to every requester.
#[derive(Debug)]
pub struct FoldedWorlds {
worlds: Worlds,
references: HashMap<Hash, BTreeSet<String>>,
}

impl FoldedWorlds {
/// Pairs the folded worlds with a reference index.
pub const fn new(worlds: Worlds, references: HashMap<Hash, BTreeSet<String>>) -> Self {
Self { worlds, references }
}
}

impl WorldAccess for FoldedWorlds {
fn is_current_member(&self, world: &str, requester: &EndpointId) -> bool {
self.worlds
.holds_here(world, *requester.as_bytes(), Role::Pull)
}

fn worlds_referencing(&self, hash: &Hash) -> Vec<String> {
self.references
.get(hash)
.map(|worlds| worlds.iter().cloned().collect())
.unwrap_or_default()
}
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use std::collections::{BTreeMap, HashMap};

use iroh_base::SecretKey;

use super::*;
use crate::groups::policy::Policy;
use crate::groups::{Body, Create, Event, MemberOp, Template};
use id_groups::blob_gate::{BlobPolicy, Request, decide};

fn id(n: u8) -> EndpointId {
SecretKey::from_bytes(&[n; 32]).public()
}

fn blob(n: u8) -> Hash {
Hash::from_bytes([n; 32])
}

/// 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 {
let (founder, member) = (*founder.as_bytes(), *member.as_bytes());
let create = p2panda_core::Hash::digest(b"create");
let add = p2panda_core::Hash::digest(b"add");
let remove = p2panda_core::Hash::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 worlds = BTreeMap::from([("docs".to_owned(), events)]);
Worlds::fold(&worlds, BTreeMap::new()).unwrap()
}

/// The folded `docs` world, with `hash` indexed as named by `docs`.
fn gate(worlds: Worlds, hash: Hash) -> FoldedWorlds {
let refs = HashMap::from([(hash, BTreeSet::from(["docs".to_owned()]))]);
FoldedWorlds::new(worlds, refs)
}

#[test]
fn folded_membership_admits_a_member_and_refuses_a_stranger() {
let g = gate(folded(id(1), id(2), false), blob(9));
let p = BlobPolicy::default();
assert!(decide(&g, &p, &id(2), &blob(9), Request::Fetch));
// The founder is Admin, so is a member too.
assert!(decide(&g, &p, &id(1), &blob(9), Request::Fetch));
assert!(!decide(&g, &p, &id(3), &blob(9), Request::Fetch));
}

#[test]
fn a_removed_member_loses_fetch_on_the_folded_world() {
let g = gate(folded(id(1), id(2), true), blob(9));
assert!(!decide(
&g,
&BlobPolicy::default(),
&id(2),
&blob(9),
Request::Fetch
));
}

#[test]
fn an_unindexed_blob_is_refused_even_to_a_member() {
let g = gate(folded(id(1), id(2), false), blob(9));
let p = BlobPolicy::default().with_observe();
assert!(!decide(&g, &p, &id(2), &blob(5), Request::Fetch));
assert!(!decide(&g, &p, &id(2), &blob(5), Request::Observe));
}

#[test]
fn observe_over_the_folded_world_follows_the_policy() {
let g = gate(folded(id(1), id(2), false), blob(9));
assert!(!decide(
&g,
&BlobPolicy::default(),
&id(2),
&blob(9),
Request::Observe
));
let p = BlobPolicy::default().with_observe();
assert!(decide(&g, &p, &id(2), &blob(9), Request::Observe));
}
}
26 changes: 26 additions & 0 deletions pkgs/id/crates/id-worlds/src/groups/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Groups, as the worlds layer sees them.
//!
//! 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 —
//! the same re-exports `id_groups::groups` carries. What lives here
//! is [`worlds`]: seam 6 of the crate-split design sends the
//! groups→worlds bridge to the worlds crate, because the bridge is
//! the consumer side of the relationship (the group layer must not
//! know worlds exist).

pub mod worlds;

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};
Loading
Loading